Update .bashrc
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-html / node_modules / typescript / lib / typingsInstaller.js
1 /*! *****************************************************************************
2 Copyright (c) Microsoft Corporation. All rights reserved.
3 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4 this file except in compliance with the License. You may obtain a copy of the
5 License at http://www.apache.org/licenses/LICENSE-2.0
6
7 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
8 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
9 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
10 MERCHANTABLITY OR NON-INFRINGEMENT.
11
12 See the Apache Version 2.0 License for specific language governing permissions
13 and limitations under the License.
14 ***************************************************************************** */
15
16
17 "use strict";
18 var __spreadArray = (this && this.__spreadArray) || function (to, from) {
19     for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
20         to[j] = from[i];
21     return to;
22 };
23 var __assign = (this && this.__assign) || function () {
24     __assign = Object.assign || function(t) {
25         for (var s, i = 1, n = arguments.length; i < n; i++) {
26             s = arguments[i];
27             for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
28                 t[p] = s[p];
29         }
30         return t;
31     };
32     return __assign.apply(this, arguments);
33 };
34 var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
35     if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
36     return cooked;
37 };
38 var __generator = (this && this.__generator) || function (thisArg, body) {
39     var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
40     return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
41     function verb(n) { return function (v) { return step([n, v]); }; }
42     function step(op) {
43         if (f) throw new TypeError("Generator is already executing.");
44         while (_) try {
45             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;
46             if (y = 0, t) op = [op[0] & 2, t.value];
47             switch (op[0]) {
48                 case 0: case 1: t = op; break;
49                 case 4: _.label++; return { value: op[1], done: false };
50                 case 5: _.label++; y = op[1]; op = [0]; continue;
51                 case 7: op = _.ops.pop(); _.trys.pop(); continue;
52                 default:
53                     if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
54                     if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
55                     if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
56                     if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
57                     if (t[2]) _.ops.pop();
58                     _.trys.pop(); continue;
59             }
60             op = body.call(thisArg, _);
61         } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
62         if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
63     }
64 };
65 var __extends = (this && this.__extends) || (function () {
66     var extendStatics = function (d, b) {
67         extendStatics = Object.setPrototypeOf ||
68             ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
69             function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
70         return extendStatics(d, b);
71     };
72     return function (d, b) {
73         if (typeof b !== "function" && b !== null)
74             throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
75         extendStatics(d, b);
76         function __() { this.constructor = d; }
77         d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
78     };
79 })();
80 var ts;
81 (function (ts) {
82     // WARNING: The script `configurePrerelease.ts` uses a regexp to parse out these values.
83     // If changing the text in this section, be sure to test `configurePrerelease` too.
84     ts.versionMajorMinor = "4.2";
85     // The following is baselined as a literal template type without intervention
86     /** The version of the TypeScript compiler release */
87     // eslint-disable-next-line @typescript-eslint/no-inferrable-types
88     ts.version = "4.2.3";
89     /* @internal */
90     var Comparison;
91     (function (Comparison) {
92         Comparison[Comparison["LessThan"] = -1] = "LessThan";
93         Comparison[Comparison["EqualTo"] = 0] = "EqualTo";
94         Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
95     })(Comparison = ts.Comparison || (ts.Comparison = {}));
96     /* @internal */
97     var NativeCollections;
98     (function (NativeCollections) {
99         /**
100          * Returns the native Map implementation if it is available and compatible (i.e. supports iteration).
101          */
102         function tryGetNativeMap() {
103             // Internet Explorer's Map doesn't support iteration, so don't use it.
104             // eslint-disable-next-line no-in-operator
105             return typeof Map !== "undefined" && "entries" in Map.prototype && new Map([[0, 0]]).size === 1 ? Map : undefined;
106         }
107         NativeCollections.tryGetNativeMap = tryGetNativeMap;
108         /**
109          * Returns the native Set implementation if it is available and compatible (i.e. supports iteration).
110          */
111         function tryGetNativeSet() {
112             // Internet Explorer's Set doesn't support iteration, so don't use it.
113             // eslint-disable-next-line no-in-operator
114             return typeof Set !== "undefined" && "entries" in Set.prototype && new Set([0]).size === 1 ? Set : undefined;
115         }
116         NativeCollections.tryGetNativeSet = tryGetNativeSet;
117     })(NativeCollections = ts.NativeCollections || (ts.NativeCollections = {}));
118 })(ts || (ts = {}));
119 /* @internal */
120 var ts;
121 (function (ts) {
122     function getCollectionImplementation(name, nativeFactory, shimFactory) {
123         var _a;
124         // NOTE: ts.ShimCollections will be defined for typescriptServices.js but not for tsc.js, so we must test for it.
125         var constructor = (_a = ts.NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](getIterator);
126         if (constructor)
127             return constructor;
128         throw new Error("TypeScript requires an environment that provides a compatible native " + name + " implementation.");
129     }
130     ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim");
131     ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim");
132     function getIterator(iterable) {
133         if (iterable) {
134             if (isArray(iterable))
135                 return arrayIterator(iterable);
136             if (iterable instanceof ts.Map)
137                 return iterable.entries();
138             if (iterable instanceof ts.Set)
139                 return iterable.values();
140             throw new Error("Iteration not supported.");
141         }
142     }
143     ts.getIterator = getIterator;
144     ts.emptyArray = [];
145     ts.emptyMap = new ts.Map();
146     ts.emptySet = new ts.Set();
147     function createMap() {
148         return new ts.Map();
149     }
150     ts.createMap = createMap;
151     /**
152      * Create a new map from a template object is provided, the map will copy entries from it.
153      * @deprecated Use `new Map(getEntries(template))` instead.
154      */
155     function createMapFromTemplate(template) {
156         var map = new ts.Map();
157         // Copies keys/values from template. Note that for..in will not throw if
158         // template is undefined, and instead will just exit the loop.
159         for (var key in template) {
160             if (hasOwnProperty.call(template, key)) {
161                 map.set(key, template[key]);
162             }
163         }
164         return map;
165     }
166     ts.createMapFromTemplate = createMapFromTemplate;
167     function length(array) {
168         return array ? array.length : 0;
169     }
170     ts.length = length;
171     /**
172      * Iterates through 'array' by index and performs the callback on each element of array until the callback
173      * returns a truthy value, then returns that value.
174      * If no such value is found, the callback is applied to each element of array and undefined is returned.
175      */
176     function forEach(array, callback) {
177         if (array) {
178             for (var i = 0; i < array.length; i++) {
179                 var result = callback(array[i], i);
180                 if (result) {
181                     return result;
182                 }
183             }
184         }
185         return undefined;
186     }
187     ts.forEach = forEach;
188     /**
189      * Like `forEach`, but iterates in reverse order.
190      */
191     function forEachRight(array, callback) {
192         if (array) {
193             for (var i = array.length - 1; i >= 0; i--) {
194                 var result = callback(array[i], i);
195                 if (result) {
196                     return result;
197                 }
198             }
199         }
200         return undefined;
201     }
202     ts.forEachRight = forEachRight;
203     /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */
204     function firstDefined(array, callback) {
205         if (array === undefined) {
206             return undefined;
207         }
208         for (var i = 0; i < array.length; i++) {
209             var result = callback(array[i], i);
210             if (result !== undefined) {
211                 return result;
212             }
213         }
214         return undefined;
215     }
216     ts.firstDefined = firstDefined;
217     function firstDefinedIterator(iter, callback) {
218         while (true) {
219             var iterResult = iter.next();
220             if (iterResult.done) {
221                 return undefined;
222             }
223             var result = callback(iterResult.value);
224             if (result !== undefined) {
225                 return result;
226             }
227         }
228     }
229     ts.firstDefinedIterator = firstDefinedIterator;
230     function reduceLeftIterator(iterator, f, initial) {
231         var result = initial;
232         if (iterator) {
233             for (var step = iterator.next(), pos = 0; !step.done; step = iterator.next(), pos++) {
234                 result = f(result, step.value, pos);
235             }
236         }
237         return result;
238     }
239     ts.reduceLeftIterator = reduceLeftIterator;
240     function zipWith(arrayA, arrayB, callback) {
241         var result = [];
242         ts.Debug.assertEqual(arrayA.length, arrayB.length);
243         for (var i = 0; i < arrayA.length; i++) {
244             result.push(callback(arrayA[i], arrayB[i], i));
245         }
246         return result;
247     }
248     ts.zipWith = zipWith;
249     function zipToIterator(arrayA, arrayB) {
250         ts.Debug.assertEqual(arrayA.length, arrayB.length);
251         var i = 0;
252         return {
253             next: function () {
254                 if (i === arrayA.length) {
255                     return { value: undefined, done: true };
256                 }
257                 i++;
258                 return { value: [arrayA[i - 1], arrayB[i - 1]], done: false };
259             }
260         };
261     }
262     ts.zipToIterator = zipToIterator;
263     function zipToMap(keys, values) {
264         ts.Debug.assert(keys.length === values.length);
265         var map = new ts.Map();
266         for (var i = 0; i < keys.length; ++i) {
267             map.set(keys[i], values[i]);
268         }
269         return map;
270     }
271     ts.zipToMap = zipToMap;
272     /**
273      * Creates a new array with `element` interspersed in between each element of `input`
274      * if there is more than 1 value in `input`. Otherwise, returns the existing array.
275      */
276     function intersperse(input, element) {
277         if (input.length <= 1) {
278             return input;
279         }
280         var result = [];
281         for (var i = 0, n = input.length; i < n; i++) {
282             if (i)
283                 result.push(element);
284             result.push(input[i]);
285         }
286         return result;
287     }
288     ts.intersperse = intersperse;
289     /**
290      * Iterates through `array` by index and performs the callback on each element of array until the callback
291      * returns a falsey value, then returns false.
292      * If no such value is found, the callback is applied to each element of array and `true` is returned.
293      */
294     function every(array, callback) {
295         if (array) {
296             for (var i = 0; i < array.length; i++) {
297                 if (!callback(array[i], i)) {
298                     return false;
299                 }
300             }
301         }
302         return true;
303     }
304     ts.every = every;
305     function find(array, predicate) {
306         for (var i = 0; i < array.length; i++) {
307             var value = array[i];
308             if (predicate(value, i)) {
309                 return value;
310             }
311         }
312         return undefined;
313     }
314     ts.find = find;
315     function findLast(array, predicate) {
316         for (var i = array.length - 1; i >= 0; i--) {
317             var value = array[i];
318             if (predicate(value, i)) {
319                 return value;
320             }
321         }
322         return undefined;
323     }
324     ts.findLast = findLast;
325     /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
326     function findIndex(array, predicate, startIndex) {
327         for (var i = startIndex || 0; i < array.length; i++) {
328             if (predicate(array[i], i)) {
329                 return i;
330             }
331         }
332         return -1;
333     }
334     ts.findIndex = findIndex;
335     function findLastIndex(array, predicate, startIndex) {
336         for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) {
337             if (predicate(array[i], i)) {
338                 return i;
339             }
340         }
341         return -1;
342     }
343     ts.findLastIndex = findLastIndex;
344     /**
345      * Returns the first truthy result of `callback`, or else fails.
346      * This is like `forEach`, but never returns undefined.
347      */
348     function findMap(array, callback) {
349         for (var i = 0; i < array.length; i++) {
350             var result = callback(array[i], i);
351             if (result) {
352                 return result;
353             }
354         }
355         return ts.Debug.fail();
356     }
357     ts.findMap = findMap;
358     function contains(array, value, equalityComparer) {
359         if (equalityComparer === void 0) { equalityComparer = equateValues; }
360         if (array) {
361             for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
362                 var v = array_1[_i];
363                 if (equalityComparer(v, value)) {
364                     return true;
365                 }
366             }
367         }
368         return false;
369     }
370     ts.contains = contains;
371     function arraysEqual(a, b, equalityComparer) {
372         if (equalityComparer === void 0) { equalityComparer = equateValues; }
373         return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); });
374     }
375     ts.arraysEqual = arraysEqual;
376     function indexOfAnyCharCode(text, charCodes, start) {
377         for (var i = start || 0; i < text.length; i++) {
378             if (contains(charCodes, text.charCodeAt(i))) {
379                 return i;
380             }
381         }
382         return -1;
383     }
384     ts.indexOfAnyCharCode = indexOfAnyCharCode;
385     function countWhere(array, predicate) {
386         var count = 0;
387         if (array) {
388             for (var i = 0; i < array.length; i++) {
389                 var v = array[i];
390                 if (predicate(v, i)) {
391                     count++;
392                 }
393             }
394         }
395         return count;
396     }
397     ts.countWhere = countWhere;
398     function filter(array, f) {
399         if (array) {
400             var len = array.length;
401             var i = 0;
402             while (i < len && f(array[i]))
403                 i++;
404             if (i < len) {
405                 var result = array.slice(0, i);
406                 i++;
407                 while (i < len) {
408                     var item = array[i];
409                     if (f(item)) {
410                         result.push(item);
411                     }
412                     i++;
413                 }
414                 return result;
415             }
416         }
417         return array;
418     }
419     ts.filter = filter;
420     function filterMutate(array, f) {
421         var outIndex = 0;
422         for (var i = 0; i < array.length; i++) {
423             if (f(array[i], i, array)) {
424                 array[outIndex] = array[i];
425                 outIndex++;
426             }
427         }
428         array.length = outIndex;
429     }
430     ts.filterMutate = filterMutate;
431     function clear(array) {
432         array.length = 0;
433     }
434     ts.clear = clear;
435     function map(array, f) {
436         var result;
437         if (array) {
438             result = [];
439             for (var i = 0; i < array.length; i++) {
440                 result.push(f(array[i], i));
441             }
442         }
443         return result;
444     }
445     ts.map = map;
446     function mapIterator(iter, mapFn) {
447         return {
448             next: function () {
449                 var iterRes = iter.next();
450                 return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false };
451             }
452         };
453     }
454     ts.mapIterator = mapIterator;
455     function sameMap(array, f) {
456         if (array) {
457             for (var i = 0; i < array.length; i++) {
458                 var item = array[i];
459                 var mapped = f(item, i);
460                 if (item !== mapped) {
461                     var result = array.slice(0, i);
462                     result.push(mapped);
463                     for (i++; i < array.length; i++) {
464                         result.push(f(array[i], i));
465                     }
466                     return result;
467                 }
468             }
469         }
470         return array;
471     }
472     ts.sameMap = sameMap;
473     /**
474      * Flattens an array containing a mix of array or non-array elements.
475      *
476      * @param array The array to flatten.
477      */
478     function flatten(array) {
479         var result = [];
480         for (var _i = 0, array_2 = array; _i < array_2.length; _i++) {
481             var v = array_2[_i];
482             if (v) {
483                 if (isArray(v)) {
484                     addRange(result, v);
485                 }
486                 else {
487                     result.push(v);
488                 }
489             }
490         }
491         return result;
492     }
493     ts.flatten = flatten;
494     /**
495      * Maps an array. If the mapped value is an array, it is spread into the result.
496      *
497      * @param array The array to map.
498      * @param mapfn The callback used to map the result into one or more values.
499      */
500     function flatMap(array, mapfn) {
501         var result;
502         if (array) {
503             for (var i = 0; i < array.length; i++) {
504                 var v = mapfn(array[i], i);
505                 if (v) {
506                     if (isArray(v)) {
507                         result = addRange(result, v);
508                     }
509                     else {
510                         result = append(result, v);
511                     }
512                 }
513             }
514         }
515         return result || ts.emptyArray;
516     }
517     ts.flatMap = flatMap;
518     function flatMapToMutable(array, mapfn) {
519         var result = [];
520         if (array) {
521             for (var i = 0; i < array.length; i++) {
522                 var v = mapfn(array[i], i);
523                 if (v) {
524                     if (isArray(v)) {
525                         addRange(result, v);
526                     }
527                     else {
528                         result.push(v);
529                     }
530                 }
531             }
532         }
533         return result;
534     }
535     ts.flatMapToMutable = flatMapToMutable;
536     function flatMapIterator(iter, mapfn) {
537         var first = iter.next();
538         if (first.done) {
539             return ts.emptyIterator;
540         }
541         var currentIter = getIterator(first.value);
542         return {
543             next: function () {
544                 while (true) {
545                     var currentRes = currentIter.next();
546                     if (!currentRes.done) {
547                         return currentRes;
548                     }
549                     var iterRes = iter.next();
550                     if (iterRes.done) {
551                         return iterRes;
552                     }
553                     currentIter = getIterator(iterRes.value);
554                 }
555             },
556         };
557         function getIterator(x) {
558             var res = mapfn(x);
559             return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res;
560         }
561     }
562     ts.flatMapIterator = flatMapIterator;
563     function sameFlatMap(array, mapfn) {
564         var result;
565         if (array) {
566             for (var i = 0; i < array.length; i++) {
567                 var item = array[i];
568                 var mapped = mapfn(item, i);
569                 if (result || item !== mapped || isArray(mapped)) {
570                     if (!result) {
571                         result = array.slice(0, i);
572                     }
573                     if (isArray(mapped)) {
574                         addRange(result, mapped);
575                     }
576                     else {
577                         result.push(mapped);
578                     }
579                 }
580             }
581         }
582         return result || array;
583     }
584     ts.sameFlatMap = sameFlatMap;
585     function mapAllOrFail(array, mapFn) {
586         var result = [];
587         for (var i = 0; i < array.length; i++) {
588             var mapped = mapFn(array[i], i);
589             if (mapped === undefined) {
590                 return undefined;
591             }
592             result.push(mapped);
593         }
594         return result;
595     }
596     ts.mapAllOrFail = mapAllOrFail;
597     function mapDefined(array, mapFn) {
598         var result = [];
599         if (array) {
600             for (var i = 0; i < array.length; i++) {
601                 var mapped = mapFn(array[i], i);
602                 if (mapped !== undefined) {
603                     result.push(mapped);
604                 }
605             }
606         }
607         return result;
608     }
609     ts.mapDefined = mapDefined;
610     function mapDefinedIterator(iter, mapFn) {
611         return {
612             next: function () {
613                 while (true) {
614                     var res = iter.next();
615                     if (res.done) {
616                         return res;
617                     }
618                     var value = mapFn(res.value);
619                     if (value !== undefined) {
620                         return { value: value, done: false };
621                     }
622                 }
623             }
624         };
625     }
626     ts.mapDefinedIterator = mapDefinedIterator;
627     function mapDefinedEntries(map, f) {
628         if (!map) {
629             return undefined;
630         }
631         var result = new ts.Map();
632         map.forEach(function (value, key) {
633             var entry = f(key, value);
634             if (entry !== undefined) {
635                 var newKey = entry[0], newValue = entry[1];
636                 if (newKey !== undefined && newValue !== undefined) {
637                     result.set(newKey, newValue);
638                 }
639             }
640         });
641         return result;
642     }
643     ts.mapDefinedEntries = mapDefinedEntries;
644     function mapDefinedValues(set, f) {
645         if (set) {
646             var result_1 = new ts.Set();
647             set.forEach(function (value) {
648                 var newValue = f(value);
649                 if (newValue !== undefined) {
650                     result_1.add(newValue);
651                 }
652             });
653             return result_1;
654         }
655     }
656     ts.mapDefinedValues = mapDefinedValues;
657     function getOrUpdate(map, key, callback) {
658         if (map.has(key)) {
659             return map.get(key);
660         }
661         var value = callback();
662         map.set(key, value);
663         return value;
664     }
665     ts.getOrUpdate = getOrUpdate;
666     function tryAddToSet(set, value) {
667         if (!set.has(value)) {
668             set.add(value);
669             return true;
670         }
671         return false;
672     }
673     ts.tryAddToSet = tryAddToSet;
674     ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } };
675     function singleIterator(value) {
676         var done = false;
677         return {
678             next: function () {
679                 var wasDone = done;
680                 done = true;
681                 return wasDone ? { value: undefined, done: true } : { value: value, done: false };
682             }
683         };
684     }
685     ts.singleIterator = singleIterator;
686     function spanMap(array, keyfn, mapfn) {
687         var result;
688         if (array) {
689             result = [];
690             var len = array.length;
691             var previousKey = void 0;
692             var key = void 0;
693             var start = 0;
694             var pos = 0;
695             while (start < len) {
696                 while (pos < len) {
697                     var value = array[pos];
698                     key = keyfn(value, pos);
699                     if (pos === 0) {
700                         previousKey = key;
701                     }
702                     else if (key !== previousKey) {
703                         break;
704                     }
705                     pos++;
706                 }
707                 if (start < pos) {
708                     var v = mapfn(array.slice(start, pos), previousKey, start, pos);
709                     if (v) {
710                         result.push(v);
711                     }
712                     start = pos;
713                 }
714                 previousKey = key;
715                 pos++;
716             }
717         }
718         return result;
719     }
720     ts.spanMap = spanMap;
721     function mapEntries(map, f) {
722         if (!map) {
723             return undefined;
724         }
725         var result = new ts.Map();
726         map.forEach(function (value, key) {
727             var _a = f(key, value), newKey = _a[0], newValue = _a[1];
728             result.set(newKey, newValue);
729         });
730         return result;
731     }
732     ts.mapEntries = mapEntries;
733     function some(array, predicate) {
734         if (array) {
735             if (predicate) {
736                 for (var _i = 0, array_3 = array; _i < array_3.length; _i++) {
737                     var v = array_3[_i];
738                     if (predicate(v)) {
739                         return true;
740                     }
741                 }
742             }
743             else {
744                 return array.length > 0;
745             }
746         }
747         return false;
748     }
749     ts.some = some;
750     /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */
751     function getRangesWhere(arr, pred, cb) {
752         var start;
753         for (var i = 0; i < arr.length; i++) {
754             if (pred(arr[i])) {
755                 start = start === undefined ? i : start;
756             }
757             else {
758                 if (start !== undefined) {
759                     cb(start, i);
760                     start = undefined;
761                 }
762             }
763         }
764         if (start !== undefined)
765             cb(start, arr.length);
766     }
767     ts.getRangesWhere = getRangesWhere;
768     function concatenate(array1, array2) {
769         if (!some(array2))
770             return array1;
771         if (!some(array1))
772             return array2;
773         return __spreadArray(__spreadArray([], array1), array2);
774     }
775     ts.concatenate = concatenate;
776     function selectIndex(_, i) {
777         return i;
778     }
779     function indicesOf(array) {
780         return array.map(selectIndex);
781     }
782     ts.indicesOf = indicesOf;
783     function deduplicateRelational(array, equalityComparer, comparer) {
784         // Perform a stable sort of the array. This ensures the first entry in a list of
785         // duplicates remains the first entry in the result.
786         var indices = indicesOf(array);
787         stableSortIndices(array, indices, comparer);
788         var last = array[indices[0]];
789         var deduplicated = [indices[0]];
790         for (var i = 1; i < indices.length; i++) {
791             var index = indices[i];
792             var item = array[index];
793             if (!equalityComparer(last, item)) {
794                 deduplicated.push(index);
795                 last = item;
796             }
797         }
798         // restore original order
799         deduplicated.sort();
800         return deduplicated.map(function (i) { return array[i]; });
801     }
802     function deduplicateEquality(array, equalityComparer) {
803         var result = [];
804         for (var _i = 0, array_4 = array; _i < array_4.length; _i++) {
805             var item = array_4[_i];
806             pushIfUnique(result, item, equalityComparer);
807         }
808         return result;
809     }
810     /**
811      * Deduplicates an unsorted array.
812      * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
813      * @param comparer An optional `Comparer` used to sort entries before comparison, though the
814      * result will remain in the original order in `array`.
815      */
816     function deduplicate(array, equalityComparer, comparer) {
817         return array.length === 0 ? [] :
818             array.length === 1 ? array.slice() :
819                 comparer ? deduplicateRelational(array, equalityComparer, comparer) :
820                     deduplicateEquality(array, equalityComparer);
821     }
822     ts.deduplicate = deduplicate;
823     /**
824      * Deduplicates an array that has already been sorted.
825      */
826     function deduplicateSorted(array, comparer) {
827         if (array.length === 0)
828             return ts.emptyArray;
829         var last = array[0];
830         var deduplicated = [last];
831         for (var i = 1; i < array.length; i++) {
832             var next = array[i];
833             switch (comparer(next, last)) {
834                 // equality comparison
835                 case true:
836                 // relational comparison
837                 // falls through
838                 case 0 /* EqualTo */:
839                     continue;
840                 case -1 /* LessThan */:
841                     // If `array` is sorted, `next` should **never** be less than `last`.
842                     return ts.Debug.fail("Array is unsorted.");
843             }
844             deduplicated.push(last = next);
845         }
846         return deduplicated;
847     }
848     function insertSorted(array, insert, compare) {
849         if (array.length === 0) {
850             array.push(insert);
851             return;
852         }
853         var insertIndex = binarySearch(array, insert, identity, compare);
854         if (insertIndex < 0) {
855             array.splice(~insertIndex, 0, insert);
856         }
857     }
858     ts.insertSorted = insertSorted;
859     function sortAndDeduplicate(array, comparer, equalityComparer) {
860         return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive);
861     }
862     ts.sortAndDeduplicate = sortAndDeduplicate;
863     function arrayIsSorted(array, comparer) {
864         if (array.length < 2)
865             return true;
866         var prevElement = array[0];
867         for (var _i = 0, _a = array.slice(1); _i < _a.length; _i++) {
868             var element = _a[_i];
869             if (comparer(prevElement, element) === 1 /* GreaterThan */) {
870                 return false;
871             }
872             prevElement = element;
873         }
874         return true;
875     }
876     ts.arrayIsSorted = arrayIsSorted;
877     function arrayIsEqualTo(array1, array2, equalityComparer) {
878         if (equalityComparer === void 0) { equalityComparer = equateValues; }
879         if (!array1 || !array2) {
880             return array1 === array2;
881         }
882         if (array1.length !== array2.length) {
883             return false;
884         }
885         for (var i = 0; i < array1.length; i++) {
886             if (!equalityComparer(array1[i], array2[i], i)) {
887                 return false;
888             }
889         }
890         return true;
891     }
892     ts.arrayIsEqualTo = arrayIsEqualTo;
893     function compact(array) {
894         var result;
895         if (array) {
896             for (var i = 0; i < array.length; i++) {
897                 var v = array[i];
898                 if (result || !v) {
899                     if (!result) {
900                         result = array.slice(0, i);
901                     }
902                     if (v) {
903                         result.push(v);
904                     }
905                 }
906             }
907         }
908         return result || array;
909     }
910     ts.compact = compact;
911     /**
912      * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that
913      * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted
914      * based on the provided comparer.
915      */
916     function relativeComplement(arrayA, arrayB, comparer) {
917         if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0)
918             return arrayB;
919         var result = [];
920         loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) {
921             if (offsetB > 0) {
922                 // Ensure `arrayB` is properly sorted.
923                 ts.Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */);
924             }
925             loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) {
926                 if (offsetA > startA) {
927                     // Ensure `arrayA` is properly sorted. We only need to perform this check if
928                     // `offsetA` has changed since we entered the loop.
929                     ts.Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */);
930                 }
931                 switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
932                     case -1 /* LessThan */:
933                         // If B is less than A, B does not exist in arrayA. Add B to the result and
934                         // move to the next element in arrayB without changing the current position
935                         // in arrayA.
936                         result.push(arrayB[offsetB]);
937                         continue loopB;
938                     case 0 /* EqualTo */:
939                         // If B is equal to A, B exists in arrayA. Move to the next element in
940                         // arrayB without adding B to the result or changing the current position
941                         // in arrayA.
942                         continue loopB;
943                     case 1 /* GreaterThan */:
944                         // If B is greater than A, we need to keep looking for B in arrayA. Move to
945                         // the next element in arrayA and recheck.
946                         continue loopA;
947                 }
948             }
949         }
950         return result;
951     }
952     ts.relativeComplement = relativeComplement;
953     function sum(array, prop) {
954         var result = 0;
955         for (var _i = 0, array_5 = array; _i < array_5.length; _i++) {
956             var v = array_5[_i];
957             result += v[prop];
958         }
959         return result;
960     }
961     ts.sum = sum;
962     function append(to, value) {
963         if (value === undefined)
964             return to;
965         if (to === undefined)
966             return [value];
967         to.push(value);
968         return to;
969     }
970     ts.append = append;
971     function combine(xs, ys) {
972         if (xs === undefined)
973             return ys;
974         if (ys === undefined)
975             return xs;
976         if (isArray(xs))
977             return isArray(ys) ? concatenate(xs, ys) : append(xs, ys);
978         if (isArray(ys))
979             return append(ys, xs);
980         return [xs, ys];
981     }
982     ts.combine = combine;
983     /**
984      * Gets the actual offset into an array for a relative offset. Negative offsets indicate a
985      * position offset from the end of the array.
986      */
987     function toOffset(array, offset) {
988         return offset < 0 ? array.length + offset : offset;
989     }
990     function addRange(to, from, start, end) {
991         if (from === undefined || from.length === 0)
992             return to;
993         if (to === undefined)
994             return from.slice(start, end);
995         start = start === undefined ? 0 : toOffset(from, start);
996         end = end === undefined ? from.length : toOffset(from, end);
997         for (var i = start; i < end && i < from.length; i++) {
998             if (from[i] !== undefined) {
999                 to.push(from[i]);
1000             }
1001         }
1002         return to;
1003     }
1004     ts.addRange = addRange;
1005     /**
1006      * @return Whether the value was added.
1007      */
1008     function pushIfUnique(array, toAdd, equalityComparer) {
1009         if (contains(array, toAdd, equalityComparer)) {
1010             return false;
1011         }
1012         else {
1013             array.push(toAdd);
1014             return true;
1015         }
1016     }
1017     ts.pushIfUnique = pushIfUnique;
1018     /**
1019      * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array.
1020      */
1021     function appendIfUnique(array, toAdd, equalityComparer) {
1022         if (array) {
1023             pushIfUnique(array, toAdd, equalityComparer);
1024             return array;
1025         }
1026         else {
1027             return [toAdd];
1028         }
1029     }
1030     ts.appendIfUnique = appendIfUnique;
1031     function stableSortIndices(array, indices, comparer) {
1032         // sort indices by value then position
1033         indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); });
1034     }
1035     /**
1036      * Returns a new sorted array.
1037      */
1038     function sort(array, comparer) {
1039         return (array.length === 0 ? array : array.slice().sort(comparer));
1040     }
1041     ts.sort = sort;
1042     function arrayIterator(array) {
1043         var i = 0;
1044         return { next: function () {
1045                 if (i === array.length) {
1046                     return { value: undefined, done: true };
1047                 }
1048                 else {
1049                     i++;
1050                     return { value: array[i - 1], done: false };
1051                 }
1052             } };
1053     }
1054     ts.arrayIterator = arrayIterator;
1055     function arrayReverseIterator(array) {
1056         var i = array.length;
1057         return {
1058             next: function () {
1059                 if (i === 0) {
1060                     return { value: undefined, done: true };
1061                 }
1062                 else {
1063                     i--;
1064                     return { value: array[i], done: false };
1065                 }
1066             }
1067         };
1068     }
1069     ts.arrayReverseIterator = arrayReverseIterator;
1070     /**
1071      * Stable sort of an array. Elements equal to each other maintain their relative position in the array.
1072      */
1073     function stableSort(array, comparer) {
1074         var indices = indicesOf(array);
1075         stableSortIndices(array, indices, comparer);
1076         return indices.map(function (i) { return array[i]; });
1077     }
1078     ts.stableSort = stableSort;
1079     function rangeEquals(array1, array2, pos, end) {
1080         while (pos < end) {
1081             if (array1[pos] !== array2[pos]) {
1082                 return false;
1083             }
1084             pos++;
1085         }
1086         return true;
1087     }
1088     ts.rangeEquals = rangeEquals;
1089     /**
1090      * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise.
1091      * A negative offset indicates the element should be retrieved from the end of the array.
1092      */
1093     function elementAt(array, offset) {
1094         if (array) {
1095             offset = toOffset(array, offset);
1096             if (offset < array.length) {
1097                 return array[offset];
1098             }
1099         }
1100         return undefined;
1101     }
1102     ts.elementAt = elementAt;
1103     /**
1104      * Returns the first element of an array if non-empty, `undefined` otherwise.
1105      */
1106     function firstOrUndefined(array) {
1107         return array.length === 0 ? undefined : array[0];
1108     }
1109     ts.firstOrUndefined = firstOrUndefined;
1110     function first(array) {
1111         ts.Debug.assert(array.length !== 0);
1112         return array[0];
1113     }
1114     ts.first = first;
1115     /**
1116      * Returns the last element of an array if non-empty, `undefined` otherwise.
1117      */
1118     function lastOrUndefined(array) {
1119         return array.length === 0 ? undefined : array[array.length - 1];
1120     }
1121     ts.lastOrUndefined = lastOrUndefined;
1122     function last(array) {
1123         ts.Debug.assert(array.length !== 0);
1124         return array[array.length - 1];
1125     }
1126     ts.last = last;
1127     /**
1128      * Returns the only element of an array if it contains only one element, `undefined` otherwise.
1129      */
1130     function singleOrUndefined(array) {
1131         return array && array.length === 1
1132             ? array[0]
1133             : undefined;
1134     }
1135     ts.singleOrUndefined = singleOrUndefined;
1136     function singleOrMany(array) {
1137         return array && array.length === 1
1138             ? array[0]
1139             : array;
1140     }
1141     ts.singleOrMany = singleOrMany;
1142     function replaceElement(array, index, value) {
1143         var result = array.slice(0);
1144         result[index] = value;
1145         return result;
1146     }
1147     ts.replaceElement = replaceElement;
1148     /**
1149      * Performs a binary search, finding the index at which `value` occurs in `array`.
1150      * If no such index is found, returns the 2's-complement of first index at which
1151      * `array[index]` exceeds `value`.
1152      * @param array A sorted array whose first element must be no larger than number
1153      * @param value The value to be searched for in the array.
1154      * @param keySelector A callback used to select the search key from `value` and each element of
1155      * `array`.
1156      * @param keyComparer A callback used to compare two keys in a sorted array.
1157      * @param offset An offset into `array` at which to start the search.
1158      */
1159     function binarySearch(array, value, keySelector, keyComparer, offset) {
1160         return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset);
1161     }
1162     ts.binarySearch = binarySearch;
1163     /**
1164      * Performs a binary search, finding the index at which an object with `key` occurs in `array`.
1165      * If no such index is found, returns the 2's-complement of first index at which
1166      * `array[index]` exceeds `key`.
1167      * @param array A sorted array whose first element must be no larger than number
1168      * @param key The key to be searched for in the array.
1169      * @param keySelector A callback used to select the search key from each element of `array`.
1170      * @param keyComparer A callback used to compare two keys in a sorted array.
1171      * @param offset An offset into `array` at which to start the search.
1172      */
1173     function binarySearchKey(array, key, keySelector, keyComparer, offset) {
1174         if (!some(array)) {
1175             return -1;
1176         }
1177         var low = offset || 0;
1178         var high = array.length - 1;
1179         while (low <= high) {
1180             var middle = low + ((high - low) >> 1);
1181             var midKey = keySelector(array[middle], middle);
1182             switch (keyComparer(midKey, key)) {
1183                 case -1 /* LessThan */:
1184                     low = middle + 1;
1185                     break;
1186                 case 0 /* EqualTo */:
1187                     return middle;
1188                 case 1 /* GreaterThan */:
1189                     high = middle - 1;
1190                     break;
1191             }
1192         }
1193         return ~low;
1194     }
1195     ts.binarySearchKey = binarySearchKey;
1196     function reduceLeft(array, f, initial, start, count) {
1197         if (array && array.length > 0) {
1198             var size = array.length;
1199             if (size > 0) {
1200                 var pos = start === undefined || start < 0 ? 0 : start;
1201                 var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count;
1202                 var result = void 0;
1203                 if (arguments.length <= 2) {
1204                     result = array[pos];
1205                     pos++;
1206                 }
1207                 else {
1208                     result = initial;
1209                 }
1210                 while (pos <= end) {
1211                     result = f(result, array[pos], pos);
1212                     pos++;
1213                 }
1214                 return result;
1215             }
1216         }
1217         return initial;
1218     }
1219     ts.reduceLeft = reduceLeft;
1220     var hasOwnProperty = Object.prototype.hasOwnProperty;
1221     /**
1222      * Indicates whether a map-like contains an own property with the specified key.
1223      *
1224      * @param map A map-like.
1225      * @param key A property key.
1226      */
1227     function hasProperty(map, key) {
1228         return hasOwnProperty.call(map, key);
1229     }
1230     ts.hasProperty = hasProperty;
1231     /**
1232      * Gets the value of an owned property in a map-like.
1233      *
1234      * @param map A map-like.
1235      * @param key A property key.
1236      */
1237     function getProperty(map, key) {
1238         return hasOwnProperty.call(map, key) ? map[key] : undefined;
1239     }
1240     ts.getProperty = getProperty;
1241     /**
1242      * Gets the owned, enumerable property keys of a map-like.
1243      */
1244     function getOwnKeys(map) {
1245         var keys = [];
1246         for (var key in map) {
1247             if (hasOwnProperty.call(map, key)) {
1248                 keys.push(key);
1249             }
1250         }
1251         return keys;
1252     }
1253     ts.getOwnKeys = getOwnKeys;
1254     function getAllKeys(obj) {
1255         var result = [];
1256         do {
1257             var names = Object.getOwnPropertyNames(obj);
1258             for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
1259                 var name = names_1[_i];
1260                 pushIfUnique(result, name);
1261             }
1262         } while (obj = Object.getPrototypeOf(obj));
1263         return result;
1264     }
1265     ts.getAllKeys = getAllKeys;
1266     function getOwnValues(sparseArray) {
1267         var values = [];
1268         for (var key in sparseArray) {
1269             if (hasOwnProperty.call(sparseArray, key)) {
1270                 values.push(sparseArray[key]);
1271             }
1272         }
1273         return values;
1274     }
1275     ts.getOwnValues = getOwnValues;
1276     var _entries = Object.entries || (function (obj) {
1277         var keys = getOwnKeys(obj);
1278         var result = Array(keys.length);
1279         for (var i = 0; i < keys.length; i++) {
1280             result[i] = [keys[i], obj[keys[i]]];
1281         }
1282         return result;
1283     });
1284     function getEntries(obj) {
1285         return obj ? _entries(obj) : [];
1286     }
1287     ts.getEntries = getEntries;
1288     function arrayOf(count, f) {
1289         var result = new Array(count);
1290         for (var i = 0; i < count; i++) {
1291             result[i] = f(i);
1292         }
1293         return result;
1294     }
1295     ts.arrayOf = arrayOf;
1296     function arrayFrom(iterator, map) {
1297         var result = [];
1298         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
1299             result.push(map ? map(iterResult.value) : iterResult.value);
1300         }
1301         return result;
1302     }
1303     ts.arrayFrom = arrayFrom;
1304     function assign(t) {
1305         var args = [];
1306         for (var _i = 1; _i < arguments.length; _i++) {
1307             args[_i - 1] = arguments[_i];
1308         }
1309         for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
1310             var arg = args_1[_a];
1311             if (arg === undefined)
1312                 continue;
1313             for (var p in arg) {
1314                 if (hasProperty(arg, p)) {
1315                     t[p] = arg[p];
1316                 }
1317             }
1318         }
1319         return t;
1320     }
1321     ts.assign = assign;
1322     /**
1323      * Performs a shallow equality comparison of the contents of two map-likes.
1324      *
1325      * @param left A map-like whose properties should be compared.
1326      * @param right A map-like whose properties should be compared.
1327      */
1328     function equalOwnProperties(left, right, equalityComparer) {
1329         if (equalityComparer === void 0) { equalityComparer = equateValues; }
1330         if (left === right)
1331             return true;
1332         if (!left || !right)
1333             return false;
1334         for (var key in left) {
1335             if (hasOwnProperty.call(left, key)) {
1336                 if (!hasOwnProperty.call(right, key))
1337                     return false;
1338                 if (!equalityComparer(left[key], right[key]))
1339                     return false;
1340             }
1341         }
1342         for (var key in right) {
1343             if (hasOwnProperty.call(right, key)) {
1344                 if (!hasOwnProperty.call(left, key))
1345                     return false;
1346             }
1347         }
1348         return true;
1349     }
1350     ts.equalOwnProperties = equalOwnProperties;
1351     function arrayToMap(array, makeKey, makeValue) {
1352         if (makeValue === void 0) { makeValue = identity; }
1353         var result = new ts.Map();
1354         for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
1355             var value = array_6[_i];
1356             var key = makeKey(value);
1357             if (key !== undefined)
1358                 result.set(key, makeValue(value));
1359         }
1360         return result;
1361     }
1362     ts.arrayToMap = arrayToMap;
1363     function arrayToNumericMap(array, makeKey, makeValue) {
1364         if (makeValue === void 0) { makeValue = identity; }
1365         var result = [];
1366         for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
1367             var value = array_7[_i];
1368             result[makeKey(value)] = makeValue(value);
1369         }
1370         return result;
1371     }
1372     ts.arrayToNumericMap = arrayToNumericMap;
1373     function arrayToMultiMap(values, makeKey, makeValue) {
1374         if (makeValue === void 0) { makeValue = identity; }
1375         var result = createMultiMap();
1376         for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
1377             var value = values_1[_i];
1378             result.add(makeKey(value), makeValue(value));
1379         }
1380         return result;
1381     }
1382     ts.arrayToMultiMap = arrayToMultiMap;
1383     function group(values, getGroupId, resultSelector) {
1384         if (resultSelector === void 0) { resultSelector = identity; }
1385         return arrayFrom(arrayToMultiMap(values, getGroupId).values(), resultSelector);
1386     }
1387     ts.group = group;
1388     function clone(object) {
1389         var result = {};
1390         for (var id in object) {
1391             if (hasOwnProperty.call(object, id)) {
1392                 result[id] = object[id];
1393             }
1394         }
1395         return result;
1396     }
1397     ts.clone = clone;
1398     /**
1399      * Creates a new object by adding the own properties of `second`, then the own properties of `first`.
1400      *
1401      * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen.
1402      */
1403     function extend(first, second) {
1404         var result = {};
1405         for (var id in second) {
1406             if (hasOwnProperty.call(second, id)) {
1407                 result[id] = second[id];
1408             }
1409         }
1410         for (var id in first) {
1411             if (hasOwnProperty.call(first, id)) {
1412                 result[id] = first[id];
1413             }
1414         }
1415         return result;
1416     }
1417     ts.extend = extend;
1418     function copyProperties(first, second) {
1419         for (var id in second) {
1420             if (hasOwnProperty.call(second, id)) {
1421                 first[id] = second[id];
1422             }
1423         }
1424     }
1425     ts.copyProperties = copyProperties;
1426     function maybeBind(obj, fn) {
1427         return fn ? fn.bind(obj) : undefined;
1428     }
1429     ts.maybeBind = maybeBind;
1430     function createMultiMap() {
1431         var map = new ts.Map();
1432         map.add = multiMapAdd;
1433         map.remove = multiMapRemove;
1434         return map;
1435     }
1436     ts.createMultiMap = createMultiMap;
1437     function multiMapAdd(key, value) {
1438         var values = this.get(key);
1439         if (values) {
1440             values.push(value);
1441         }
1442         else {
1443             this.set(key, values = [value]);
1444         }
1445         return values;
1446     }
1447     function multiMapRemove(key, value) {
1448         var values = this.get(key);
1449         if (values) {
1450             unorderedRemoveItem(values, value);
1451             if (!values.length) {
1452                 this.delete(key);
1453             }
1454         }
1455     }
1456     function createUnderscoreEscapedMultiMap() {
1457         return createMultiMap();
1458     }
1459     ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap;
1460     /**
1461      * Tests whether a value is an array.
1462      */
1463     function isArray(value) {
1464         return Array.isArray ? Array.isArray(value) : value instanceof Array;
1465     }
1466     ts.isArray = isArray;
1467     function toArray(value) {
1468         return isArray(value) ? value : [value];
1469     }
1470     ts.toArray = toArray;
1471     /**
1472      * Tests whether a value is string
1473      */
1474     function isString(text) {
1475         return typeof text === "string";
1476     }
1477     ts.isString = isString;
1478     function isNumber(x) {
1479         return typeof x === "number";
1480     }
1481     ts.isNumber = isNumber;
1482     function tryCast(value, test) {
1483         return value !== undefined && test(value) ? value : undefined;
1484     }
1485     ts.tryCast = tryCast;
1486     function cast(value, test) {
1487         if (value !== undefined && test(value))
1488             return value;
1489         return ts.Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + ts.Debug.getFunctionName(test) + "'.");
1490     }
1491     ts.cast = cast;
1492     /** Does nothing. */
1493     function noop(_) { }
1494     ts.noop = noop;
1495     /** Do nothing and return false */
1496     function returnFalse() { return false; }
1497     ts.returnFalse = returnFalse;
1498     /** Do nothing and return true */
1499     function returnTrue() { return true; }
1500     ts.returnTrue = returnTrue;
1501     /** Do nothing and return undefined */
1502     function returnUndefined() { return undefined; }
1503     ts.returnUndefined = returnUndefined;
1504     /** Returns its argument. */
1505     function identity(x) { return x; }
1506     ts.identity = identity;
1507     /** Returns lower case string */
1508     function toLowerCase(x) { return x.toLowerCase(); }
1509     ts.toLowerCase = toLowerCase;
1510     // We convert the file names to lower case as key for file name on case insensitive file system
1511     // While doing so we need to handle special characters (eg \u0130) to ensure that we dont convert
1512     // it to lower case, fileName with its lowercase form can exist along side it.
1513     // Handle special characters and make those case sensitive instead
1514     //
1515     // |-#--|-Unicode--|-Char code-|-Desc-------------------------------------------------------------------|
1516     // | 1. | i        | 105       | Ascii i                                                                |
1517     // | 2. | I        | 73        | Ascii I                                                                |
1518     // |-------- Special characters ------------------------------------------------------------------------|
1519     // | 3. | \u0130   | 304       | Upper case I with dot above                                            |
1520     // | 4. | i,\u0307 | 105,775   | i, followed by 775: Lower case of (3rd item)                           |
1521     // | 5. | I,\u0307 | 73,775    | I, followed by 775: Upper case of (4th item), lower case is (4th item) |
1522     // | 6. | \u0131   | 305       | Lower case i without dot, upper case is I (2nd item)                   |
1523     // | 7. | \u00DF   | 223       | Lower case sharp s                                                     |
1524     //
1525     // Because item 3 is special where in its lowercase character has its own
1526     // upper case form we cant convert its case.
1527     // Rest special characters are either already in lower case format or
1528     // they have corresponding upper case character so they dont need special handling
1529     //
1530     // But to avoid having to do string building for most common cases, also ignore
1531     // a-z, 0-9, \u0131, \u00DF, \, /, ., : and space
1532     var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
1533     /**
1534      * Case insensitive file systems have descripencies in how they handle some characters (eg. turkish Upper case I with dot on top - \u0130)
1535      * This function is used in places where we want to make file name as a key on these systems
1536      * 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
1537      * 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
1538      * Technically we would want this function to be platform sepcific as well but
1539      * 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
1540      * We could use upper case and we would still need to deal with the descripencies but
1541      * 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
1542      * 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
1543      */
1544     function toFileNameLowerCase(x) {
1545         return fileNameLowerCaseRegExp.test(x) ?
1546             x.replace(fileNameLowerCaseRegExp, toLowerCase) :
1547             x;
1548     }
1549     ts.toFileNameLowerCase = toFileNameLowerCase;
1550     /** Throws an error because a function is not implemented. */
1551     function notImplemented() {
1552         throw new Error("Not implemented");
1553     }
1554     ts.notImplemented = notImplemented;
1555     function memoize(callback) {
1556         var value;
1557         return function () {
1558             if (callback) {
1559                 value = callback();
1560                 callback = undefined;
1561             }
1562             return value;
1563         };
1564     }
1565     ts.memoize = memoize;
1566     /** A version of `memoize` that supports a single primitive argument */
1567     function memoizeOne(callback) {
1568         var map = new ts.Map();
1569         return function (arg) {
1570             var key = typeof arg + ":" + arg;
1571             var value = map.get(key);
1572             if (value === undefined && !map.has(key)) {
1573                 value = callback(arg);
1574                 map.set(key, value);
1575             }
1576             return value;
1577         };
1578     }
1579     ts.memoizeOne = memoizeOne;
1580     function compose(a, b, c, d, e) {
1581         if (!!e) {
1582             var args_2 = [];
1583             for (var i = 0; i < arguments.length; i++) {
1584                 args_2[i] = arguments[i];
1585             }
1586             return function (t) { return reduceLeft(args_2, function (u, f) { return f(u); }, t); };
1587         }
1588         else if (d) {
1589             return function (t) { return d(c(b(a(t)))); };
1590         }
1591         else if (c) {
1592             return function (t) { return c(b(a(t))); };
1593         }
1594         else if (b) {
1595             return function (t) { return b(a(t)); };
1596         }
1597         else if (a) {
1598             return function (t) { return a(t); };
1599         }
1600         else {
1601             return function (t) { return t; };
1602         }
1603     }
1604     ts.compose = compose;
1605     var AssertionLevel;
1606     (function (AssertionLevel) {
1607         AssertionLevel[AssertionLevel["None"] = 0] = "None";
1608         AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal";
1609         AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive";
1610         AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive";
1611     })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {}));
1612     function equateValues(a, b) {
1613         return a === b;
1614     }
1615     ts.equateValues = equateValues;
1616     /**
1617      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1618      *
1619      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1620      * value of each code-point after applying `toUpperCase` to each string. We always map both
1621      * strings to their upper-case form as some unicode characters do not properly round-trip to
1622      * lowercase (such as `ẞ` (German sharp capital s)).
1623      */
1624     function equateStringsCaseInsensitive(a, b) {
1625         return a === b
1626             || a !== undefined
1627                 && b !== undefined
1628                 && a.toUpperCase() === b.toUpperCase();
1629     }
1630     ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive;
1631     /**
1632      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1633      *
1634      * Case-sensitive comparisons compare both strings one code-point at a time using the
1635      * integer value of each code-point.
1636      */
1637     function equateStringsCaseSensitive(a, b) {
1638         return equateValues(a, b);
1639     }
1640     ts.equateStringsCaseSensitive = equateStringsCaseSensitive;
1641     function compareComparableValues(a, b) {
1642         return a === b ? 0 /* EqualTo */ :
1643             a === undefined ? -1 /* LessThan */ :
1644                 b === undefined ? 1 /* GreaterThan */ :
1645                     a < b ? -1 /* LessThan */ :
1646                         1 /* GreaterThan */;
1647     }
1648     /**
1649      * Compare two numeric values for their order relative to each other.
1650      * To compare strings, use any of the `compareStrings` functions.
1651      */
1652     function compareValues(a, b) {
1653         return compareComparableValues(a, b);
1654     }
1655     ts.compareValues = compareValues;
1656     /**
1657      * Compare two TextSpans, first by `start`, then by `length`.
1658      */
1659     function compareTextSpans(a, b) {
1660         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);
1661     }
1662     ts.compareTextSpans = compareTextSpans;
1663     function min(a, b, compare) {
1664         return compare(a, b) === -1 /* LessThan */ ? a : b;
1665     }
1666     ts.min = min;
1667     /**
1668      * Compare two strings using a case-insensitive ordinal comparison.
1669      *
1670      * Ordinal comparisons are based on the difference between the unicode code points of both
1671      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1672      * comparisons provide predictable ordering, but place "a" after "B".
1673      *
1674      * Case-insensitive comparisons compare both strings one code-point at a time using the integer
1675      * value of each code-point after applying `toUpperCase` to each string. We always map both
1676      * strings to their upper-case form as some unicode characters do not properly round-trip to
1677      * lowercase (such as `ẞ` (German sharp capital s)).
1678      */
1679     function compareStringsCaseInsensitive(a, b) {
1680         if (a === b)
1681             return 0 /* EqualTo */;
1682         if (a === undefined)
1683             return -1 /* LessThan */;
1684         if (b === undefined)
1685             return 1 /* GreaterThan */;
1686         a = a.toUpperCase();
1687         b = b.toUpperCase();
1688         return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1689     }
1690     ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive;
1691     /**
1692      * Compare two strings using a case-sensitive ordinal comparison.
1693      *
1694      * Ordinal comparisons are based on the difference between the unicode code points of both
1695      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1696      * comparisons provide predictable ordering, but place "a" after "B".
1697      *
1698      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1699      * value of each code-point.
1700      */
1701     function compareStringsCaseSensitive(a, b) {
1702         return compareComparableValues(a, b);
1703     }
1704     ts.compareStringsCaseSensitive = compareStringsCaseSensitive;
1705     function getStringComparer(ignoreCase) {
1706         return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
1707     }
1708     ts.getStringComparer = getStringComparer;
1709     /**
1710      * Creates a string comparer for use with string collation in the UI.
1711      */
1712     var createUIStringComparer = (function () {
1713         var defaultComparer;
1714         var enUSComparer;
1715         var stringComparerFactory = getStringComparerFactory();
1716         return createStringComparer;
1717         function compareWithCallback(a, b, comparer) {
1718             if (a === b)
1719                 return 0 /* EqualTo */;
1720             if (a === undefined)
1721                 return -1 /* LessThan */;
1722             if (b === undefined)
1723                 return 1 /* GreaterThan */;
1724             var value = comparer(a, b);
1725             return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1726         }
1727         function createIntlCollatorStringComparer(locale) {
1728             // Intl.Collator.prototype.compare is bound to the collator. See NOTE in
1729             // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare
1730             var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare;
1731             return function (a, b) { return compareWithCallback(a, b, comparer); };
1732         }
1733         function createLocaleCompareStringComparer(locale) {
1734             // if the locale is not the default locale (`undefined`), use the fallback comparer.
1735             if (locale !== undefined)
1736                 return createFallbackStringComparer();
1737             return function (a, b) { return compareWithCallback(a, b, compareStrings); };
1738             function compareStrings(a, b) {
1739                 return a.localeCompare(b);
1740             }
1741         }
1742         function createFallbackStringComparer() {
1743             // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b".
1744             // We first sort case insensitively.  So "Aaa" will come before "baa".
1745             // Then we sort case sensitively, so "aaa" will come before "Aaa".
1746             //
1747             // For case insensitive comparisons we always map both strings to their
1748             // upper-case form as some unicode characters do not properly round-trip to
1749             // lowercase (such as `ẞ` (German sharp capital s)).
1750             return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); };
1751             function compareDictionaryOrder(a, b) {
1752                 return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b);
1753             }
1754             function compareStrings(a, b) {
1755                 return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1756             }
1757         }
1758         function getStringComparerFactory() {
1759             // If the host supports Intl, we use it for comparisons using the default locale.
1760             if (typeof Intl === "object" && typeof Intl.Collator === "function") {
1761                 return createIntlCollatorStringComparer;
1762             }
1763             // If the host does not support Intl, we fall back to localeCompare.
1764             // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it.
1765             if (typeof String.prototype.localeCompare === "function" &&
1766                 typeof String.prototype.toLocaleUpperCase === "function" &&
1767                 "a".localeCompare("B") < 0) {
1768                 return createLocaleCompareStringComparer;
1769             }
1770             // Otherwise, fall back to ordinal comparison:
1771             return createFallbackStringComparer;
1772         }
1773         function createStringComparer(locale) {
1774             // Hold onto common string comparers. This avoids constantly reallocating comparers during
1775             // tests.
1776             if (locale === undefined) {
1777                 return defaultComparer || (defaultComparer = stringComparerFactory(locale));
1778             }
1779             else if (locale === "en-US") {
1780                 return enUSComparer || (enUSComparer = stringComparerFactory(locale));
1781             }
1782             else {
1783                 return stringComparerFactory(locale);
1784             }
1785         }
1786     })();
1787     var uiComparerCaseSensitive;
1788     var uiLocale;
1789     function getUILocale() {
1790         return uiLocale;
1791     }
1792     ts.getUILocale = getUILocale;
1793     function setUILocale(value) {
1794         if (uiLocale !== value) {
1795             uiLocale = value;
1796             uiComparerCaseSensitive = undefined;
1797         }
1798     }
1799     ts.setUILocale = setUILocale;
1800     /**
1801      * Compare two strings in a using the case-sensitive sort behavior of the UI locale.
1802      *
1803      * Ordering is not predictable between different host locales, but is best for displaying
1804      * ordered data for UI presentation. Characters with multiple unicode representations may
1805      * be considered equal.
1806      *
1807      * Case-sensitive comparisons compare strings that differ in base characters, or
1808      * accents/diacritic marks, or case as unequal.
1809      */
1810     function compareStringsCaseSensitiveUI(a, b) {
1811         var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale));
1812         return comparer(a, b);
1813     }
1814     ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI;
1815     function compareProperties(a, b, key, comparer) {
1816         return a === b ? 0 /* EqualTo */ :
1817             a === undefined ? -1 /* LessThan */ :
1818                 b === undefined ? 1 /* GreaterThan */ :
1819                     comparer(a[key], b[key]);
1820     }
1821     ts.compareProperties = compareProperties;
1822     /** True is greater than false. */
1823     function compareBooleans(a, b) {
1824         return compareValues(a ? 1 : 0, b ? 1 : 0);
1825     }
1826     ts.compareBooleans = compareBooleans;
1827     /**
1828      * 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.
1829      * Names less than length 3 only check for case-insensitive equality.
1830      *
1831      * find the candidate with the smallest Levenshtein distance,
1832      *    except for candidates:
1833      *      * With no name
1834      *      * Whose length differs from the target name by more than 0.34 of the length of the name.
1835      *      * Whose levenshtein distance is more than 0.4 of the length of the name
1836      *        (0.4 allows 1 substitution/transposition for every 5 characters,
1837      *         and 1 insertion/deletion at 3 characters)
1838      */
1839     function getSpellingSuggestion(name, candidates, getName) {
1840         var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
1841         var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result is worse than this, don't bother.
1842         var bestCandidate;
1843         for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) {
1844             var candidate = candidates_1[_i];
1845             var candidateName = getName(candidate);
1846             if (candidateName !== undefined && Math.abs(candidateName.length - name.length) <= maximumLengthDifference) {
1847                 if (candidateName === name) {
1848                     continue;
1849                 }
1850                 // Only consider candidates less than 3 characters long when they differ by case.
1851                 // Otherwise, don't bother, since a user would usually notice differences of a 2-character name.
1852                 if (candidateName.length < 3 && candidateName.toLowerCase() !== name.toLowerCase()) {
1853                     continue;
1854                 }
1855                 var distance = levenshteinWithMax(name, candidateName, bestDistance - 0.1);
1856                 if (distance === undefined) {
1857                     continue;
1858                 }
1859                 ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
1860                 bestDistance = distance;
1861                 bestCandidate = candidate;
1862             }
1863         }
1864         return bestCandidate;
1865     }
1866     ts.getSpellingSuggestion = getSpellingSuggestion;
1867     function levenshteinWithMax(s1, s2, max) {
1868         var previous = new Array(s2.length + 1);
1869         var current = new Array(s2.length + 1);
1870         /** Represents any value > max. We don't care about the particular value. */
1871         var big = max + 0.01;
1872         for (var i = 0; i <= s2.length; i++) {
1873             previous[i] = i;
1874         }
1875         for (var i = 1; i <= s1.length; i++) {
1876             var c1 = s1.charCodeAt(i - 1);
1877             var minJ = Math.ceil(i > max ? i - max : 1);
1878             var maxJ = Math.floor(s2.length > max + i ? max + i : s2.length);
1879             current[0] = i;
1880             /** Smallest value of the matrix in the ith column. */
1881             var colMin = i;
1882             for (var j = 1; j < minJ; j++) {
1883                 current[j] = big;
1884             }
1885             for (var j = minJ; j <= maxJ; j++) {
1886                 // case difference should be significantly cheaper than other differences
1887                 var substitutionDistance = s1[i - 1].toLowerCase() === s2[j - 1].toLowerCase()
1888                     ? (previous[j - 1] + 0.1)
1889                     : (previous[j - 1] + 2);
1890                 var dist = c1 === s2.charCodeAt(j - 1)
1891                     ? previous[j - 1]
1892                     : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ substitutionDistance);
1893                 current[j] = dist;
1894                 colMin = Math.min(colMin, dist);
1895             }
1896             for (var j = maxJ + 1; j <= s2.length; j++) {
1897                 current[j] = big;
1898             }
1899             if (colMin > max) {
1900                 // Give up -- everything in this column is > max and it can't get better in future columns.
1901                 return undefined;
1902             }
1903             var temp = previous;
1904             previous = current;
1905             current = temp;
1906         }
1907         var res = previous[s2.length];
1908         return res > max ? undefined : res;
1909     }
1910     function endsWith(str, suffix) {
1911         var expectedPos = str.length - suffix.length;
1912         return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
1913     }
1914     ts.endsWith = endsWith;
1915     function removeSuffix(str, suffix) {
1916         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str;
1917     }
1918     ts.removeSuffix = removeSuffix;
1919     function tryRemoveSuffix(str, suffix) {
1920         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined;
1921     }
1922     ts.tryRemoveSuffix = tryRemoveSuffix;
1923     function stringContains(str, substring) {
1924         return str.indexOf(substring) !== -1;
1925     }
1926     ts.stringContains = stringContains;
1927     /**
1928      * Takes a string like "jquery-min.4.2.3" and returns "jquery"
1929      */
1930     function removeMinAndVersionNumbers(fileName) {
1931         // Match a "." or "-" followed by a version number or 'min' at the end of the name
1932         var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/;
1933         // The "min" or version may both be present, in either order, so try applying the above twice.
1934         return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, "");
1935     }
1936     ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers;
1937     /** Remove an item from an array, moving everything to its right one space left. */
1938     function orderedRemoveItem(array, item) {
1939         for (var i = 0; i < array.length; i++) {
1940             if (array[i] === item) {
1941                 orderedRemoveItemAt(array, i);
1942                 return true;
1943             }
1944         }
1945         return false;
1946     }
1947     ts.orderedRemoveItem = orderedRemoveItem;
1948     /** Remove an item by index from an array, moving everything to its right one space left. */
1949     function orderedRemoveItemAt(array, index) {
1950         // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
1951         for (var i = index; i < array.length - 1; i++) {
1952             array[i] = array[i + 1];
1953         }
1954         array.pop();
1955     }
1956     ts.orderedRemoveItemAt = orderedRemoveItemAt;
1957     function unorderedRemoveItemAt(array, index) {
1958         // Fill in the "hole" left at `index`.
1959         array[index] = array[array.length - 1];
1960         array.pop();
1961     }
1962     ts.unorderedRemoveItemAt = unorderedRemoveItemAt;
1963     /** Remove the *first* occurrence of `item` from the array. */
1964     function unorderedRemoveItem(array, item) {
1965         return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; });
1966     }
1967     ts.unorderedRemoveItem = unorderedRemoveItem;
1968     /** Remove the *first* element satisfying `predicate`. */
1969     function unorderedRemoveFirstItemWhere(array, predicate) {
1970         for (var i = 0; i < array.length; i++) {
1971             if (predicate(array[i])) {
1972                 unorderedRemoveItemAt(array, i);
1973                 return true;
1974             }
1975         }
1976         return false;
1977     }
1978     function createGetCanonicalFileName(useCaseSensitiveFileNames) {
1979         return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
1980     }
1981     ts.createGetCanonicalFileName = createGetCanonicalFileName;
1982     function patternText(_a) {
1983         var prefix = _a.prefix, suffix = _a.suffix;
1984         return prefix + "*" + suffix;
1985     }
1986     ts.patternText = patternText;
1987     /**
1988      * Given that candidate matches pattern, returns the text matching the '*'.
1989      * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
1990      */
1991     function matchedText(pattern, candidate) {
1992         ts.Debug.assert(isPatternMatch(pattern, candidate));
1993         return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length);
1994     }
1995     ts.matchedText = matchedText;
1996     /** Return the object corresponding to the best pattern to match `candidate`. */
1997     function findBestPatternMatch(values, getPattern, candidate) {
1998         var matchedValue;
1999         // use length of prefix as betterness criteria
2000         var longestMatchPrefixLength = -1;
2001         for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
2002             var v = values_2[_i];
2003             var pattern = getPattern(v);
2004             if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
2005                 longestMatchPrefixLength = pattern.prefix.length;
2006                 matchedValue = v;
2007             }
2008         }
2009         return matchedValue;
2010     }
2011     ts.findBestPatternMatch = findBestPatternMatch;
2012     function startsWith(str, prefix) {
2013         return str.lastIndexOf(prefix, 0) === 0;
2014     }
2015     ts.startsWith = startsWith;
2016     function removePrefix(str, prefix) {
2017         return startsWith(str, prefix) ? str.substr(prefix.length) : str;
2018     }
2019     ts.removePrefix = removePrefix;
2020     function tryRemovePrefix(str, prefix, getCanonicalFileName) {
2021         if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; }
2022         return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined;
2023     }
2024     ts.tryRemovePrefix = tryRemovePrefix;
2025     function isPatternMatch(_a, candidate) {
2026         var prefix = _a.prefix, suffix = _a.suffix;
2027         return candidate.length >= prefix.length + suffix.length &&
2028             startsWith(candidate, prefix) &&
2029             endsWith(candidate, suffix);
2030     }
2031     function and(f, g) {
2032         return function (arg) { return f(arg) && g(arg); };
2033     }
2034     ts.and = and;
2035     function or() {
2036         var fs = [];
2037         for (var _i = 0; _i < arguments.length; _i++) {
2038             fs[_i] = arguments[_i];
2039         }
2040         return function () {
2041             var args = [];
2042             for (var _i = 0; _i < arguments.length; _i++) {
2043                 args[_i] = arguments[_i];
2044             }
2045             for (var _a = 0, fs_1 = fs; _a < fs_1.length; _a++) {
2046                 var f = fs_1[_a];
2047                 if (f.apply(void 0, args)) {
2048                     return true;
2049                 }
2050             }
2051             return false;
2052         };
2053     }
2054     ts.or = or;
2055     function not(fn) {
2056         return function () {
2057             var args = [];
2058             for (var _i = 0; _i < arguments.length; _i++) {
2059                 args[_i] = arguments[_i];
2060             }
2061             return !fn.apply(void 0, args);
2062         };
2063     }
2064     ts.not = not;
2065     function assertType(_) { }
2066     ts.assertType = assertType;
2067     function singleElementArray(t) {
2068         return t === undefined ? undefined : [t];
2069     }
2070     ts.singleElementArray = singleElementArray;
2071     function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) {
2072         unchanged = unchanged || noop;
2073         var newIndex = 0;
2074         var oldIndex = 0;
2075         var newLen = newItems.length;
2076         var oldLen = oldItems.length;
2077         var hasChanges = false;
2078         while (newIndex < newLen && oldIndex < oldLen) {
2079             var newItem = newItems[newIndex];
2080             var oldItem = oldItems[oldIndex];
2081             var compareResult = comparer(newItem, oldItem);
2082             if (compareResult === -1 /* LessThan */) {
2083                 inserted(newItem);
2084                 newIndex++;
2085                 hasChanges = true;
2086             }
2087             else if (compareResult === 1 /* GreaterThan */) {
2088                 deleted(oldItem);
2089                 oldIndex++;
2090                 hasChanges = true;
2091             }
2092             else {
2093                 unchanged(oldItem, newItem);
2094                 newIndex++;
2095                 oldIndex++;
2096             }
2097         }
2098         while (newIndex < newLen) {
2099             inserted(newItems[newIndex++]);
2100             hasChanges = true;
2101         }
2102         while (oldIndex < oldLen) {
2103             deleted(oldItems[oldIndex++]);
2104             hasChanges = true;
2105         }
2106         return hasChanges;
2107     }
2108     ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes;
2109     function fill(length, cb) {
2110         var result = Array(length);
2111         for (var i = 0; i < length; i++) {
2112             result[i] = cb(i);
2113         }
2114         return result;
2115     }
2116     ts.fill = fill;
2117     function cartesianProduct(arrays) {
2118         var result = [];
2119         cartesianProductWorker(arrays, result, /*outer*/ undefined, 0);
2120         return result;
2121     }
2122     ts.cartesianProduct = cartesianProduct;
2123     function cartesianProductWorker(arrays, result, outer, index) {
2124         for (var _i = 0, _a = arrays[index]; _i < _a.length; _i++) {
2125             var element = _a[_i];
2126             var inner = void 0;
2127             if (outer) {
2128                 inner = outer.slice();
2129                 inner.push(element);
2130             }
2131             else {
2132                 inner = [element];
2133             }
2134             if (index === arrays.length - 1) {
2135                 result.push(inner);
2136             }
2137             else {
2138                 cartesianProductWorker(arrays, result, inner, index + 1);
2139             }
2140         }
2141     }
2142     /**
2143      * Returns string left-padded with spaces or zeros until it reaches the given length.
2144      *
2145      * @param s String to pad.
2146      * @param length Final padded length. If less than or equal to 's.length', returns 's' unchanged.
2147      * @param padString Character to use as padding (default " ").
2148      */
2149     function padLeft(s, length, padString) {
2150         if (padString === void 0) { padString = " "; }
2151         return length <= s.length ? s : padString.repeat(length - s.length) + s;
2152     }
2153     ts.padLeft = padLeft;
2154     /**
2155      * Returns string right-padded with spaces until it reaches the given length.
2156      *
2157      * @param s String to pad.
2158      * @param length Final padded length. If less than or equal to 's.length', returns 's' unchanged.
2159      * @param padString Character to use as padding (default " ").
2160      */
2161     function padRight(s, length, padString) {
2162         if (padString === void 0) { padString = " "; }
2163         return length <= s.length ? s : s + padString.repeat(length - s.length);
2164     }
2165     ts.padRight = padRight;
2166     function takeWhile(array, predicate) {
2167         var len = array.length;
2168         var index = 0;
2169         while (index < len && predicate(array[index])) {
2170             index++;
2171         }
2172         return array.slice(0, index);
2173     }
2174     ts.takeWhile = takeWhile;
2175 })(ts || (ts = {}));
2176 /* @internal */
2177 var ts;
2178 (function (ts) {
2179     var LogLevel;
2180     (function (LogLevel) {
2181         LogLevel[LogLevel["Off"] = 0] = "Off";
2182         LogLevel[LogLevel["Error"] = 1] = "Error";
2183         LogLevel[LogLevel["Warning"] = 2] = "Warning";
2184         LogLevel[LogLevel["Info"] = 3] = "Info";
2185         LogLevel[LogLevel["Verbose"] = 4] = "Verbose";
2186     })(LogLevel = ts.LogLevel || (ts.LogLevel = {}));
2187     var Debug;
2188     (function (Debug) {
2189         var typeScriptVersion;
2190         /* eslint-disable prefer-const */
2191         var currentAssertionLevel = 0 /* None */;
2192         Debug.currentLogLevel = LogLevel.Warning;
2193         Debug.isDebugging = false;
2194         function getTypeScriptVersion() {
2195             return typeScriptVersion !== null && typeScriptVersion !== void 0 ? typeScriptVersion : (typeScriptVersion = new ts.Version(ts.version));
2196         }
2197         Debug.getTypeScriptVersion = getTypeScriptVersion;
2198         function shouldLog(level) {
2199             return Debug.currentLogLevel <= level;
2200         }
2201         Debug.shouldLog = shouldLog;
2202         function logMessage(level, s) {
2203             if (Debug.loggingHost && shouldLog(level)) {
2204                 Debug.loggingHost.log(level, s);
2205             }
2206         }
2207         function log(s) {
2208             logMessage(LogLevel.Info, s);
2209         }
2210         Debug.log = log;
2211         (function (log_1) {
2212             function error(s) {
2213                 logMessage(LogLevel.Error, s);
2214             }
2215             log_1.error = error;
2216             function warn(s) {
2217                 logMessage(LogLevel.Warning, s);
2218             }
2219             log_1.warn = warn;
2220             function log(s) {
2221                 logMessage(LogLevel.Info, s);
2222             }
2223             log_1.log = log;
2224             function trace(s) {
2225                 logMessage(LogLevel.Verbose, s);
2226             }
2227             log_1.trace = trace;
2228         })(log = Debug.log || (Debug.log = {}));
2229         var assertionCache = {};
2230         function getAssertionLevel() {
2231             return currentAssertionLevel;
2232         }
2233         Debug.getAssertionLevel = getAssertionLevel;
2234         function setAssertionLevel(level) {
2235             var prevAssertionLevel = currentAssertionLevel;
2236             currentAssertionLevel = level;
2237             if (level > prevAssertionLevel) {
2238                 // restore assertion functions for the current assertion level (see `shouldAssertFunction`).
2239                 for (var _i = 0, _a = ts.getOwnKeys(assertionCache); _i < _a.length; _i++) {
2240                     var key = _a[_i];
2241                     var cachedFunc = assertionCache[key];
2242                     if (cachedFunc !== undefined && Debug[key] !== cachedFunc.assertion && level >= cachedFunc.level) {
2243                         Debug[key] = cachedFunc;
2244                         assertionCache[key] = undefined;
2245                     }
2246                 }
2247             }
2248         }
2249         Debug.setAssertionLevel = setAssertionLevel;
2250         function shouldAssert(level) {
2251             return currentAssertionLevel >= level;
2252         }
2253         Debug.shouldAssert = shouldAssert;
2254         /**
2255          * Tests whether an assertion function should be executed. If it shouldn't, it is cached and replaced with `ts.noop`.
2256          * Replaced assertion functions are restored when `Debug.setAssertionLevel` is set to a high enough level.
2257          * @param level The minimum assertion level required.
2258          * @param name The name of the current assertion function.
2259          */
2260         function shouldAssertFunction(level, name) {
2261             if (!shouldAssert(level)) {
2262                 assertionCache[name] = { level: level, assertion: Debug[name] };
2263                 Debug[name] = ts.noop;
2264                 return false;
2265             }
2266             return true;
2267         }
2268         function fail(message, stackCrawlMark) {
2269             debugger;
2270             var e = new Error(message ? "Debug Failure. " + message : "Debug Failure.");
2271             if (Error.captureStackTrace) {
2272                 Error.captureStackTrace(e, stackCrawlMark || fail);
2273             }
2274             throw e;
2275         }
2276         Debug.fail = fail;
2277         function failBadSyntaxKind(node, message, stackCrawlMark) {
2278             return fail((message || "Unexpected node.") + "\r\nNode " + formatSyntaxKind(node.kind) + " was unexpected.", stackCrawlMark || failBadSyntaxKind);
2279         }
2280         Debug.failBadSyntaxKind = failBadSyntaxKind;
2281         function assert(expression, message, verboseDebugInfo, stackCrawlMark) {
2282             if (!expression) {
2283                 message = message ? "False expression: " + message : "False expression.";
2284                 if (verboseDebugInfo) {
2285                     message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
2286                 }
2287                 fail(message, stackCrawlMark || assert);
2288             }
2289         }
2290         Debug.assert = assert;
2291         function assertEqual(a, b, msg, msg2, stackCrawlMark) {
2292             if (a !== b) {
2293                 var message = msg ? msg2 ? msg + " " + msg2 : msg : "";
2294                 fail("Expected " + a + " === " + b + ". " + message, stackCrawlMark || assertEqual);
2295             }
2296         }
2297         Debug.assertEqual = assertEqual;
2298         function assertLessThan(a, b, msg, stackCrawlMark) {
2299             if (a >= b) {
2300                 fail("Expected " + a + " < " + b + ". " + (msg || ""), stackCrawlMark || assertLessThan);
2301             }
2302         }
2303         Debug.assertLessThan = assertLessThan;
2304         function assertLessThanOrEqual(a, b, stackCrawlMark) {
2305             if (a > b) {
2306                 fail("Expected " + a + " <= " + b, stackCrawlMark || assertLessThanOrEqual);
2307             }
2308         }
2309         Debug.assertLessThanOrEqual = assertLessThanOrEqual;
2310         function assertGreaterThanOrEqual(a, b, stackCrawlMark) {
2311             if (a < b) {
2312                 fail("Expected " + a + " >= " + b, stackCrawlMark || assertGreaterThanOrEqual);
2313             }
2314         }
2315         Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual;
2316         function assertIsDefined(value, message, stackCrawlMark) {
2317             // eslint-disable-next-line no-null/no-null
2318             if (value === undefined || value === null) {
2319                 fail(message, stackCrawlMark || assertIsDefined);
2320             }
2321         }
2322         Debug.assertIsDefined = assertIsDefined;
2323         function checkDefined(value, message, stackCrawlMark) {
2324             assertIsDefined(value, message, stackCrawlMark || checkDefined);
2325             return value;
2326         }
2327         Debug.checkDefined = checkDefined;
2328         /**
2329          * @deprecated Use `checkDefined` to check whether a value is defined inline. Use `assertIsDefined` to check whether
2330          * a value is defined at the statement level.
2331          */
2332         Debug.assertDefined = checkDefined;
2333         function assertEachIsDefined(value, message, stackCrawlMark) {
2334             for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
2335                 var v = value_1[_i];
2336                 assertIsDefined(v, message, stackCrawlMark || assertEachIsDefined);
2337             }
2338         }
2339         Debug.assertEachIsDefined = assertEachIsDefined;
2340         function checkEachDefined(value, message, stackCrawlMark) {
2341             assertEachIsDefined(value, message, stackCrawlMark || checkEachDefined);
2342             return value;
2343         }
2344         Debug.checkEachDefined = checkEachDefined;
2345         /**
2346          * @deprecated Use `checkEachDefined` to check whether the elements of an array are defined inline. Use `assertEachIsDefined` to check whether
2347          * the elements of an array are defined at the statement level.
2348          */
2349         Debug.assertEachDefined = checkEachDefined;
2350         function assertNever(member, message, stackCrawlMark) {
2351             if (message === void 0) { message = "Illegal value:"; }
2352             var detail = typeof member === "object" && ts.hasProperty(member, "kind") && ts.hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind(member.kind) : JSON.stringify(member);
2353             return fail(message + " " + detail, stackCrawlMark || assertNever);
2354         }
2355         Debug.assertNever = assertNever;
2356         function assertEachNode(nodes, test, message, stackCrawlMark) {
2357             if (shouldAssertFunction(1 /* Normal */, "assertEachNode")) {
2358                 assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertEachNode);
2359             }
2360         }
2361         Debug.assertEachNode = assertEachNode;
2362         function assertNode(node, test, message, stackCrawlMark) {
2363             if (shouldAssertFunction(1 /* Normal */, "assertNode")) {
2364                 assert(node !== undefined && (test === undefined || test(node)), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNode);
2365             }
2366         }
2367         Debug.assertNode = assertNode;
2368         function assertNotNode(node, test, message, stackCrawlMark) {
2369             if (shouldAssertFunction(1 /* Normal */, "assertNotNode")) {
2370                 assert(node === undefined || test === undefined || !test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " should not have passed test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNotNode);
2371             }
2372         }
2373         Debug.assertNotNode = assertNotNode;
2374         function assertOptionalNode(node, test, message, stackCrawlMark) {
2375             if (shouldAssertFunction(1 /* Normal */, "assertOptionalNode")) {
2376                 assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertOptionalNode);
2377             }
2378         }
2379         Debug.assertOptionalNode = assertOptionalNode;
2380         function assertOptionalToken(node, kind, message, stackCrawlMark) {
2381             if (shouldAssertFunction(1 /* Normal */, "assertOptionalToken")) {
2382                 assert(kind === undefined || node === undefined || node.kind === kind, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was not a '" + formatSyntaxKind(kind) + "' token."; }, stackCrawlMark || assertOptionalToken);
2383             }
2384         }
2385         Debug.assertOptionalToken = assertOptionalToken;
2386         function assertMissingNode(node, message, stackCrawlMark) {
2387             if (shouldAssertFunction(1 /* Normal */, "assertMissingNode")) {
2388                 assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, stackCrawlMark || assertMissingNode);
2389             }
2390         }
2391         Debug.assertMissingNode = assertMissingNode;
2392         function getFunctionName(func) {
2393             if (typeof func !== "function") {
2394                 return "";
2395             }
2396             else if (func.hasOwnProperty("name")) {
2397                 return func.name;
2398             }
2399             else {
2400                 var text = Function.prototype.toString.call(func);
2401                 var match = /^function\s+([\w\$]+)\s*\(/.exec(text);
2402                 return match ? match[1] : "";
2403             }
2404         }
2405         Debug.getFunctionName = getFunctionName;
2406         function formatSymbol(symbol) {
2407             return "{ name: " + ts.unescapeLeadingUnderscores(symbol.escapedName) + "; flags: " + formatSymbolFlags(symbol.flags) + "; declarations: " + ts.map(symbol.declarations, function (node) { return formatSyntaxKind(node.kind); }) + " }";
2408         }
2409         Debug.formatSymbol = formatSymbol;
2410         /**
2411          * Formats an enum value as a string for debugging and debug assertions.
2412          */
2413         function formatEnum(value, enumObject, isFlags) {
2414             if (value === void 0) { value = 0; }
2415             var members = getEnumMembers(enumObject);
2416             if (value === 0) {
2417                 return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
2418             }
2419             if (isFlags) {
2420                 var result = "";
2421                 var remainingFlags = value;
2422                 for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
2423                     var _a = members_1[_i], enumValue = _a[0], enumName = _a[1];
2424                     if (enumValue > value) {
2425                         break;
2426                     }
2427                     if (enumValue !== 0 && enumValue & value) {
2428                         result = "" + result + (result ? "|" : "") + enumName;
2429                         remainingFlags &= ~enumValue;
2430                     }
2431                 }
2432                 if (remainingFlags === 0) {
2433                     return result;
2434                 }
2435             }
2436             else {
2437                 for (var _b = 0, members_2 = members; _b < members_2.length; _b++) {
2438                     var _c = members_2[_b], enumValue = _c[0], enumName = _c[1];
2439                     if (enumValue === value) {
2440                         return enumName;
2441                     }
2442                 }
2443             }
2444             return value.toString();
2445         }
2446         Debug.formatEnum = formatEnum;
2447         function getEnumMembers(enumObject) {
2448             var result = [];
2449             for (var name in enumObject) {
2450                 var value = enumObject[name];
2451                 if (typeof value === "number") {
2452                     result.push([value, name]);
2453                 }
2454             }
2455             return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); });
2456         }
2457         function formatSyntaxKind(kind) {
2458             return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false);
2459         }
2460         Debug.formatSyntaxKind = formatSyntaxKind;
2461         function formatNodeFlags(flags) {
2462             return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true);
2463         }
2464         Debug.formatNodeFlags = formatNodeFlags;
2465         function formatModifierFlags(flags) {
2466             return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true);
2467         }
2468         Debug.formatModifierFlags = formatModifierFlags;
2469         function formatTransformFlags(flags) {
2470             return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true);
2471         }
2472         Debug.formatTransformFlags = formatTransformFlags;
2473         function formatEmitFlags(flags) {
2474             return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true);
2475         }
2476         Debug.formatEmitFlags = formatEmitFlags;
2477         function formatSymbolFlags(flags) {
2478             return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true);
2479         }
2480         Debug.formatSymbolFlags = formatSymbolFlags;
2481         function formatTypeFlags(flags) {
2482             return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true);
2483         }
2484         Debug.formatTypeFlags = formatTypeFlags;
2485         function formatSignatureFlags(flags) {
2486             return formatEnum(flags, ts.SignatureFlags, /*isFlags*/ true);
2487         }
2488         Debug.formatSignatureFlags = formatSignatureFlags;
2489         function formatObjectFlags(flags) {
2490             return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true);
2491         }
2492         Debug.formatObjectFlags = formatObjectFlags;
2493         function formatFlowFlags(flags) {
2494             return formatEnum(flags, ts.FlowFlags, /*isFlags*/ true);
2495         }
2496         Debug.formatFlowFlags = formatFlowFlags;
2497         var isDebugInfoEnabled = false;
2498         var extendedDebugModule;
2499         function extendedDebug() {
2500             enableDebugInfo();
2501             if (!extendedDebugModule) {
2502                 throw new Error("Debugging helpers could not be loaded.");
2503             }
2504             return extendedDebugModule;
2505         }
2506         function printControlFlowGraph(flowNode) {
2507             return console.log(formatControlFlowGraph(flowNode));
2508         }
2509         Debug.printControlFlowGraph = printControlFlowGraph;
2510         function formatControlFlowGraph(flowNode) {
2511             return extendedDebug().formatControlFlowGraph(flowNode);
2512         }
2513         Debug.formatControlFlowGraph = formatControlFlowGraph;
2514         var flowNodeProto;
2515         function attachFlowNodeDebugInfoWorker(flowNode) {
2516             if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator
2517                 Object.defineProperties(flowNode, {
2518                     // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2519                     __tsDebuggerDisplay: {
2520                         value: function () {
2521                             var flowHeader = this.flags & 2 /* Start */ ? "FlowStart" :
2522                                 this.flags & 4 /* BranchLabel */ ? "FlowBranchLabel" :
2523                                     this.flags & 8 /* LoopLabel */ ? "FlowLoopLabel" :
2524                                         this.flags & 16 /* Assignment */ ? "FlowAssignment" :
2525                                             this.flags & 32 /* TrueCondition */ ? "FlowTrueCondition" :
2526                                                 this.flags & 64 /* FalseCondition */ ? "FlowFalseCondition" :
2527                                                     this.flags & 128 /* SwitchClause */ ? "FlowSwitchClause" :
2528                                                         this.flags & 256 /* ArrayMutation */ ? "FlowArrayMutation" :
2529                                                             this.flags & 512 /* Call */ ? "FlowCall" :
2530                                                                 this.flags & 1024 /* ReduceLabel */ ? "FlowReduceLabel" :
2531                                                                     this.flags & 1 /* Unreachable */ ? "FlowUnreachable" :
2532                                                                         "UnknownFlow";
2533                             var remainingFlags = this.flags & ~(2048 /* Referenced */ - 1);
2534                             return "" + flowHeader + (remainingFlags ? " (" + formatFlowFlags(remainingFlags) + ")" : "");
2535                         }
2536                     },
2537                     __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } },
2538                     __debugToString: { value: function () { return formatControlFlowGraph(this); } }
2539                 });
2540             }
2541         }
2542         function attachFlowNodeDebugInfo(flowNode) {
2543             if (isDebugInfoEnabled) {
2544                 if (typeof Object.setPrototypeOf === "function") {
2545                     // if we're in es2015, attach the method to a shared prototype for `FlowNode`
2546                     // so the method doesn't show up in the watch window.
2547                     if (!flowNodeProto) {
2548                         flowNodeProto = Object.create(Object.prototype);
2549                         attachFlowNodeDebugInfoWorker(flowNodeProto);
2550                     }
2551                     Object.setPrototypeOf(flowNode, flowNodeProto);
2552                 }
2553                 else {
2554                     // not running in an es2015 environment, attach the method directly.
2555                     attachFlowNodeDebugInfoWorker(flowNode);
2556                 }
2557             }
2558         }
2559         Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo;
2560         var nodeArrayProto;
2561         function attachNodeArrayDebugInfoWorker(array) {
2562             if (!("__tsDebuggerDisplay" in array)) { // eslint-disable-line no-in-operator
2563                 Object.defineProperties(array, {
2564                     __tsDebuggerDisplay: {
2565                         value: function (defaultValue) {
2566                             // An `Array` with extra properties is rendered as `[A, B, prop1: 1, prop2: 2]`. Most of
2567                             // these aren't immediately useful so we trim off the `prop1: ..., prop2: ...` part from the
2568                             // formatted string.
2569                             defaultValue = String(defaultValue).replace(/(?:,[\s\w\d_]+:[^,]+)+\]$/, "]");
2570                             return "NodeArray " + defaultValue;
2571                         }
2572                     }
2573                 });
2574             }
2575         }
2576         function attachNodeArrayDebugInfo(array) {
2577             if (isDebugInfoEnabled) {
2578                 if (typeof Object.setPrototypeOf === "function") {
2579                     // if we're in es2015, attach the method to a shared prototype for `NodeArray`
2580                     // so the method doesn't show up in the watch window.
2581                     if (!nodeArrayProto) {
2582                         nodeArrayProto = Object.create(Array.prototype);
2583                         attachNodeArrayDebugInfoWorker(nodeArrayProto);
2584                     }
2585                     Object.setPrototypeOf(array, nodeArrayProto);
2586                 }
2587                 else {
2588                     // not running in an es2015 environment, attach the method directly.
2589                     attachNodeArrayDebugInfoWorker(array);
2590                 }
2591             }
2592         }
2593         Debug.attachNodeArrayDebugInfo = attachNodeArrayDebugInfo;
2594         /**
2595          * Injects debug information into frequently used types.
2596          */
2597         function enableDebugInfo() {
2598             if (isDebugInfoEnabled)
2599                 return;
2600             // avoid recomputing
2601             var weakTypeTextMap;
2602             var weakNodeTextMap;
2603             function getWeakTypeTextMap() {
2604                 if (weakTypeTextMap === undefined) {
2605                     if (typeof WeakMap === "function")
2606                         weakTypeTextMap = new WeakMap();
2607                 }
2608                 return weakTypeTextMap;
2609             }
2610             function getWeakNodeTextMap() {
2611                 if (weakNodeTextMap === undefined) {
2612                     if (typeof WeakMap === "function")
2613                         weakNodeTextMap = new WeakMap();
2614                 }
2615                 return weakNodeTextMap;
2616             }
2617             // Add additional properties in debug mode to assist with debugging.
2618             Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, {
2619                 // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2620                 __tsDebuggerDisplay: {
2621                     value: function () {
2622                         var symbolHeader = this.flags & 33554432 /* Transient */ ? "TransientSymbol" :
2623                             "Symbol";
2624                         var remainingSymbolFlags = this.flags & ~33554432 /* Transient */;
2625                         return symbolHeader + " '" + ts.symbolName(this) + "'" + (remainingSymbolFlags ? " (" + formatSymbolFlags(remainingSymbolFlags) + ")" : "");
2626                     }
2627                 },
2628                 __debugFlags: { get: function () { return formatSymbolFlags(this.flags); } }
2629             });
2630             Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, {
2631                 // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2632                 __tsDebuggerDisplay: {
2633                     value: function () {
2634                         var typeHeader = this.flags & 98304 /* Nullable */ ? "NullableType" :
2635                             this.flags & 384 /* StringOrNumberLiteral */ ? "LiteralType " + JSON.stringify(this.value) :
2636                                 this.flags & 2048 /* BigIntLiteral */ ? "LiteralType " + (this.value.negative ? "-" : "") + this.value.base10Value + "n" :
2637                                     this.flags & 8192 /* UniqueESSymbol */ ? "UniqueESSymbolType" :
2638                                         this.flags & 32 /* Enum */ ? "EnumType" :
2639                                             this.flags & 67359327 /* Intrinsic */ ? "IntrinsicType " + this.intrinsicName :
2640                                                 this.flags & 1048576 /* Union */ ? "UnionType" :
2641                                                     this.flags & 2097152 /* Intersection */ ? "IntersectionType" :
2642                                                         this.flags & 4194304 /* Index */ ? "IndexType" :
2643                                                             this.flags & 8388608 /* IndexedAccess */ ? "IndexedAccessType" :
2644                                                                 this.flags & 16777216 /* Conditional */ ? "ConditionalType" :
2645                                                                     this.flags & 33554432 /* Substitution */ ? "SubstitutionType" :
2646                                                                         this.flags & 262144 /* TypeParameter */ ? "TypeParameter" :
2647                                                                             this.flags & 524288 /* Object */ ?
2648                                                                                 this.objectFlags & 3 /* ClassOrInterface */ ? "InterfaceType" :
2649                                                                                     this.objectFlags & 4 /* Reference */ ? "TypeReference" :
2650                                                                                         this.objectFlags & 8 /* Tuple */ ? "TupleType" :
2651                                                                                             this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" :
2652                                                                                                 this.objectFlags & 32 /* Mapped */ ? "MappedType" :
2653                                                                                                     this.objectFlags & 2048 /* ReverseMapped */ ? "ReverseMappedType" :
2654                                                                                                         this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" :
2655                                                                                                             "ObjectType" :
2656                                                                                 "Type";
2657                         var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~2367 /* ObjectTypeKindMask */ : 0;
2658                         return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : "");
2659                     }
2660                 },
2661                 __debugFlags: { get: function () { return formatTypeFlags(this.flags); } },
2662                 __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? formatObjectFlags(this.objectFlags) : ""; } },
2663                 __debugTypeToString: {
2664                     value: function () {
2665                         // avoid recomputing
2666                         var map = getWeakTypeTextMap();
2667                         var text = map === null || map === void 0 ? void 0 : map.get(this);
2668                         if (text === undefined) {
2669                             text = this.checker.typeToString(this);
2670                             map === null || map === void 0 ? void 0 : map.set(this, text);
2671                         }
2672                         return text;
2673                     }
2674                 },
2675             });
2676             Object.defineProperties(ts.objectAllocator.getSignatureConstructor().prototype, {
2677                 __debugFlags: { get: function () { return formatSignatureFlags(this.flags); } },
2678                 __debugSignatureToString: { value: function () { var _a; return (_a = this.checker) === null || _a === void 0 ? void 0 : _a.signatureToString(this); } }
2679             });
2680             var nodeConstructors = [
2681                 ts.objectAllocator.getNodeConstructor(),
2682                 ts.objectAllocator.getIdentifierConstructor(),
2683                 ts.objectAllocator.getTokenConstructor(),
2684                 ts.objectAllocator.getSourceFileConstructor()
2685             ];
2686             for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) {
2687                 var ctor = nodeConstructors_1[_i];
2688                 if (!ctor.prototype.hasOwnProperty("__debugKind")) {
2689                     Object.defineProperties(ctor.prototype, {
2690                         // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2691                         __tsDebuggerDisplay: {
2692                             value: function () {
2693                                 var nodeHeader = ts.isGeneratedIdentifier(this) ? "GeneratedIdentifier" :
2694                                     ts.isIdentifier(this) ? "Identifier '" + ts.idText(this) + "'" :
2695                                         ts.isPrivateIdentifier(this) ? "PrivateIdentifier '" + ts.idText(this) + "'" :
2696                                             ts.isStringLiteral(this) ? "StringLiteral " + JSON.stringify(this.text.length < 10 ? this.text : this.text.slice(10) + "...") :
2697                                                 ts.isNumericLiteral(this) ? "NumericLiteral " + this.text :
2698                                                     ts.isBigIntLiteral(this) ? "BigIntLiteral " + this.text + "n" :
2699                                                         ts.isTypeParameterDeclaration(this) ? "TypeParameterDeclaration" :
2700                                                             ts.isParameter(this) ? "ParameterDeclaration" :
2701                                                                 ts.isConstructorDeclaration(this) ? "ConstructorDeclaration" :
2702                                                                     ts.isGetAccessorDeclaration(this) ? "GetAccessorDeclaration" :
2703                                                                         ts.isSetAccessorDeclaration(this) ? "SetAccessorDeclaration" :
2704                                                                             ts.isCallSignatureDeclaration(this) ? "CallSignatureDeclaration" :
2705                                                                                 ts.isConstructSignatureDeclaration(this) ? "ConstructSignatureDeclaration" :
2706                                                                                     ts.isIndexSignatureDeclaration(this) ? "IndexSignatureDeclaration" :
2707                                                                                         ts.isTypePredicateNode(this) ? "TypePredicateNode" :
2708                                                                                             ts.isTypeReferenceNode(this) ? "TypeReferenceNode" :
2709                                                                                                 ts.isFunctionTypeNode(this) ? "FunctionTypeNode" :
2710                                                                                                     ts.isConstructorTypeNode(this) ? "ConstructorTypeNode" :
2711                                                                                                         ts.isTypeQueryNode(this) ? "TypeQueryNode" :
2712                                                                                                             ts.isTypeLiteralNode(this) ? "TypeLiteralNode" :
2713                                                                                                                 ts.isArrayTypeNode(this) ? "ArrayTypeNode" :
2714                                                                                                                     ts.isTupleTypeNode(this) ? "TupleTypeNode" :
2715                                                                                                                         ts.isOptionalTypeNode(this) ? "OptionalTypeNode" :
2716                                                                                                                             ts.isRestTypeNode(this) ? "RestTypeNode" :
2717                                                                                                                                 ts.isUnionTypeNode(this) ? "UnionTypeNode" :
2718                                                                                                                                     ts.isIntersectionTypeNode(this) ? "IntersectionTypeNode" :
2719                                                                                                                                         ts.isConditionalTypeNode(this) ? "ConditionalTypeNode" :
2720                                                                                                                                             ts.isInferTypeNode(this) ? "InferTypeNode" :
2721                                                                                                                                                 ts.isParenthesizedTypeNode(this) ? "ParenthesizedTypeNode" :
2722                                                                                                                                                     ts.isThisTypeNode(this) ? "ThisTypeNode" :
2723                                                                                                                                                         ts.isTypeOperatorNode(this) ? "TypeOperatorNode" :
2724                                                                                                                                                             ts.isIndexedAccessTypeNode(this) ? "IndexedAccessTypeNode" :
2725                                                                                                                                                                 ts.isMappedTypeNode(this) ? "MappedTypeNode" :
2726                                                                                                                                                                     ts.isLiteralTypeNode(this) ? "LiteralTypeNode" :
2727                                                                                                                                                                         ts.isNamedTupleMember(this) ? "NamedTupleMember" :
2728                                                                                                                                                                             ts.isImportTypeNode(this) ? "ImportTypeNode" :
2729                                                                                                                                                                                 formatSyntaxKind(this.kind);
2730                                 return "" + nodeHeader + (this.flags ? " (" + formatNodeFlags(this.flags) + ")" : "");
2731                             }
2732                         },
2733                         __debugKind: { get: function () { return formatSyntaxKind(this.kind); } },
2734                         __debugNodeFlags: { get: function () { return formatNodeFlags(this.flags); } },
2735                         __debugModifierFlags: { get: function () { return formatModifierFlags(ts.getEffectiveModifierFlagsNoCache(this)); } },
2736                         __debugTransformFlags: { get: function () { return formatTransformFlags(this.transformFlags); } },
2737                         __debugIsParseTreeNode: { get: function () { return ts.isParseTreeNode(this); } },
2738                         __debugEmitFlags: { get: function () { return formatEmitFlags(ts.getEmitFlags(this)); } },
2739                         __debugGetText: {
2740                             value: function (includeTrivia) {
2741                                 if (ts.nodeIsSynthesized(this))
2742                                     return "";
2743                                 // avoid recomputing
2744                                 var map = getWeakNodeTextMap();
2745                                 var text = map === null || map === void 0 ? void 0 : map.get(this);
2746                                 if (text === undefined) {
2747                                     var parseNode = ts.getParseTreeNode(this);
2748                                     var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode);
2749                                     text = sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
2750                                     map === null || map === void 0 ? void 0 : map.set(this, text);
2751                                 }
2752                                 return text;
2753                             }
2754                         }
2755                     });
2756                 }
2757             }
2758             // attempt to load extended debugging information
2759             try {
2760                 if (ts.sys && ts.sys.require) {
2761                     var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath()));
2762                     var result = ts.sys.require(basePath, "./compiler-debug");
2763                     if (!result.error) {
2764                         result.module.init(ts);
2765                         extendedDebugModule = result.module;
2766                     }
2767                 }
2768             }
2769             catch (_a) {
2770                 // do nothing
2771             }
2772             isDebugInfoEnabled = true;
2773         }
2774         Debug.enableDebugInfo = enableDebugInfo;
2775         function formatDeprecationMessage(name, error, errorAfter, since, message) {
2776             var deprecationMessage = error ? "DeprecationError: " : "DeprecationWarning: ";
2777             deprecationMessage += "'" + name + "' ";
2778             deprecationMessage += since ? "has been deprecated since v" + since : "is deprecated";
2779             deprecationMessage += error ? " and can no longer be used." : errorAfter ? " and will no longer be usable after v" + errorAfter + "." : ".";
2780             deprecationMessage += message ? " " + ts.formatStringFromArgs(message, [name], 0) : "";
2781             return deprecationMessage;
2782         }
2783         function createErrorDeprecation(name, errorAfter, since, message) {
2784             var deprecationMessage = formatDeprecationMessage(name, /*error*/ true, errorAfter, since, message);
2785             return function () {
2786                 throw new TypeError(deprecationMessage);
2787             };
2788         }
2789         function createWarningDeprecation(name, errorAfter, since, message) {
2790             var hasWrittenDeprecation = false;
2791             return function () {
2792                 if (!hasWrittenDeprecation) {
2793                     log.warn(formatDeprecationMessage(name, /*error*/ false, errorAfter, since, message));
2794                     hasWrittenDeprecation = true;
2795                 }
2796             };
2797         }
2798         function createDeprecation(name, options) {
2799             var _a, _b;
2800             if (options === void 0) { options = {}; }
2801             var version = typeof options.typeScriptVersion === "string" ? new ts.Version(options.typeScriptVersion) : (_a = options.typeScriptVersion) !== null && _a !== void 0 ? _a : getTypeScriptVersion();
2802             var errorAfter = typeof options.errorAfter === "string" ? new ts.Version(options.errorAfter) : options.errorAfter;
2803             var warnAfter = typeof options.warnAfter === "string" ? new ts.Version(options.warnAfter) : options.warnAfter;
2804             var since = typeof options.since === "string" ? new ts.Version(options.since) : (_b = options.since) !== null && _b !== void 0 ? _b : warnAfter;
2805             var error = options.error || errorAfter && version.compareTo(errorAfter) <= 0;
2806             var warn = !warnAfter || version.compareTo(warnAfter) >= 0;
2807             return error ? createErrorDeprecation(name, errorAfter, since, options.message) :
2808                 warn ? createWarningDeprecation(name, errorAfter, since, options.message) :
2809                     ts.noop;
2810         }
2811         function wrapFunction(deprecation, func) {
2812             return function () {
2813                 deprecation();
2814                 return func.apply(this, arguments);
2815             };
2816         }
2817         function deprecate(func, options) {
2818             var deprecation = createDeprecation(getFunctionName(func), options);
2819             return wrapFunction(deprecation, func);
2820         }
2821         Debug.deprecate = deprecate;
2822     })(Debug = ts.Debug || (ts.Debug = {}));
2823 })(ts || (ts = {}));
2824 /* @internal */
2825 var ts;
2826 (function (ts) {
2827     // https://semver.org/#spec-item-2
2828     // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative
2829     // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor
2830     // > version, and Z is the patch version. Each element MUST increase numerically.
2831     //
2832     // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default
2833     // value of `0`.
2834     var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2835     // https://semver.org/#spec-item-9
2836     // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated
2837     // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII
2838     // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers
2839     // > MUST NOT include leading zeroes.
2840     var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i;
2841     // https://semver.org/#spec-item-10
2842     // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated
2843     // > identifiers immediately following the patch or pre-release version. Identifiers MUST
2844     // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
2845     var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i;
2846     // https://semver.org/#spec-item-9
2847     // > Numeric identifiers MUST NOT include leading zeroes.
2848     var numericIdentifierRegExp = /^(0|[1-9]\d*)$/;
2849     /**
2850      * Describes a precise semantic version number, https://semver.org
2851      */
2852     var Version = /** @class */ (function () {
2853         function Version(major, minor, patch, prerelease, build) {
2854             if (minor === void 0) { minor = 0; }
2855             if (patch === void 0) { patch = 0; }
2856             if (prerelease === void 0) { prerelease = ""; }
2857             if (build === void 0) { build = ""; }
2858             if (typeof major === "string") {
2859                 var result = ts.Debug.checkDefined(tryParseComponents(major), "Invalid version");
2860                 (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build);
2861             }
2862             ts.Debug.assert(major >= 0, "Invalid argument: major");
2863             ts.Debug.assert(minor >= 0, "Invalid argument: minor");
2864             ts.Debug.assert(patch >= 0, "Invalid argument: patch");
2865             ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease");
2866             ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build");
2867             this.major = major;
2868             this.minor = minor;
2869             this.patch = patch;
2870             this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray;
2871             this.build = build ? build.split(".") : ts.emptyArray;
2872         }
2873         Version.tryParse = function (text) {
2874             var result = tryParseComponents(text);
2875             if (!result)
2876                 return undefined;
2877             var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build;
2878             return new Version(major, minor, patch, prerelease, build);
2879         };
2880         Version.prototype.compareTo = function (other) {
2881             // https://semver.org/#spec-item-11
2882             // > Precedence is determined by the first difference when comparing each of these
2883             // > identifiers from left to right as follows: Major, minor, and patch versions are
2884             // > always compared numerically.
2885             //
2886             // https://semver.org/#spec-item-11
2887             // > Precedence for two pre-release versions with the same major, minor, and patch version
2888             // > MUST be determined by comparing each dot separated identifier from left to right until
2889             // > a difference is found [...]
2890             //
2891             // https://semver.org/#spec-item-11
2892             // > Build metadata does not figure into precedence
2893             if (this === other)
2894                 return 0 /* EqualTo */;
2895             if (other === undefined)
2896                 return 1 /* GreaterThan */;
2897             return ts.compareValues(this.major, other.major)
2898                 || ts.compareValues(this.minor, other.minor)
2899                 || ts.compareValues(this.patch, other.patch)
2900                 || comparePrereleaseIdentifiers(this.prerelease, other.prerelease);
2901         };
2902         Version.prototype.increment = function (field) {
2903             switch (field) {
2904                 case "major": return new Version(this.major + 1, 0, 0);
2905                 case "minor": return new Version(this.major, this.minor + 1, 0);
2906                 case "patch": return new Version(this.major, this.minor, this.patch + 1);
2907                 default: return ts.Debug.assertNever(field);
2908             }
2909         };
2910         Version.prototype.toString = function () {
2911             var result = this.major + "." + this.minor + "." + this.patch;
2912             if (ts.some(this.prerelease))
2913                 result += "-" + this.prerelease.join(".");
2914             if (ts.some(this.build))
2915                 result += "+" + this.build.join(".");
2916             return result;
2917         };
2918         Version.zero = new Version(0, 0, 0);
2919         return Version;
2920     }());
2921     ts.Version = Version;
2922     function tryParseComponents(text) {
2923         var match = versionRegExp.exec(text);
2924         if (!match)
2925             return undefined;
2926         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;
2927         if (prerelease && !prereleaseRegExp.test(prerelease))
2928             return undefined;
2929         if (build && !buildRegExp.test(build))
2930             return undefined;
2931         return {
2932             major: parseInt(major, 10),
2933             minor: parseInt(minor, 10),
2934             patch: parseInt(patch, 10),
2935             prerelease: prerelease,
2936             build: build
2937         };
2938     }
2939     function comparePrereleaseIdentifiers(left, right) {
2940         // https://semver.org/#spec-item-11
2941         // > When major, minor, and patch are equal, a pre-release version has lower precedence
2942         // > than a normal version.
2943         if (left === right)
2944             return 0 /* EqualTo */;
2945         if (left.length === 0)
2946             return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */;
2947         if (right.length === 0)
2948             return -1 /* LessThan */;
2949         // https://semver.org/#spec-item-11
2950         // > Precedence for two pre-release versions with the same major, minor, and patch version
2951         // > MUST be determined by comparing each dot separated identifier from left to right until
2952         // > a difference is found [...]
2953         var length = Math.min(left.length, right.length);
2954         for (var i = 0; i < length; i++) {
2955             var leftIdentifier = left[i];
2956             var rightIdentifier = right[i];
2957             if (leftIdentifier === rightIdentifier)
2958                 continue;
2959             var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier);
2960             var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier);
2961             if (leftIsNumeric || rightIsNumeric) {
2962                 // https://semver.org/#spec-item-11
2963                 // > Numeric identifiers always have lower precedence than non-numeric identifiers.
2964                 if (leftIsNumeric !== rightIsNumeric)
2965                     return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */;
2966                 // https://semver.org/#spec-item-11
2967                 // > identifiers consisting of only digits are compared numerically
2968                 var result = ts.compareValues(+leftIdentifier, +rightIdentifier);
2969                 if (result)
2970                     return result;
2971             }
2972             else {
2973                 // https://semver.org/#spec-item-11
2974                 // > identifiers with letters or hyphens are compared lexically in ASCII sort order.
2975                 var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier);
2976                 if (result)
2977                     return result;
2978             }
2979         }
2980         // https://semver.org/#spec-item-11
2981         // > A larger set of pre-release fields has a higher precedence than a smaller set, if all
2982         // > of the preceding identifiers are equal.
2983         return ts.compareValues(left.length, right.length);
2984     }
2985     /**
2986      * Describes a semantic version range, per https://github.com/npm/node-semver#ranges
2987      */
2988     var VersionRange = /** @class */ (function () {
2989         function VersionRange(spec) {
2990             this._alternatives = spec ? ts.Debug.checkDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray;
2991         }
2992         VersionRange.tryParse = function (text) {
2993             var sets = parseRange(text);
2994             if (sets) {
2995                 var range = new VersionRange("");
2996                 range._alternatives = sets;
2997                 return range;
2998             }
2999             return undefined;
3000         };
3001         VersionRange.prototype.test = function (version) {
3002             if (typeof version === "string")
3003                 version = new Version(version);
3004             return testDisjunction(version, this._alternatives);
3005         };
3006         VersionRange.prototype.toString = function () {
3007             return formatDisjunction(this._alternatives);
3008         };
3009         return VersionRange;
3010     }());
3011     ts.VersionRange = VersionRange;
3012     // https://github.com/npm/node-semver#range-grammar
3013     //
3014     // range-set    ::= range ( logical-or range ) *
3015     // range        ::= hyphen | simple ( ' ' simple ) * | ''
3016     // logical-or   ::= ( ' ' ) * '||' ( ' ' ) *
3017     var logicalOrRegExp = /\s*\|\|\s*/g;
3018     var whitespaceRegExp = /\s+/g;
3019     // https://github.com/npm/node-semver#range-grammar
3020     //
3021     // partial      ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
3022     // xr           ::= 'x' | 'X' | '*' | nr
3023     // nr           ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
3024     // qualifier    ::= ( '-' pre )? ( '+' build )?
3025     // pre          ::= parts
3026     // build        ::= parts
3027     // parts        ::= part ( '.' part ) *
3028     // part         ::= nr | [-0-9A-Za-z]+
3029     var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
3030     // https://github.com/npm/node-semver#range-grammar
3031     //
3032     // hyphen       ::= partial ' - ' partial
3033     var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i;
3034     // https://github.com/npm/node-semver#range-grammar
3035     //
3036     // simple       ::= primitive | partial | tilde | caret
3037     // primitive    ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
3038     // tilde        ::= '~' partial
3039     // caret        ::= '^' partial
3040     var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
3041     function parseRange(text) {
3042         var alternatives = [];
3043         for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) {
3044             var range = _a[_i];
3045             if (!range)
3046                 continue;
3047             var comparators = [];
3048             var match = hyphenRegExp.exec(range);
3049             if (match) {
3050                 if (!parseHyphen(match[1], match[2], comparators))
3051                     return undefined;
3052             }
3053             else {
3054                 for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) {
3055                     var simple = _c[_b];
3056                     var match_1 = rangeRegExp.exec(simple);
3057                     if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators))
3058                         return undefined;
3059                 }
3060             }
3061             alternatives.push(comparators);
3062         }
3063         return alternatives;
3064     }
3065     function parsePartial(text) {
3066         var match = partialRegExp.exec(text);
3067         if (!match)
3068             return undefined;
3069         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];
3070         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);
3071         return { version: version, major: major, minor: minor, patch: patch };
3072     }
3073     function parseHyphen(left, right, comparators) {
3074         var leftResult = parsePartial(left);
3075         if (!leftResult)
3076             return false;
3077         var rightResult = parsePartial(right);
3078         if (!rightResult)
3079             return false;
3080         if (!isWildcard(leftResult.major)) {
3081             comparators.push(createComparator(">=", leftResult.version));
3082         }
3083         if (!isWildcard(rightResult.major)) {
3084             comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) :
3085                 isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) :
3086                     createComparator("<=", rightResult.version));
3087         }
3088         return true;
3089     }
3090     function parseComparator(operator, text, comparators) {
3091         var result = parsePartial(text);
3092         if (!result)
3093             return false;
3094         var version = result.version, major = result.major, minor = result.minor, patch = result.patch;
3095         if (!isWildcard(major)) {
3096             switch (operator) {
3097                 case "~":
3098                     comparators.push(createComparator(">=", version));
3099                     comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" :
3100                         "minor")));
3101                     break;
3102                 case "^":
3103                     comparators.push(createComparator(">=", version));
3104                     comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" :
3105                         version.minor > 0 || isWildcard(patch) ? "minor" :
3106                             "patch")));
3107                     break;
3108                 case "<":
3109                 case ">=":
3110                     comparators.push(createComparator(operator, version));
3111                     break;
3112                 case "<=":
3113                 case ">":
3114                     comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) :
3115                         isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) :
3116                             createComparator(operator, version));
3117                     break;
3118                 case "=":
3119                 case undefined:
3120                     if (isWildcard(minor) || isWildcard(patch)) {
3121                         comparators.push(createComparator(">=", version));
3122                         comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor")));
3123                     }
3124                     else {
3125                         comparators.push(createComparator("=", version));
3126                     }
3127                     break;
3128                 default:
3129                     // unrecognized
3130                     return false;
3131             }
3132         }
3133         else if (operator === "<" || operator === ">") {
3134             comparators.push(createComparator("<", Version.zero));
3135         }
3136         return true;
3137     }
3138     function isWildcard(part) {
3139         return part === "*" || part === "x" || part === "X";
3140     }
3141     function createComparator(operator, operand) {
3142         return { operator: operator, operand: operand };
3143     }
3144     function testDisjunction(version, alternatives) {
3145         // an empty disjunction is treated as "*" (all versions)
3146         if (alternatives.length === 0)
3147             return true;
3148         for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
3149             var alternative = alternatives_1[_i];
3150             if (testAlternative(version, alternative))
3151                 return true;
3152         }
3153         return false;
3154     }
3155     function testAlternative(version, comparators) {
3156         for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) {
3157             var comparator = comparators_1[_i];
3158             if (!testComparator(version, comparator.operator, comparator.operand))
3159                 return false;
3160         }
3161         return true;
3162     }
3163     function testComparator(version, operator, operand) {
3164         var cmp = version.compareTo(operand);
3165         switch (operator) {
3166             case "<": return cmp < 0;
3167             case "<=": return cmp <= 0;
3168             case ">": return cmp > 0;
3169             case ">=": return cmp >= 0;
3170             case "=": return cmp === 0;
3171             default: return ts.Debug.assertNever(operator);
3172         }
3173     }
3174     function formatDisjunction(alternatives) {
3175         return ts.map(alternatives, formatAlternative).join(" || ") || "*";
3176     }
3177     function formatAlternative(comparators) {
3178         return ts.map(comparators, formatComparator).join(" ");
3179     }
3180     function formatComparator(comparator) {
3181         return "" + comparator.operator + comparator.operand;
3182     }
3183 })(ts || (ts = {}));
3184 /*@internal*/
3185 var ts;
3186 (function (ts) {
3187     // The following definitions provide the minimum compatible support for the Web Performance User Timings API
3188     // between browsers and NodeJS:
3189     // eslint-disable-next-line @typescript-eslint/naming-convention
3190     function hasRequiredAPI(performance, PerformanceObserver) {
3191         return typeof performance === "object" &&
3192             typeof performance.timeOrigin === "number" &&
3193             typeof performance.mark === "function" &&
3194             typeof performance.measure === "function" &&
3195             typeof performance.now === "function" &&
3196             typeof PerformanceObserver === "function";
3197     }
3198     function tryGetWebPerformanceHooks() {
3199         if (typeof performance === "object" &&
3200             typeof PerformanceObserver === "function" &&
3201             hasRequiredAPI(performance, PerformanceObserver)) {
3202             return {
3203                 // For now we always write native performance events when running in the browser. We may
3204                 // make this conditional in the future if we find that native web performance hooks
3205                 // in the browser also slow down compilation.
3206                 shouldWriteNativeEvents: true,
3207                 performance: performance,
3208                 PerformanceObserver: PerformanceObserver
3209             };
3210         }
3211     }
3212     function tryGetNodePerformanceHooks() {
3213         if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof module === "object" && typeof require === "function") {
3214             try {
3215                 var performance_1;
3216                 var _a = require("perf_hooks"), nodePerformance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver;
3217                 if (hasRequiredAPI(nodePerformance_1, PerformanceObserver_1)) {
3218                     performance_1 = nodePerformance_1;
3219                     // There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not
3220                     // match the Web Performance API specification. Node's implementation did not allow
3221                     // optional `start` and `end` arguments for `performance.measure`.
3222                     // See https://github.com/nodejs/node/pull/32651 for more information.
3223                     var version_1 = new ts.Version(process.versions.node);
3224                     var range = new ts.VersionRange("<12.16.3 || 13 <13.13");
3225                     if (range.test(version_1)) {
3226                         performance_1 = {
3227                             get timeOrigin() { return nodePerformance_1.timeOrigin; },
3228                             now: function () { return nodePerformance_1.now(); },
3229                             mark: function (name) { return nodePerformance_1.mark(name); },
3230                             measure: function (name, start, end) {
3231                                 if (start === void 0) { start = "nodeStart"; }
3232                                 if (end === undefined) {
3233                                     end = "__performance.measure-fix__";
3234                                     nodePerformance_1.mark(end);
3235                                 }
3236                                 nodePerformance_1.measure(name, start, end);
3237                                 if (end === "__performance.measure-fix__") {
3238                                     nodePerformance_1.clearMarks("__performance.measure-fix__");
3239                                 }
3240                             }
3241                         };
3242                     }
3243                     return {
3244                         // By default, only write native events when generating a cpu profile or using the v8 profiler.
3245                         shouldWriteNativeEvents: false,
3246                         performance: performance_1,
3247                         PerformanceObserver: PerformanceObserver_1
3248                     };
3249                 }
3250             }
3251             catch (_b) {
3252                 // ignore errors
3253             }
3254         }
3255     }
3256     // Unlike with the native Map/Set 'tryGet' functions in corePublic.ts, we eagerly evaluate these
3257     // since we will need them for `timestamp`, below.
3258     var nativePerformanceHooks = tryGetWebPerformanceHooks() || tryGetNodePerformanceHooks();
3259     var nativePerformance = nativePerformanceHooks === null || nativePerformanceHooks === void 0 ? void 0 : nativePerformanceHooks.performance;
3260     function tryGetNativePerformanceHooks() {
3261         return nativePerformanceHooks;
3262     }
3263     ts.tryGetNativePerformanceHooks = tryGetNativePerformanceHooks;
3264     /** Gets a timestamp with (at least) ms resolution */
3265     ts.timestamp = nativePerformance ? function () { return nativePerformance.now(); } :
3266         Date.now ? Date.now :
3267             function () { return +(new Date()); };
3268 })(ts || (ts = {}));
3269 /*@internal*/
3270 /** Performance measurements for the compiler. */
3271 var ts;
3272 (function (ts) {
3273     var performance;
3274     (function (performance) {
3275         var perfHooks;
3276         // when set, indicates the implementation of `Performance` to use for user timing.
3277         // when unset, indicates user timing is unavailable or disabled.
3278         var performanceImpl;
3279         function createTimerIf(condition, measureName, startMarkName, endMarkName) {
3280             return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer;
3281         }
3282         performance.createTimerIf = createTimerIf;
3283         function createTimer(measureName, startMarkName, endMarkName) {
3284             var enterCount = 0;
3285             return {
3286                 enter: enter,
3287                 exit: exit
3288             };
3289             function enter() {
3290                 if (++enterCount === 1) {
3291                     mark(startMarkName);
3292                 }
3293             }
3294             function exit() {
3295                 if (--enterCount === 0) {
3296                     mark(endMarkName);
3297                     measure(measureName, startMarkName, endMarkName);
3298                 }
3299                 else if (enterCount < 0) {
3300                     ts.Debug.fail("enter/exit count does not match.");
3301                 }
3302             }
3303         }
3304         performance.createTimer = createTimer;
3305         performance.nullTimer = { enter: ts.noop, exit: ts.noop };
3306         var enabled = false;
3307         var timeorigin = ts.timestamp();
3308         var marks = new ts.Map();
3309         var counts = new ts.Map();
3310         var durations = new ts.Map();
3311         /**
3312          * Marks a performance event.
3313          *
3314          * @param markName The name of the mark.
3315          */
3316         function mark(markName) {
3317             var _a;
3318             if (enabled) {
3319                 var count = (_a = counts.get(markName)) !== null && _a !== void 0 ? _a : 0;
3320                 counts.set(markName, count + 1);
3321                 marks.set(markName, ts.timestamp());
3322                 performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName);
3323             }
3324         }
3325         performance.mark = mark;
3326         /**
3327          * Adds a performance measurement with the specified name.
3328          *
3329          * @param measureName The name of the performance measurement.
3330          * @param startMarkName The name of the starting mark. If not supplied, the point at which the
3331          *      profiler was enabled is used.
3332          * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is
3333          *      used.
3334          */
3335         function measure(measureName, startMarkName, endMarkName) {
3336             var _a, _b;
3337             if (enabled) {
3338                 var end = (_a = (endMarkName !== undefined ? marks.get(endMarkName) : undefined)) !== null && _a !== void 0 ? _a : ts.timestamp();
3339                 var start = (_b = (startMarkName !== undefined ? marks.get(startMarkName) : undefined)) !== null && _b !== void 0 ? _b : timeorigin;
3340                 var previousDuration = durations.get(measureName) || 0;
3341                 durations.set(measureName, previousDuration + (end - start));
3342                 performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName);
3343             }
3344         }
3345         performance.measure = measure;
3346         /**
3347          * Gets the number of times a marker was encountered.
3348          *
3349          * @param markName The name of the mark.
3350          */
3351         function getCount(markName) {
3352             return counts.get(markName) || 0;
3353         }
3354         performance.getCount = getCount;
3355         /**
3356          * Gets the total duration of all measurements with the supplied name.
3357          *
3358          * @param measureName The name of the measure whose durations should be accumulated.
3359          */
3360         function getDuration(measureName) {
3361             return durations.get(measureName) || 0;
3362         }
3363         performance.getDuration = getDuration;
3364         /**
3365          * Iterate over each measure, performing some action
3366          *
3367          * @param cb The action to perform for each measure
3368          */
3369         function forEachMeasure(cb) {
3370             durations.forEach(function (duration, measureName) { return cb(measureName, duration); });
3371         }
3372         performance.forEachMeasure = forEachMeasure;
3373         /**
3374          * Indicates whether the performance API is enabled.
3375          */
3376         function isEnabled() {
3377             return enabled;
3378         }
3379         performance.isEnabled = isEnabled;
3380         /** Enables (and resets) performance measurements for the compiler. */
3381         function enable(system) {
3382             var _a;
3383             if (system === void 0) { system = ts.sys; }
3384             if (!enabled) {
3385                 enabled = true;
3386                 perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks());
3387                 if (perfHooks) {
3388                     timeorigin = perfHooks.performance.timeOrigin;
3389                     // NodeJS's Web Performance API is currently slower than expected, but we'd still like
3390                     // to be able to leverage native trace events when node is run with either `--cpu-prof`
3391                     // or `--prof`, if we're running with our own `--generateCpuProfile` flag, or when
3392                     // running in debug mode (since its possible to generate a cpu profile while debugging).
3393                     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)) {
3394                         performanceImpl = perfHooks.performance;
3395                     }
3396                 }
3397             }
3398             return true;
3399         }
3400         performance.enable = enable;
3401         /** Disables performance measurements for the compiler. */
3402         function disable() {
3403             if (enabled) {
3404                 marks.clear();
3405                 counts.clear();
3406                 durations.clear();
3407                 performanceImpl = undefined;
3408                 enabled = false;
3409             }
3410         }
3411         performance.disable = disable;
3412     })(performance = ts.performance || (ts.performance = {}));
3413 })(ts || (ts = {}));
3414 /* @internal */
3415 var ts;
3416 (function (ts) {
3417     var _a;
3418     var nullLogger = {
3419         logEvent: ts.noop,
3420         logErrEvent: ts.noop,
3421         logPerfEvent: ts.noop,
3422         logInfoEvent: ts.noop,
3423         logStartCommand: ts.noop,
3424         logStopCommand: ts.noop,
3425         logStartUpdateProgram: ts.noop,
3426         logStopUpdateProgram: ts.noop,
3427         logStartUpdateGraph: ts.noop,
3428         logStopUpdateGraph: ts.noop,
3429         logStartResolveModule: ts.noop,
3430         logStopResolveModule: ts.noop,
3431         logStartParseSourceFile: ts.noop,
3432         logStopParseSourceFile: ts.noop,
3433         logStartReadFile: ts.noop,
3434         logStopReadFile: ts.noop,
3435         logStartBindFile: ts.noop,
3436         logStopBindFile: ts.noop,
3437         logStartScheduledOperation: ts.noop,
3438         logStopScheduledOperation: ts.noop,
3439     };
3440     // Load optional module to enable Event Tracing for Windows
3441     // See https://github.com/microsoft/typescript-etw for more information
3442     var etwModule;
3443     try {
3444         var etwModulePath = (_a = process.env.TS_ETW_MODULE_PATH) !== null && _a !== void 0 ? _a : "./node_modules/@microsoft/typescript-etw";
3445         // require() will throw an exception if the module is not found
3446         // It may also return undefined if not installed properly
3447         etwModule = require(etwModulePath);
3448     }
3449     catch (e) {
3450         etwModule = undefined;
3451     }
3452     /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
3453     ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
3454 })(ts || (ts = {}));
3455 /* Tracing events for the compiler. */
3456 /*@internal*/
3457 var ts;
3458 (function (ts) {
3459     // enable the above using startTracing()
3460 })(ts || (ts = {}));
3461 // `tracingEnabled` should never be used directly, only through the above
3462 /* @internal */
3463 (function (ts) {
3464     var tracingEnabled;
3465     (function (tracingEnabled) {
3466         var Mode;
3467         (function (Mode) {
3468             Mode[Mode["Project"] = 0] = "Project";
3469             Mode[Mode["Build"] = 1] = "Build";
3470             Mode[Mode["Server"] = 2] = "Server";
3471         })(Mode = tracingEnabled.Mode || (tracingEnabled.Mode = {}));
3472         var fs;
3473         var traceCount = 0;
3474         var traceFd = 0;
3475         var mode;
3476         var legendPath;
3477         var legend = [];
3478         ;
3479         /** Starts tracing for the given project. */
3480         function startTracing(tracingMode, traceDir, configFilePath) {
3481             ts.Debug.assert(!ts.tracing, "Tracing already started");
3482             if (fs === undefined) {
3483                 try {
3484                     fs = require("fs");
3485                 }
3486                 catch (e) {
3487                     throw new Error("tracing requires having fs\n(original error: " + (e.message || e) + ")");
3488                 }
3489             }
3490             mode = tracingMode;
3491             if (legendPath === undefined) {
3492                 legendPath = ts.combinePaths(traceDir, "legend.json");
3493             }
3494             // Note that writing will fail later on if it exists and is not a directory
3495             if (!fs.existsSync(traceDir)) {
3496                 fs.mkdirSync(traceDir, { recursive: true });
3497             }
3498             var countPart = mode === 1 /* Build */ ? "." + process.pid + "-" + ++traceCount
3499                 : mode === 2 /* Server */ ? "." + process.pid
3500                     : "";
3501             var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json");
3502             var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json");
3503             legend.push({
3504                 configFilePath: configFilePath,
3505                 tracePath: tracePath,
3506                 typesPath: typesPath,
3507             });
3508             traceFd = fs.openSync(tracePath, "w");
3509             ts.tracing = tracingEnabled; // only when traceFd is properly set
3510             // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import)
3511             var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 };
3512             fs.writeSync(traceFd, "[\n"
3513                 + [__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" })]
3514                     .map(function (v) { return JSON.stringify(v); }).join(",\n"));
3515         }
3516         tracingEnabled.startTracing = startTracing;
3517         /** Stops tracing for the in-progress project and dumps the type catalog. */
3518         function stopTracing(typeCatalog) {
3519             ts.Debug.assert(ts.tracing, "Tracing is not in progress");
3520             ts.Debug.assert(!!typeCatalog === (mode !== 2 /* Server */)); // Have a type catalog iff not in server mode
3521             fs.writeSync(traceFd, "\n]\n");
3522             fs.closeSync(traceFd);
3523             ts.tracing = undefined;
3524             if (typeCatalog) {
3525                 dumpTypes(typeCatalog);
3526             }
3527             else {
3528                 // We pre-computed this path for convenience, but clear it
3529                 // now that the file won't be created.
3530                 legend[legend.length - 1].typesPath = undefined;
3531             }
3532         }
3533         tracingEnabled.stopTracing = stopTracing;
3534         var Phase;
3535         (function (Phase) {
3536             Phase["Parse"] = "parse";
3537             Phase["Program"] = "program";
3538             Phase["Bind"] = "bind";
3539             Phase["Check"] = "check";
3540             Phase["CheckTypes"] = "checkTypes";
3541             Phase["Emit"] = "emit";
3542             Phase["Session"] = "session";
3543         })(Phase = tracingEnabled.Phase || (tracingEnabled.Phase = {}));
3544         function instant(phase, name, args) {
3545             writeEvent("I", phase, name, args, "\"s\":\"g\"");
3546         }
3547         tracingEnabled.instant = instant;
3548         var eventStack = [];
3549         /**
3550          * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event
3551          * never terminates (typically for reducing a scenario too big to trace to one that can be completed).
3552          * In the future we might implement an exit handler to dump unfinished events which would deprecate
3553          * these operations.
3554          */
3555         function push(phase, name, args, separateBeginAndEnd) {
3556             if (separateBeginAndEnd === void 0) { separateBeginAndEnd = false; }
3557             if (separateBeginAndEnd) {
3558                 writeEvent("B", phase, name, args);
3559             }
3560             eventStack.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp(), separateBeginAndEnd: separateBeginAndEnd });
3561         }
3562         tracingEnabled.push = push;
3563         function pop() {
3564             ts.Debug.assert(eventStack.length > 0);
3565             writeStackEvent(eventStack.length - 1, 1000 * ts.timestamp());
3566             eventStack.length--;
3567         }
3568         tracingEnabled.pop = pop;
3569         function popAll() {
3570             var endTime = 1000 * ts.timestamp();
3571             for (var i = eventStack.length - 1; i >= 0; i--) {
3572                 writeStackEvent(i, endTime);
3573             }
3574             eventStack.length = 0;
3575         }
3576         tracingEnabled.popAll = popAll;
3577         // sample every 10ms
3578         var sampleInterval = 1000 * 10;
3579         function writeStackEvent(index, endTime) {
3580             var _a = eventStack[index], phase = _a.phase, name = _a.name, args = _a.args, time = _a.time, separateBeginAndEnd = _a.separateBeginAndEnd;
3581             if (separateBeginAndEnd) {
3582                 writeEvent("E", phase, name, args, /*extras*/ undefined, endTime);
3583             }
3584             // test if [time,endTime) straddles a sampling point
3585             else if (sampleInterval - (time % sampleInterval) <= endTime - time) {
3586                 writeEvent("X", phase, name, args, "\"dur\":" + (endTime - time), time);
3587             }
3588         }
3589         function writeEvent(eventType, phase, name, args, extras, time) {
3590             if (time === void 0) { time = 1000 * ts.timestamp(); }
3591             // In server mode, there's no easy way to dump type information, so we drop events that would require it.
3592             if (mode === 2 /* Server */ && phase === "checkTypes" /* CheckTypes */)
3593                 return;
3594             ts.performance.mark("beginTracing");
3595             fs.writeSync(traceFd, ",\n{\"pid\":1,\"tid\":1,\"ph\":\"" + eventType + "\",\"cat\":\"" + phase + "\",\"ts\":" + time + ",\"name\":\"" + name + "\"");
3596             if (extras)
3597                 fs.writeSync(traceFd, "," + extras);
3598             if (args)
3599                 fs.writeSync(traceFd, ",\"args\":" + JSON.stringify(args));
3600             fs.writeSync(traceFd, "}");
3601             ts.performance.mark("endTracing");
3602             ts.performance.measure("Tracing", "beginTracing", "endTracing");
3603         }
3604         function indexFromOne(lc) {
3605             return {
3606                 line: lc.line + 1,
3607                 character: lc.character + 1,
3608             };
3609         }
3610         function dumpTypes(types) {
3611             var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
3612             ts.performance.mark("beginDumpTypes");
3613             var typesPath = legend[legend.length - 1].typesPath;
3614             var typesFd = fs.openSync(typesPath, "w");
3615             var recursionIdentityMap = new ts.Map();
3616             // Cleverness: no line break here so that the type ID will match the line number
3617             fs.writeSync(typesFd, "[");
3618             var numTypes = types.length;
3619             for (var i = 0; i < numTypes; i++) {
3620                 var type = types[i];
3621                 var objectFlags = type.objectFlags;
3622                 var symbol = (_a = type.aliasSymbol) !== null && _a !== void 0 ? _a : type.symbol;
3623                 var firstDeclaration = (_b = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _b === void 0 ? void 0 : _b[0];
3624                 var firstFile = firstDeclaration && ts.getSourceFileOfNode(firstDeclaration);
3625                 // It's slow to compute the display text, so skip it unless it's really valuable (or cheap)
3626                 var display = void 0;
3627                 if ((objectFlags & 16 /* Anonymous */) | (type.flags & 2944 /* Literal */)) {
3628                     try {
3629                         display = (_c = type.checker) === null || _c === void 0 ? void 0 : _c.typeToString(type);
3630                     }
3631                     catch (_s) {
3632                         display = undefined;
3633                     }
3634                 }
3635                 var indexedAccessProperties = {};
3636                 if (type.flags & 8388608 /* IndexedAccess */) {
3637                     var indexedAccessType = type;
3638                     indexedAccessProperties = {
3639                         indexedAccessObjectType: (_d = indexedAccessType.objectType) === null || _d === void 0 ? void 0 : _d.id,
3640                         indexedAccessIndexType: (_e = indexedAccessType.indexType) === null || _e === void 0 ? void 0 : _e.id,
3641                     };
3642                 }
3643                 var referenceProperties = {};
3644                 if (objectFlags & 4 /* Reference */) {
3645                     var referenceType = type;
3646                     referenceProperties = {
3647                         instantiatedType: (_f = referenceType.target) === null || _f === void 0 ? void 0 : _f.id,
3648                         typeArguments: (_g = referenceType.resolvedTypeArguments) === null || _g === void 0 ? void 0 : _g.map(function (t) { return t.id; }),
3649                     };
3650                 }
3651                 var conditionalProperties = {};
3652                 if (type.flags & 16777216 /* Conditional */) {
3653                     var conditionalType = type;
3654                     conditionalProperties = {
3655                         conditionalCheckType: (_h = conditionalType.checkType) === null || _h === void 0 ? void 0 : _h.id,
3656                         conditionalExtendsType: (_j = conditionalType.extendsType) === null || _j === void 0 ? void 0 : _j.id,
3657                         conditionalTrueType: (_l = (_k = conditionalType.resolvedTrueType) === null || _k === void 0 ? void 0 : _k.id) !== null && _l !== void 0 ? _l : -1,
3658                         conditionalFalseType: (_o = (_m = conditionalType.resolvedFalseType) === null || _m === void 0 ? void 0 : _m.id) !== null && _o !== void 0 ? _o : -1,
3659                     };
3660                 }
3661                 // We can't print out an arbitrary object, so just assign each one a unique number.
3662                 // Don't call it an "id" so people don't treat it as a type id.
3663                 var recursionToken = void 0;
3664                 var recursionIdentity = type.checker.getRecursionIdentity(type);
3665                 if (recursionIdentity) {
3666                     recursionToken = recursionIdentityMap.get(recursionIdentity);
3667                     if (!recursionToken) {
3668                         recursionToken = recursionIdentityMap.size;
3669                         recursionIdentityMap.set(recursionIdentity, recursionToken);
3670                     }
3671                 }
3672                 var descriptor = __assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, unionTypes: (type.flags & 1048576 /* Union */) ? (_p = type.types) === null || _p === void 0 ? void 0 : _p.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152 /* Intersection */) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_q = type.aliasTypeArguments) === null || _q === void 0 ? void 0 : _q.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304 /* Index */) ? (_r = type.type) === null || _r === void 0 ? void 0 : _r.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), { firstDeclaration: firstDeclaration && {
3673                         path: firstFile.path,
3674                         start: indexFromOne(ts.getLineAndCharacterOfPosition(firstFile, firstDeclaration.pos)),
3675                         end: indexFromOne(ts.getLineAndCharacterOfPosition(ts.getSourceFileOfNode(firstDeclaration), firstDeclaration.end)),
3676                     }, flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display });
3677                 fs.writeSync(typesFd, JSON.stringify(descriptor));
3678                 if (i < numTypes - 1) {
3679                     fs.writeSync(typesFd, ",\n");
3680                 }
3681             }
3682             fs.writeSync(typesFd, "]\n");
3683             fs.closeSync(typesFd);
3684             ts.performance.mark("endDumpTypes");
3685             ts.performance.measure("Dump types", "beginDumpTypes", "endDumpTypes");
3686         }
3687         function dumpLegend() {
3688             if (!legendPath) {
3689                 return;
3690             }
3691             fs.writeFileSync(legendPath, JSON.stringify(legend));
3692         }
3693         tracingEnabled.dumpLegend = dumpLegend;
3694     })(tracingEnabled = ts.tracingEnabled || (ts.tracingEnabled = {}));
3695 })(ts || (ts = {}));
3696 /*@internal*/
3697 (function (ts) {
3698     // define after tracingEnabled is initialized
3699     ts.startTracing = ts.tracingEnabled.startTracing;
3700 })(ts || (ts = {}));
3701 var ts;
3702 (function (ts) {
3703     // token > SyntaxKind.Identifier => token is a keyword
3704     // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
3705     var SyntaxKind;
3706     (function (SyntaxKind) {
3707         SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
3708         SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken";
3709         SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
3710         SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
3711         SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
3712         SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
3713         // We detect and preserve #! on the first line
3714         SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
3715         // We detect and provide better error recovery when we encounter a git merge marker.  This
3716         // allows us to edit files with git-conflict markers in them in a much more pleasant manner.
3717         SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
3718         // Literals
3719         SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
3720         SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral";
3721         SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
3722         SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText";
3723         SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces";
3724         SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral";
3725         SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral";
3726         // Pseudo-literals
3727         SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead";
3728         SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle";
3729         SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail";
3730         // Punctuation
3731         SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken";
3732         SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken";
3733         SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken";
3734         SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken";
3735         SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken";
3736         SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken";
3737         SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken";
3738         SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken";
3739         SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken";
3740         SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken";
3741         SyntaxKind[SyntaxKind["QuestionDotToken"] = 28] = "QuestionDotToken";
3742         SyntaxKind[SyntaxKind["LessThanToken"] = 29] = "LessThanToken";
3743         SyntaxKind[SyntaxKind["LessThanSlashToken"] = 30] = "LessThanSlashToken";
3744         SyntaxKind[SyntaxKind["GreaterThanToken"] = 31] = "GreaterThanToken";
3745         SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 32] = "LessThanEqualsToken";
3746         SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 33] = "GreaterThanEqualsToken";
3747         SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 34] = "EqualsEqualsToken";
3748         SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 35] = "ExclamationEqualsToken";
3749         SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 36] = "EqualsEqualsEqualsToken";
3750         SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 37] = "ExclamationEqualsEqualsToken";
3751         SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 38] = "EqualsGreaterThanToken";
3752         SyntaxKind[SyntaxKind["PlusToken"] = 39] = "PlusToken";
3753         SyntaxKind[SyntaxKind["MinusToken"] = 40] = "MinusToken";
3754         SyntaxKind[SyntaxKind["AsteriskToken"] = 41] = "AsteriskToken";
3755         SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 42] = "AsteriskAsteriskToken";
3756         SyntaxKind[SyntaxKind["SlashToken"] = 43] = "SlashToken";
3757         SyntaxKind[SyntaxKind["PercentToken"] = 44] = "PercentToken";
3758         SyntaxKind[SyntaxKind["PlusPlusToken"] = 45] = "PlusPlusToken";
3759         SyntaxKind[SyntaxKind["MinusMinusToken"] = 46] = "MinusMinusToken";
3760         SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 47] = "LessThanLessThanToken";
3761         SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanToken";
3762         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 49] = "GreaterThanGreaterThanGreaterThanToken";
3763         SyntaxKind[SyntaxKind["AmpersandToken"] = 50] = "AmpersandToken";
3764         SyntaxKind[SyntaxKind["BarToken"] = 51] = "BarToken";
3765         SyntaxKind[SyntaxKind["CaretToken"] = 52] = "CaretToken";
3766         SyntaxKind[SyntaxKind["ExclamationToken"] = 53] = "ExclamationToken";
3767         SyntaxKind[SyntaxKind["TildeToken"] = 54] = "TildeToken";
3768         SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 55] = "AmpersandAmpersandToken";
3769         SyntaxKind[SyntaxKind["BarBarToken"] = 56] = "BarBarToken";
3770         SyntaxKind[SyntaxKind["QuestionToken"] = 57] = "QuestionToken";
3771         SyntaxKind[SyntaxKind["ColonToken"] = 58] = "ColonToken";
3772         SyntaxKind[SyntaxKind["AtToken"] = 59] = "AtToken";
3773         SyntaxKind[SyntaxKind["QuestionQuestionToken"] = 60] = "QuestionQuestionToken";
3774         /** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */
3775         SyntaxKind[SyntaxKind["BacktickToken"] = 61] = "BacktickToken";
3776         // Assignments
3777         SyntaxKind[SyntaxKind["EqualsToken"] = 62] = "EqualsToken";
3778         SyntaxKind[SyntaxKind["PlusEqualsToken"] = 63] = "PlusEqualsToken";
3779         SyntaxKind[SyntaxKind["MinusEqualsToken"] = 64] = "MinusEqualsToken";
3780         SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 65] = "AsteriskEqualsToken";
3781         SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 66] = "AsteriskAsteriskEqualsToken";
3782         SyntaxKind[SyntaxKind["SlashEqualsToken"] = 67] = "SlashEqualsToken";
3783         SyntaxKind[SyntaxKind["PercentEqualsToken"] = 68] = "PercentEqualsToken";
3784         SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 69] = "LessThanLessThanEqualsToken";
3785         SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 70] = "GreaterThanGreaterThanEqualsToken";
3786         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 71] = "GreaterThanGreaterThanGreaterThanEqualsToken";
3787         SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 72] = "AmpersandEqualsToken";
3788         SyntaxKind[SyntaxKind["BarEqualsToken"] = 73] = "BarEqualsToken";
3789         SyntaxKind[SyntaxKind["BarBarEqualsToken"] = 74] = "BarBarEqualsToken";
3790         SyntaxKind[SyntaxKind["AmpersandAmpersandEqualsToken"] = 75] = "AmpersandAmpersandEqualsToken";
3791         SyntaxKind[SyntaxKind["QuestionQuestionEqualsToken"] = 76] = "QuestionQuestionEqualsToken";
3792         SyntaxKind[SyntaxKind["CaretEqualsToken"] = 77] = "CaretEqualsToken";
3793         // Identifiers and PrivateIdentifiers
3794         SyntaxKind[SyntaxKind["Identifier"] = 78] = "Identifier";
3795         SyntaxKind[SyntaxKind["PrivateIdentifier"] = 79] = "PrivateIdentifier";
3796         // Reserved words
3797         SyntaxKind[SyntaxKind["BreakKeyword"] = 80] = "BreakKeyword";
3798         SyntaxKind[SyntaxKind["CaseKeyword"] = 81] = "CaseKeyword";
3799         SyntaxKind[SyntaxKind["CatchKeyword"] = 82] = "CatchKeyword";
3800         SyntaxKind[SyntaxKind["ClassKeyword"] = 83] = "ClassKeyword";
3801         SyntaxKind[SyntaxKind["ConstKeyword"] = 84] = "ConstKeyword";
3802         SyntaxKind[SyntaxKind["ContinueKeyword"] = 85] = "ContinueKeyword";
3803         SyntaxKind[SyntaxKind["DebuggerKeyword"] = 86] = "DebuggerKeyword";
3804         SyntaxKind[SyntaxKind["DefaultKeyword"] = 87] = "DefaultKeyword";
3805         SyntaxKind[SyntaxKind["DeleteKeyword"] = 88] = "DeleteKeyword";
3806         SyntaxKind[SyntaxKind["DoKeyword"] = 89] = "DoKeyword";
3807         SyntaxKind[SyntaxKind["ElseKeyword"] = 90] = "ElseKeyword";
3808         SyntaxKind[SyntaxKind["EnumKeyword"] = 91] = "EnumKeyword";
3809         SyntaxKind[SyntaxKind["ExportKeyword"] = 92] = "ExportKeyword";
3810         SyntaxKind[SyntaxKind["ExtendsKeyword"] = 93] = "ExtendsKeyword";
3811         SyntaxKind[SyntaxKind["FalseKeyword"] = 94] = "FalseKeyword";
3812         SyntaxKind[SyntaxKind["FinallyKeyword"] = 95] = "FinallyKeyword";
3813         SyntaxKind[SyntaxKind["ForKeyword"] = 96] = "ForKeyword";
3814         SyntaxKind[SyntaxKind["FunctionKeyword"] = 97] = "FunctionKeyword";
3815         SyntaxKind[SyntaxKind["IfKeyword"] = 98] = "IfKeyword";
3816         SyntaxKind[SyntaxKind["ImportKeyword"] = 99] = "ImportKeyword";
3817         SyntaxKind[SyntaxKind["InKeyword"] = 100] = "InKeyword";
3818         SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 101] = "InstanceOfKeyword";
3819         SyntaxKind[SyntaxKind["NewKeyword"] = 102] = "NewKeyword";
3820         SyntaxKind[SyntaxKind["NullKeyword"] = 103] = "NullKeyword";
3821         SyntaxKind[SyntaxKind["ReturnKeyword"] = 104] = "ReturnKeyword";
3822         SyntaxKind[SyntaxKind["SuperKeyword"] = 105] = "SuperKeyword";
3823         SyntaxKind[SyntaxKind["SwitchKeyword"] = 106] = "SwitchKeyword";
3824         SyntaxKind[SyntaxKind["ThisKeyword"] = 107] = "ThisKeyword";
3825         SyntaxKind[SyntaxKind["ThrowKeyword"] = 108] = "ThrowKeyword";
3826         SyntaxKind[SyntaxKind["TrueKeyword"] = 109] = "TrueKeyword";
3827         SyntaxKind[SyntaxKind["TryKeyword"] = 110] = "TryKeyword";
3828         SyntaxKind[SyntaxKind["TypeOfKeyword"] = 111] = "TypeOfKeyword";
3829         SyntaxKind[SyntaxKind["VarKeyword"] = 112] = "VarKeyword";
3830         SyntaxKind[SyntaxKind["VoidKeyword"] = 113] = "VoidKeyword";
3831         SyntaxKind[SyntaxKind["WhileKeyword"] = 114] = "WhileKeyword";
3832         SyntaxKind[SyntaxKind["WithKeyword"] = 115] = "WithKeyword";
3833         // Strict mode reserved words
3834         SyntaxKind[SyntaxKind["ImplementsKeyword"] = 116] = "ImplementsKeyword";
3835         SyntaxKind[SyntaxKind["InterfaceKeyword"] = 117] = "InterfaceKeyword";
3836         SyntaxKind[SyntaxKind["LetKeyword"] = 118] = "LetKeyword";
3837         SyntaxKind[SyntaxKind["PackageKeyword"] = 119] = "PackageKeyword";
3838         SyntaxKind[SyntaxKind["PrivateKeyword"] = 120] = "PrivateKeyword";
3839         SyntaxKind[SyntaxKind["ProtectedKeyword"] = 121] = "ProtectedKeyword";
3840         SyntaxKind[SyntaxKind["PublicKeyword"] = 122] = "PublicKeyword";
3841         SyntaxKind[SyntaxKind["StaticKeyword"] = 123] = "StaticKeyword";
3842         SyntaxKind[SyntaxKind["YieldKeyword"] = 124] = "YieldKeyword";
3843         // Contextual keywords
3844         SyntaxKind[SyntaxKind["AbstractKeyword"] = 125] = "AbstractKeyword";
3845         SyntaxKind[SyntaxKind["AsKeyword"] = 126] = "AsKeyword";
3846         SyntaxKind[SyntaxKind["AssertsKeyword"] = 127] = "AssertsKeyword";
3847         SyntaxKind[SyntaxKind["AnyKeyword"] = 128] = "AnyKeyword";
3848         SyntaxKind[SyntaxKind["AsyncKeyword"] = 129] = "AsyncKeyword";
3849         SyntaxKind[SyntaxKind["AwaitKeyword"] = 130] = "AwaitKeyword";
3850         SyntaxKind[SyntaxKind["BooleanKeyword"] = 131] = "BooleanKeyword";
3851         SyntaxKind[SyntaxKind["ConstructorKeyword"] = 132] = "ConstructorKeyword";
3852         SyntaxKind[SyntaxKind["DeclareKeyword"] = 133] = "DeclareKeyword";
3853         SyntaxKind[SyntaxKind["GetKeyword"] = 134] = "GetKeyword";
3854         SyntaxKind[SyntaxKind["InferKeyword"] = 135] = "InferKeyword";
3855         SyntaxKind[SyntaxKind["IntrinsicKeyword"] = 136] = "IntrinsicKeyword";
3856         SyntaxKind[SyntaxKind["IsKeyword"] = 137] = "IsKeyword";
3857         SyntaxKind[SyntaxKind["KeyOfKeyword"] = 138] = "KeyOfKeyword";
3858         SyntaxKind[SyntaxKind["ModuleKeyword"] = 139] = "ModuleKeyword";
3859         SyntaxKind[SyntaxKind["NamespaceKeyword"] = 140] = "NamespaceKeyword";
3860         SyntaxKind[SyntaxKind["NeverKeyword"] = 141] = "NeverKeyword";
3861         SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 142] = "ReadonlyKeyword";
3862         SyntaxKind[SyntaxKind["RequireKeyword"] = 143] = "RequireKeyword";
3863         SyntaxKind[SyntaxKind["NumberKeyword"] = 144] = "NumberKeyword";
3864         SyntaxKind[SyntaxKind["ObjectKeyword"] = 145] = "ObjectKeyword";
3865         SyntaxKind[SyntaxKind["SetKeyword"] = 146] = "SetKeyword";
3866         SyntaxKind[SyntaxKind["StringKeyword"] = 147] = "StringKeyword";
3867         SyntaxKind[SyntaxKind["SymbolKeyword"] = 148] = "SymbolKeyword";
3868         SyntaxKind[SyntaxKind["TypeKeyword"] = 149] = "TypeKeyword";
3869         SyntaxKind[SyntaxKind["UndefinedKeyword"] = 150] = "UndefinedKeyword";
3870         SyntaxKind[SyntaxKind["UniqueKeyword"] = 151] = "UniqueKeyword";
3871         SyntaxKind[SyntaxKind["UnknownKeyword"] = 152] = "UnknownKeyword";
3872         SyntaxKind[SyntaxKind["FromKeyword"] = 153] = "FromKeyword";
3873         SyntaxKind[SyntaxKind["GlobalKeyword"] = 154] = "GlobalKeyword";
3874         SyntaxKind[SyntaxKind["BigIntKeyword"] = 155] = "BigIntKeyword";
3875         SyntaxKind[SyntaxKind["OfKeyword"] = 156] = "OfKeyword";
3876         // Parse tree nodes
3877         // Names
3878         SyntaxKind[SyntaxKind["QualifiedName"] = 157] = "QualifiedName";
3879         SyntaxKind[SyntaxKind["ComputedPropertyName"] = 158] = "ComputedPropertyName";
3880         // Signature elements
3881         SyntaxKind[SyntaxKind["TypeParameter"] = 159] = "TypeParameter";
3882         SyntaxKind[SyntaxKind["Parameter"] = 160] = "Parameter";
3883         SyntaxKind[SyntaxKind["Decorator"] = 161] = "Decorator";
3884         // TypeMember
3885         SyntaxKind[SyntaxKind["PropertySignature"] = 162] = "PropertySignature";
3886         SyntaxKind[SyntaxKind["PropertyDeclaration"] = 163] = "PropertyDeclaration";
3887         SyntaxKind[SyntaxKind["MethodSignature"] = 164] = "MethodSignature";
3888         SyntaxKind[SyntaxKind["MethodDeclaration"] = 165] = "MethodDeclaration";
3889         SyntaxKind[SyntaxKind["Constructor"] = 166] = "Constructor";
3890         SyntaxKind[SyntaxKind["GetAccessor"] = 167] = "GetAccessor";
3891         SyntaxKind[SyntaxKind["SetAccessor"] = 168] = "SetAccessor";
3892         SyntaxKind[SyntaxKind["CallSignature"] = 169] = "CallSignature";
3893         SyntaxKind[SyntaxKind["ConstructSignature"] = 170] = "ConstructSignature";
3894         SyntaxKind[SyntaxKind["IndexSignature"] = 171] = "IndexSignature";
3895         // Type
3896         SyntaxKind[SyntaxKind["TypePredicate"] = 172] = "TypePredicate";
3897         SyntaxKind[SyntaxKind["TypeReference"] = 173] = "TypeReference";
3898         SyntaxKind[SyntaxKind["FunctionType"] = 174] = "FunctionType";
3899         SyntaxKind[SyntaxKind["ConstructorType"] = 175] = "ConstructorType";
3900         SyntaxKind[SyntaxKind["TypeQuery"] = 176] = "TypeQuery";
3901         SyntaxKind[SyntaxKind["TypeLiteral"] = 177] = "TypeLiteral";
3902         SyntaxKind[SyntaxKind["ArrayType"] = 178] = "ArrayType";
3903         SyntaxKind[SyntaxKind["TupleType"] = 179] = "TupleType";
3904         SyntaxKind[SyntaxKind["OptionalType"] = 180] = "OptionalType";
3905         SyntaxKind[SyntaxKind["RestType"] = 181] = "RestType";
3906         SyntaxKind[SyntaxKind["UnionType"] = 182] = "UnionType";
3907         SyntaxKind[SyntaxKind["IntersectionType"] = 183] = "IntersectionType";
3908         SyntaxKind[SyntaxKind["ConditionalType"] = 184] = "ConditionalType";
3909         SyntaxKind[SyntaxKind["InferType"] = 185] = "InferType";
3910         SyntaxKind[SyntaxKind["ParenthesizedType"] = 186] = "ParenthesizedType";
3911         SyntaxKind[SyntaxKind["ThisType"] = 187] = "ThisType";
3912         SyntaxKind[SyntaxKind["TypeOperator"] = 188] = "TypeOperator";
3913         SyntaxKind[SyntaxKind["IndexedAccessType"] = 189] = "IndexedAccessType";
3914         SyntaxKind[SyntaxKind["MappedType"] = 190] = "MappedType";
3915         SyntaxKind[SyntaxKind["LiteralType"] = 191] = "LiteralType";
3916         SyntaxKind[SyntaxKind["NamedTupleMember"] = 192] = "NamedTupleMember";
3917         SyntaxKind[SyntaxKind["TemplateLiteralType"] = 193] = "TemplateLiteralType";
3918         SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 194] = "TemplateLiteralTypeSpan";
3919         SyntaxKind[SyntaxKind["ImportType"] = 195] = "ImportType";
3920         // Binding patterns
3921         SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 196] = "ObjectBindingPattern";
3922         SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 197] = "ArrayBindingPattern";
3923         SyntaxKind[SyntaxKind["BindingElement"] = 198] = "BindingElement";
3924         // Expression
3925         SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 199] = "ArrayLiteralExpression";
3926         SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 200] = "ObjectLiteralExpression";
3927         SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 201] = "PropertyAccessExpression";
3928         SyntaxKind[SyntaxKind["ElementAccessExpression"] = 202] = "ElementAccessExpression";
3929         SyntaxKind[SyntaxKind["CallExpression"] = 203] = "CallExpression";
3930         SyntaxKind[SyntaxKind["NewExpression"] = 204] = "NewExpression";
3931         SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 205] = "TaggedTemplateExpression";
3932         SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 206] = "TypeAssertionExpression";
3933         SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 207] = "ParenthesizedExpression";
3934         SyntaxKind[SyntaxKind["FunctionExpression"] = 208] = "FunctionExpression";
3935         SyntaxKind[SyntaxKind["ArrowFunction"] = 209] = "ArrowFunction";
3936         SyntaxKind[SyntaxKind["DeleteExpression"] = 210] = "DeleteExpression";
3937         SyntaxKind[SyntaxKind["TypeOfExpression"] = 211] = "TypeOfExpression";
3938         SyntaxKind[SyntaxKind["VoidExpression"] = 212] = "VoidExpression";
3939         SyntaxKind[SyntaxKind["AwaitExpression"] = 213] = "AwaitExpression";
3940         SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 214] = "PrefixUnaryExpression";
3941         SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 215] = "PostfixUnaryExpression";
3942         SyntaxKind[SyntaxKind["BinaryExpression"] = 216] = "BinaryExpression";
3943         SyntaxKind[SyntaxKind["ConditionalExpression"] = 217] = "ConditionalExpression";
3944         SyntaxKind[SyntaxKind["TemplateExpression"] = 218] = "TemplateExpression";
3945         SyntaxKind[SyntaxKind["YieldExpression"] = 219] = "YieldExpression";
3946         SyntaxKind[SyntaxKind["SpreadElement"] = 220] = "SpreadElement";
3947         SyntaxKind[SyntaxKind["ClassExpression"] = 221] = "ClassExpression";
3948         SyntaxKind[SyntaxKind["OmittedExpression"] = 222] = "OmittedExpression";
3949         SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 223] = "ExpressionWithTypeArguments";
3950         SyntaxKind[SyntaxKind["AsExpression"] = 224] = "AsExpression";
3951         SyntaxKind[SyntaxKind["NonNullExpression"] = 225] = "NonNullExpression";
3952         SyntaxKind[SyntaxKind["MetaProperty"] = 226] = "MetaProperty";
3953         SyntaxKind[SyntaxKind["SyntheticExpression"] = 227] = "SyntheticExpression";
3954         // Misc
3955         SyntaxKind[SyntaxKind["TemplateSpan"] = 228] = "TemplateSpan";
3956         SyntaxKind[SyntaxKind["SemicolonClassElement"] = 229] = "SemicolonClassElement";
3957         // Element
3958         SyntaxKind[SyntaxKind["Block"] = 230] = "Block";
3959         SyntaxKind[SyntaxKind["EmptyStatement"] = 231] = "EmptyStatement";
3960         SyntaxKind[SyntaxKind["VariableStatement"] = 232] = "VariableStatement";
3961         SyntaxKind[SyntaxKind["ExpressionStatement"] = 233] = "ExpressionStatement";
3962         SyntaxKind[SyntaxKind["IfStatement"] = 234] = "IfStatement";
3963         SyntaxKind[SyntaxKind["DoStatement"] = 235] = "DoStatement";
3964         SyntaxKind[SyntaxKind["WhileStatement"] = 236] = "WhileStatement";
3965         SyntaxKind[SyntaxKind["ForStatement"] = 237] = "ForStatement";
3966         SyntaxKind[SyntaxKind["ForInStatement"] = 238] = "ForInStatement";
3967         SyntaxKind[SyntaxKind["ForOfStatement"] = 239] = "ForOfStatement";
3968         SyntaxKind[SyntaxKind["ContinueStatement"] = 240] = "ContinueStatement";
3969         SyntaxKind[SyntaxKind["BreakStatement"] = 241] = "BreakStatement";
3970         SyntaxKind[SyntaxKind["ReturnStatement"] = 242] = "ReturnStatement";
3971         SyntaxKind[SyntaxKind["WithStatement"] = 243] = "WithStatement";
3972         SyntaxKind[SyntaxKind["SwitchStatement"] = 244] = "SwitchStatement";
3973         SyntaxKind[SyntaxKind["LabeledStatement"] = 245] = "LabeledStatement";
3974         SyntaxKind[SyntaxKind["ThrowStatement"] = 246] = "ThrowStatement";
3975         SyntaxKind[SyntaxKind["TryStatement"] = 247] = "TryStatement";
3976         SyntaxKind[SyntaxKind["DebuggerStatement"] = 248] = "DebuggerStatement";
3977         SyntaxKind[SyntaxKind["VariableDeclaration"] = 249] = "VariableDeclaration";
3978         SyntaxKind[SyntaxKind["VariableDeclarationList"] = 250] = "VariableDeclarationList";
3979         SyntaxKind[SyntaxKind["FunctionDeclaration"] = 251] = "FunctionDeclaration";
3980         SyntaxKind[SyntaxKind["ClassDeclaration"] = 252] = "ClassDeclaration";
3981         SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 253] = "InterfaceDeclaration";
3982         SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 254] = "TypeAliasDeclaration";
3983         SyntaxKind[SyntaxKind["EnumDeclaration"] = 255] = "EnumDeclaration";
3984         SyntaxKind[SyntaxKind["ModuleDeclaration"] = 256] = "ModuleDeclaration";
3985         SyntaxKind[SyntaxKind["ModuleBlock"] = 257] = "ModuleBlock";
3986         SyntaxKind[SyntaxKind["CaseBlock"] = 258] = "CaseBlock";
3987         SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 259] = "NamespaceExportDeclaration";
3988         SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 260] = "ImportEqualsDeclaration";
3989         SyntaxKind[SyntaxKind["ImportDeclaration"] = 261] = "ImportDeclaration";
3990         SyntaxKind[SyntaxKind["ImportClause"] = 262] = "ImportClause";
3991         SyntaxKind[SyntaxKind["NamespaceImport"] = 263] = "NamespaceImport";
3992         SyntaxKind[SyntaxKind["NamedImports"] = 264] = "NamedImports";
3993         SyntaxKind[SyntaxKind["ImportSpecifier"] = 265] = "ImportSpecifier";
3994         SyntaxKind[SyntaxKind["ExportAssignment"] = 266] = "ExportAssignment";
3995         SyntaxKind[SyntaxKind["ExportDeclaration"] = 267] = "ExportDeclaration";
3996         SyntaxKind[SyntaxKind["NamedExports"] = 268] = "NamedExports";
3997         SyntaxKind[SyntaxKind["NamespaceExport"] = 269] = "NamespaceExport";
3998         SyntaxKind[SyntaxKind["ExportSpecifier"] = 270] = "ExportSpecifier";
3999         SyntaxKind[SyntaxKind["MissingDeclaration"] = 271] = "MissingDeclaration";
4000         // Module references
4001         SyntaxKind[SyntaxKind["ExternalModuleReference"] = 272] = "ExternalModuleReference";
4002         // JSX
4003         SyntaxKind[SyntaxKind["JsxElement"] = 273] = "JsxElement";
4004         SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 274] = "JsxSelfClosingElement";
4005         SyntaxKind[SyntaxKind["JsxOpeningElement"] = 275] = "JsxOpeningElement";
4006         SyntaxKind[SyntaxKind["JsxClosingElement"] = 276] = "JsxClosingElement";
4007         SyntaxKind[SyntaxKind["JsxFragment"] = 277] = "JsxFragment";
4008         SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 278] = "JsxOpeningFragment";
4009         SyntaxKind[SyntaxKind["JsxClosingFragment"] = 279] = "JsxClosingFragment";
4010         SyntaxKind[SyntaxKind["JsxAttribute"] = 280] = "JsxAttribute";
4011         SyntaxKind[SyntaxKind["JsxAttributes"] = 281] = "JsxAttributes";
4012         SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 282] = "JsxSpreadAttribute";
4013         SyntaxKind[SyntaxKind["JsxExpression"] = 283] = "JsxExpression";
4014         // Clauses
4015         SyntaxKind[SyntaxKind["CaseClause"] = 284] = "CaseClause";
4016         SyntaxKind[SyntaxKind["DefaultClause"] = 285] = "DefaultClause";
4017         SyntaxKind[SyntaxKind["HeritageClause"] = 286] = "HeritageClause";
4018         SyntaxKind[SyntaxKind["CatchClause"] = 287] = "CatchClause";
4019         // Property assignments
4020         SyntaxKind[SyntaxKind["PropertyAssignment"] = 288] = "PropertyAssignment";
4021         SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 289] = "ShorthandPropertyAssignment";
4022         SyntaxKind[SyntaxKind["SpreadAssignment"] = 290] = "SpreadAssignment";
4023         // Enum
4024         SyntaxKind[SyntaxKind["EnumMember"] = 291] = "EnumMember";
4025         // Unparsed
4026         SyntaxKind[SyntaxKind["UnparsedPrologue"] = 292] = "UnparsedPrologue";
4027         SyntaxKind[SyntaxKind["UnparsedPrepend"] = 293] = "UnparsedPrepend";
4028         SyntaxKind[SyntaxKind["UnparsedText"] = 294] = "UnparsedText";
4029         SyntaxKind[SyntaxKind["UnparsedInternalText"] = 295] = "UnparsedInternalText";
4030         SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 296] = "UnparsedSyntheticReference";
4031         // Top-level nodes
4032         SyntaxKind[SyntaxKind["SourceFile"] = 297] = "SourceFile";
4033         SyntaxKind[SyntaxKind["Bundle"] = 298] = "Bundle";
4034         SyntaxKind[SyntaxKind["UnparsedSource"] = 299] = "UnparsedSource";
4035         SyntaxKind[SyntaxKind["InputFiles"] = 300] = "InputFiles";
4036         // JSDoc nodes
4037         SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 301] = "JSDocTypeExpression";
4038         SyntaxKind[SyntaxKind["JSDocNameReference"] = 302] = "JSDocNameReference";
4039         // The * type
4040         SyntaxKind[SyntaxKind["JSDocAllType"] = 303] = "JSDocAllType";
4041         // The ? type
4042         SyntaxKind[SyntaxKind["JSDocUnknownType"] = 304] = "JSDocUnknownType";
4043         SyntaxKind[SyntaxKind["JSDocNullableType"] = 305] = "JSDocNullableType";
4044         SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 306] = "JSDocNonNullableType";
4045         SyntaxKind[SyntaxKind["JSDocOptionalType"] = 307] = "JSDocOptionalType";
4046         SyntaxKind[SyntaxKind["JSDocFunctionType"] = 308] = "JSDocFunctionType";
4047         SyntaxKind[SyntaxKind["JSDocVariadicType"] = 309] = "JSDocVariadicType";
4048         // https://jsdoc.app/about-namepaths.html
4049         SyntaxKind[SyntaxKind["JSDocNamepathType"] = 310] = "JSDocNamepathType";
4050         SyntaxKind[SyntaxKind["JSDocComment"] = 311] = "JSDocComment";
4051         SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 312] = "JSDocTypeLiteral";
4052         SyntaxKind[SyntaxKind["JSDocSignature"] = 313] = "JSDocSignature";
4053         SyntaxKind[SyntaxKind["JSDocTag"] = 314] = "JSDocTag";
4054         SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 315] = "JSDocAugmentsTag";
4055         SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 316] = "JSDocImplementsTag";
4056         SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 317] = "JSDocAuthorTag";
4057         SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 318] = "JSDocDeprecatedTag";
4058         SyntaxKind[SyntaxKind["JSDocClassTag"] = 319] = "JSDocClassTag";
4059         SyntaxKind[SyntaxKind["JSDocPublicTag"] = 320] = "JSDocPublicTag";
4060         SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 321] = "JSDocPrivateTag";
4061         SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 322] = "JSDocProtectedTag";
4062         SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 323] = "JSDocReadonlyTag";
4063         SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 324] = "JSDocCallbackTag";
4064         SyntaxKind[SyntaxKind["JSDocEnumTag"] = 325] = "JSDocEnumTag";
4065         SyntaxKind[SyntaxKind["JSDocParameterTag"] = 326] = "JSDocParameterTag";
4066         SyntaxKind[SyntaxKind["JSDocReturnTag"] = 327] = "JSDocReturnTag";
4067         SyntaxKind[SyntaxKind["JSDocThisTag"] = 328] = "JSDocThisTag";
4068         SyntaxKind[SyntaxKind["JSDocTypeTag"] = 329] = "JSDocTypeTag";
4069         SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 330] = "JSDocTemplateTag";
4070         SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 331] = "JSDocTypedefTag";
4071         SyntaxKind[SyntaxKind["JSDocSeeTag"] = 332] = "JSDocSeeTag";
4072         SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 333] = "JSDocPropertyTag";
4073         // Synthesized list
4074         SyntaxKind[SyntaxKind["SyntaxList"] = 334] = "SyntaxList";
4075         // Transformation nodes
4076         SyntaxKind[SyntaxKind["NotEmittedStatement"] = 335] = "NotEmittedStatement";
4077         SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 336] = "PartiallyEmittedExpression";
4078         SyntaxKind[SyntaxKind["CommaListExpression"] = 337] = "CommaListExpression";
4079         SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 338] = "MergeDeclarationMarker";
4080         SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 339] = "EndOfDeclarationMarker";
4081         SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 340] = "SyntheticReferenceExpression";
4082         // Enum value count
4083         SyntaxKind[SyntaxKind["Count"] = 341] = "Count";
4084         // Markers
4085         SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment";
4086         SyntaxKind[SyntaxKind["LastAssignment"] = 77] = "LastAssignment";
4087         SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 63] = "FirstCompoundAssignment";
4088         SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 77] = "LastCompoundAssignment";
4089         SyntaxKind[SyntaxKind["FirstReservedWord"] = 80] = "FirstReservedWord";
4090         SyntaxKind[SyntaxKind["LastReservedWord"] = 115] = "LastReservedWord";
4091         SyntaxKind[SyntaxKind["FirstKeyword"] = 80] = "FirstKeyword";
4092         SyntaxKind[SyntaxKind["LastKeyword"] = 156] = "LastKeyword";
4093         SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 116] = "FirstFutureReservedWord";
4094         SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 124] = "LastFutureReservedWord";
4095         SyntaxKind[SyntaxKind["FirstTypeNode"] = 172] = "FirstTypeNode";
4096         SyntaxKind[SyntaxKind["LastTypeNode"] = 195] = "LastTypeNode";
4097         SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation";
4098         SyntaxKind[SyntaxKind["LastPunctuation"] = 77] = "LastPunctuation";
4099         SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
4100         SyntaxKind[SyntaxKind["LastToken"] = 156] = "LastToken";
4101         SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
4102         SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
4103         SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
4104         SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken";
4105         SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken";
4106         SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken";
4107         SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator";
4108         SyntaxKind[SyntaxKind["LastBinaryOperator"] = 77] = "LastBinaryOperator";
4109         SyntaxKind[SyntaxKind["FirstStatement"] = 232] = "FirstStatement";
4110         SyntaxKind[SyntaxKind["LastStatement"] = 248] = "LastStatement";
4111         SyntaxKind[SyntaxKind["FirstNode"] = 157] = "FirstNode";
4112         SyntaxKind[SyntaxKind["FirstJSDocNode"] = 301] = "FirstJSDocNode";
4113         SyntaxKind[SyntaxKind["LastJSDocNode"] = 333] = "LastJSDocNode";
4114         SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 314] = "FirstJSDocTagNode";
4115         SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 333] = "LastJSDocTagNode";
4116         /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 125] = "FirstContextualKeyword";
4117         /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 156] = "LastContextualKeyword";
4118     })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
4119     var NodeFlags;
4120     (function (NodeFlags) {
4121         NodeFlags[NodeFlags["None"] = 0] = "None";
4122         NodeFlags[NodeFlags["Let"] = 1] = "Let";
4123         NodeFlags[NodeFlags["Const"] = 2] = "Const";
4124         NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace";
4125         NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized";
4126         NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace";
4127         NodeFlags[NodeFlags["OptionalChain"] = 32] = "OptionalChain";
4128         NodeFlags[NodeFlags["ExportContext"] = 64] = "ExportContext";
4129         NodeFlags[NodeFlags["ContainsThis"] = 128] = "ContainsThis";
4130         NodeFlags[NodeFlags["HasImplicitReturn"] = 256] = "HasImplicitReturn";
4131         NodeFlags[NodeFlags["HasExplicitReturn"] = 512] = "HasExplicitReturn";
4132         NodeFlags[NodeFlags["GlobalAugmentation"] = 1024] = "GlobalAugmentation";
4133         NodeFlags[NodeFlags["HasAsyncFunctions"] = 2048] = "HasAsyncFunctions";
4134         NodeFlags[NodeFlags["DisallowInContext"] = 4096] = "DisallowInContext";
4135         NodeFlags[NodeFlags["YieldContext"] = 8192] = "YieldContext";
4136         NodeFlags[NodeFlags["DecoratorContext"] = 16384] = "DecoratorContext";
4137         NodeFlags[NodeFlags["AwaitContext"] = 32768] = "AwaitContext";
4138         NodeFlags[NodeFlags["ThisNodeHasError"] = 65536] = "ThisNodeHasError";
4139         NodeFlags[NodeFlags["JavaScriptFile"] = 131072] = "JavaScriptFile";
4140         NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 262144] = "ThisNodeOrAnySubNodesHasError";
4141         NodeFlags[NodeFlags["HasAggregatedChildData"] = 524288] = "HasAggregatedChildData";
4142         // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid
4143         // walking the tree if the flags are not set. However, these flags are just a approximation
4144         // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared.
4145         // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag.
4146         // This means that the tree will always be traversed during module resolution, or when looking for external module indicators.
4147         // However, the removal operation should not occur often and in the case of the
4148         // removal, it is likely that users will add the import anyway.
4149         // The advantage of this approach is its simplicity. For the case of batch compilation,
4150         // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used.
4151         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 1048576] = "PossiblyContainsDynamicImport";
4152         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 2097152] = "PossiblyContainsImportMeta";
4153         NodeFlags[NodeFlags["JSDoc"] = 4194304] = "JSDoc";
4154         /* @internal */ NodeFlags[NodeFlags["Ambient"] = 8388608] = "Ambient";
4155         /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 16777216] = "InWithStatement";
4156         NodeFlags[NodeFlags["JsonFile"] = 33554432] = "JsonFile";
4157         /* @internal */ NodeFlags[NodeFlags["TypeCached"] = 67108864] = "TypeCached";
4158         /* @internal */ NodeFlags[NodeFlags["Deprecated"] = 134217728] = "Deprecated";
4159         NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
4160         NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 768] = "ReachabilityCheckFlags";
4161         NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 2816] = "ReachabilityAndEmitFlags";
4162         // Parsing context flags
4163         NodeFlags[NodeFlags["ContextFlags"] = 25358336] = "ContextFlags";
4164         // Exclude these flags when parsing a Type
4165         NodeFlags[NodeFlags["TypeExcludesFlags"] = 40960] = "TypeExcludesFlags";
4166         // Represents all flags that are potentially set once and
4167         // never cleared on SourceFiles which get re-used in between incremental parses.
4168         // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`.
4169         /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 3145728] = "PermanentlySetIncrementalFlags";
4170     })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
4171     var ModifierFlags;
4172     (function (ModifierFlags) {
4173         ModifierFlags[ModifierFlags["None"] = 0] = "None";
4174         ModifierFlags[ModifierFlags["Export"] = 1] = "Export";
4175         ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient";
4176         ModifierFlags[ModifierFlags["Public"] = 4] = "Public";
4177         ModifierFlags[ModifierFlags["Private"] = 8] = "Private";
4178         ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected";
4179         ModifierFlags[ModifierFlags["Static"] = 32] = "Static";
4180         ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly";
4181         ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract";
4182         ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
4183         ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
4184         ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
4185         ModifierFlags[ModifierFlags["HasComputedJSDocModifiers"] = 4096] = "HasComputedJSDocModifiers";
4186         ModifierFlags[ModifierFlags["Deprecated"] = 8192] = "Deprecated";
4187         ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
4188         ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
4189         // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
4190         ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier";
4191         ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
4192         ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
4193         ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
4194         ModifierFlags[ModifierFlags["All"] = 11263] = "All";
4195     })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
4196     var JsxFlags;
4197     (function (JsxFlags) {
4198         JsxFlags[JsxFlags["None"] = 0] = "None";
4199         /** An element from a named property of the JSX.IntrinsicElements interface */
4200         JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
4201         /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
4202         JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
4203         JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
4204     })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
4205     /* @internal */
4206     var RelationComparisonResult;
4207     (function (RelationComparisonResult) {
4208         RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
4209         RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
4210         RelationComparisonResult[RelationComparisonResult["Reported"] = 4] = "Reported";
4211         RelationComparisonResult[RelationComparisonResult["ReportsUnmeasurable"] = 8] = "ReportsUnmeasurable";
4212         RelationComparisonResult[RelationComparisonResult["ReportsUnreliable"] = 16] = "ReportsUnreliable";
4213         RelationComparisonResult[RelationComparisonResult["ReportsMask"] = 24] = "ReportsMask";
4214     })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
4215     var GeneratedIdentifierFlags;
4216     (function (GeneratedIdentifierFlags) {
4217         // Kinds
4218         GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
4219         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
4220         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
4221         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
4222         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
4223         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
4224         // Flags
4225         GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
4226         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
4227         GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
4228         GeneratedIdentifierFlags[GeneratedIdentifierFlags["AllowNameSubstitution"] = 64] = "AllowNameSubstitution";
4229     })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
4230     var TokenFlags;
4231     (function (TokenFlags) {
4232         TokenFlags[TokenFlags["None"] = 0] = "None";
4233         /* @internal */
4234         TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
4235         /* @internal */
4236         TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
4237         /* @internal */
4238         TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
4239         /* @internal */
4240         TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
4241         TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
4242         TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
4243         TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
4244         TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
4245         TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
4246         /* @internal */
4247         TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
4248         /* @internal */
4249         TokenFlags[TokenFlags["UnicodeEscape"] = 1024] = "UnicodeEscape";
4250         /* @internal */
4251         TokenFlags[TokenFlags["ContainsInvalidEscape"] = 2048] = "ContainsInvalidEscape";
4252         /* @internal */
4253         TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
4254         /* @internal */
4255         TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
4256         /* @internal */
4257         TokenFlags[TokenFlags["TemplateLiteralLikeFlags"] = 2048] = "TemplateLiteralLikeFlags";
4258     })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
4259     // NOTE: Ensure this is up-to-date with src/debug/debug.ts
4260     var FlowFlags;
4261     (function (FlowFlags) {
4262         FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
4263         FlowFlags[FlowFlags["Start"] = 2] = "Start";
4264         FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
4265         FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
4266         FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
4267         FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition";
4268         FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition";
4269         FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause";
4270         FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
4271         FlowFlags[FlowFlags["Call"] = 512] = "Call";
4272         FlowFlags[FlowFlags["ReduceLabel"] = 1024] = "ReduceLabel";
4273         FlowFlags[FlowFlags["Referenced"] = 2048] = "Referenced";
4274         FlowFlags[FlowFlags["Shared"] = 4096] = "Shared";
4275         FlowFlags[FlowFlags["Label"] = 12] = "Label";
4276         FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
4277     })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
4278     /* @internal */
4279     var CommentDirectiveType;
4280     (function (CommentDirectiveType) {
4281         CommentDirectiveType[CommentDirectiveType["ExpectError"] = 0] = "ExpectError";
4282         CommentDirectiveType[CommentDirectiveType["Ignore"] = 1] = "Ignore";
4283     })(CommentDirectiveType = ts.CommentDirectiveType || (ts.CommentDirectiveType = {}));
4284     var OperationCanceledException = /** @class */ (function () {
4285         function OperationCanceledException() {
4286         }
4287         return OperationCanceledException;
4288     }());
4289     ts.OperationCanceledException = OperationCanceledException;
4290     /*@internal*/
4291     var FileIncludeKind;
4292     (function (FileIncludeKind) {
4293         FileIncludeKind[FileIncludeKind["RootFile"] = 0] = "RootFile";
4294         FileIncludeKind[FileIncludeKind["SourceFromProjectReference"] = 1] = "SourceFromProjectReference";
4295         FileIncludeKind[FileIncludeKind["OutputFromProjectReference"] = 2] = "OutputFromProjectReference";
4296         FileIncludeKind[FileIncludeKind["Import"] = 3] = "Import";
4297         FileIncludeKind[FileIncludeKind["ReferenceFile"] = 4] = "ReferenceFile";
4298         FileIncludeKind[FileIncludeKind["TypeReferenceDirective"] = 5] = "TypeReferenceDirective";
4299         FileIncludeKind[FileIncludeKind["LibFile"] = 6] = "LibFile";
4300         FileIncludeKind[FileIncludeKind["LibReferenceDirective"] = 7] = "LibReferenceDirective";
4301         FileIncludeKind[FileIncludeKind["AutomaticTypeDirectiveFile"] = 8] = "AutomaticTypeDirectiveFile";
4302     })(FileIncludeKind = ts.FileIncludeKind || (ts.FileIncludeKind = {}));
4303     /*@internal*/
4304     var FilePreprocessingDiagnosticsKind;
4305     (function (FilePreprocessingDiagnosticsKind) {
4306         FilePreprocessingDiagnosticsKind[FilePreprocessingDiagnosticsKind["FilePreprocessingReferencedDiagnostic"] = 0] = "FilePreprocessingReferencedDiagnostic";
4307         FilePreprocessingDiagnosticsKind[FilePreprocessingDiagnosticsKind["FilePreprocessingFileExplainingDiagnostic"] = 1] = "FilePreprocessingFileExplainingDiagnostic";
4308     })(FilePreprocessingDiagnosticsKind = ts.FilePreprocessingDiagnosticsKind || (ts.FilePreprocessingDiagnosticsKind = {}));
4309     /* @internal */
4310     var StructureIsReused;
4311     (function (StructureIsReused) {
4312         StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
4313         StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
4314         StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
4315     })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
4316     /** Return code used by getEmitOutput function to indicate status of the function */
4317     var ExitStatus;
4318     (function (ExitStatus) {
4319         // Compiler ran successfully.  Either this was a simple do-nothing compilation (for example,
4320         // when -version or -help was provided, or this was a normal compilation, no diagnostics
4321         // were produced, and all outputs were generated successfully.
4322         ExitStatus[ExitStatus["Success"] = 0] = "Success";
4323         // Diagnostics were produced and because of them no code was generated.
4324         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
4325         // Diagnostics were produced and outputs were generated in spite of them.
4326         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
4327         // When build skipped because passed in project is invalid
4328         ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped";
4329         // When build is skipped because project references form cycle
4330         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped";
4331         /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
4332         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped";
4333     })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
4334     /* @internal */
4335     var UnionReduction;
4336     (function (UnionReduction) {
4337         UnionReduction[UnionReduction["None"] = 0] = "None";
4338         UnionReduction[UnionReduction["Literal"] = 1] = "Literal";
4339         UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype";
4340     })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {}));
4341     /* @internal */
4342     var ContextFlags;
4343     (function (ContextFlags) {
4344         ContextFlags[ContextFlags["None"] = 0] = "None";
4345         ContextFlags[ContextFlags["Signature"] = 1] = "Signature";
4346         ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints";
4347         ContextFlags[ContextFlags["Completions"] = 4] = "Completions";
4348         ContextFlags[ContextFlags["SkipBindingPatterns"] = 8] = "SkipBindingPatterns";
4349     })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {}));
4350     // NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
4351     var NodeBuilderFlags;
4352     (function (NodeBuilderFlags) {
4353         NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
4354         // Options
4355         NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
4356         NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
4357         NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
4358         NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
4359         NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences";
4360         NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
4361         NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
4362         NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
4363         NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
4364         NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName";
4365         NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
4366         NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
4367         NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
4368         NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
4369         NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
4370         NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
4371         NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
4372         NodeBuilderFlags[NodeBuilderFlags["NoUndefinedOptionalParameterType"] = 1073741824] = "NoUndefinedOptionalParameterType";
4373         // Error handling
4374         NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
4375         NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
4376         NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
4377         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
4378         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
4379         NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
4380         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
4381         // Errors (cont.)
4382         NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
4383         /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
4384         NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
4385         // State
4386         NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
4387         NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
4388         NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
4389         NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
4390     })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
4391     // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
4392     var TypeFormatFlags;
4393     (function (TypeFormatFlags) {
4394         TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
4395         TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
4396         TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
4397         // hole because there's a hole in node builder flags
4398         TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
4399         // hole because there's a hole in node builder flags
4400         TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
4401         TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
4402         // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead
4403         TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
4404         // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead
4405         TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
4406         TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
4407         TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
4408         TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
4409         TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
4410         TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
4411         TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
4412         // Error Handling
4413         TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
4414         // TypeFormatFlags exclusive
4415         TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
4416         TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
4417         // State
4418         TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
4419         TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
4420         TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
4421         TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
4422         /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
4423         TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask";
4424     })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
4425     var SymbolFormatFlags;
4426     (function (SymbolFormatFlags) {
4427         SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
4428         // Write symbols's type argument if it is instantiated symbol
4429         // eg. class C<T> { p: T }   <-- Show p as C<T>.p here
4430         //     var a: C<number>;
4431         //     var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
4432         SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
4433         // Use only external alias information to get the symbol name in the given context
4434         // eg.  module m { export class c { } } import x = m.c;
4435         // When this flag is specified m.c will be used to refer to the class instead of alias symbol x
4436         SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
4437         // Build symbol name using any nodes needed, instead of just components of an entity name
4438         SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
4439         // Prefer aliases which are not directly visible
4440         SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
4441         // Skip building an accessible symbol chain
4442         /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain";
4443     })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
4444     /* @internal */
4445     var SymbolAccessibility;
4446     (function (SymbolAccessibility) {
4447         SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
4448         SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
4449         SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
4450     })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
4451     /* @internal */
4452     var SyntheticSymbolKind;
4453     (function (SyntheticSymbolKind) {
4454         SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
4455         SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread";
4456     })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {}));
4457     var TypePredicateKind;
4458     (function (TypePredicateKind) {
4459         TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
4460         TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
4461         TypePredicateKind[TypePredicateKind["AssertsThis"] = 2] = "AssertsThis";
4462         TypePredicateKind[TypePredicateKind["AssertsIdentifier"] = 3] = "AssertsIdentifier";
4463     })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
4464     /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
4465     /* @internal */
4466     var TypeReferenceSerializationKind;
4467     (function (TypeReferenceSerializationKind) {
4468         // The TypeReferenceNode could not be resolved.
4469         // The type name should be emitted using a safe fallback.
4470         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
4471         // The TypeReferenceNode resolves to a type with a constructor
4472         // function that can be reached at runtime (e.g. a `class`
4473         // declaration or a `var` declaration for the static side
4474         // of a type, such as the global `Promise` type in lib.d.ts).
4475         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue";
4476         // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type.
4477         TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType";
4478         // The TypeReferenceNode resolves to a Number-like type.
4479         TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType";
4480         // The TypeReferenceNode resolves to a BigInt-like type.
4481         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType";
4482         // The TypeReferenceNode resolves to a String-like type.
4483         TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType";
4484         // The TypeReferenceNode resolves to a Boolean-like type.
4485         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType";
4486         // The TypeReferenceNode resolves to an Array-like type.
4487         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType";
4488         // The TypeReferenceNode resolves to the ESSymbol type.
4489         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType";
4490         // The TypeReferenceNode resolved to the global Promise constructor symbol.
4491         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise";
4492         // The TypeReferenceNode resolves to a Function type or a type with call signatures.
4493         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature";
4494         // The TypeReferenceNode resolves to any other type.
4495         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType";
4496     })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
4497     var SymbolFlags;
4498     (function (SymbolFlags) {
4499         SymbolFlags[SymbolFlags["None"] = 0] = "None";
4500         SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable";
4501         SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable";
4502         SymbolFlags[SymbolFlags["Property"] = 4] = "Property";
4503         SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember";
4504         SymbolFlags[SymbolFlags["Function"] = 16] = "Function";
4505         SymbolFlags[SymbolFlags["Class"] = 32] = "Class";
4506         SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface";
4507         SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum";
4508         SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum";
4509         SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule";
4510         SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule";
4511         SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral";
4512         SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral";
4513         SymbolFlags[SymbolFlags["Method"] = 8192] = "Method";
4514         SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor";
4515         SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor";
4516         SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor";
4517         SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature";
4518         SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter";
4519         SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias";
4520         SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue";
4521         SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias";
4522         SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype";
4523         SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar";
4524         SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
4525         SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
4526         SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment";
4527         SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports";
4528         /* @internal */
4529         SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
4530         SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
4531         SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
4532         SymbolFlags[SymbolFlags["Value"] = 111551] = "Value";
4533         SymbolFlags[SymbolFlags["Type"] = 788968] = "Type";
4534         SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
4535         SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
4536         SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
4537         // Variables can be redeclared, but can not redeclare a block-scoped declaration with the
4538         // same name, or any other value that is not a variable, e.g. ValueModule or Class
4539         SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 111550] = "FunctionScopedVariableExcludes";
4540         // Block-scoped declarations are not allowed to be re-declared
4541         // they can not merge with anything in the value space
4542         SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 111551] = "BlockScopedVariableExcludes";
4543         SymbolFlags[SymbolFlags["ParameterExcludes"] = 111551] = "ParameterExcludes";
4544         SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
4545         SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes";
4546         SymbolFlags[SymbolFlags["FunctionExcludes"] = 110991] = "FunctionExcludes";
4547         SymbolFlags[SymbolFlags["ClassExcludes"] = 899503] = "ClassExcludes";
4548         SymbolFlags[SymbolFlags["InterfaceExcludes"] = 788872] = "InterfaceExcludes";
4549         SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes";
4550         SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes";
4551         SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes";
4552         SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
4553         SymbolFlags[SymbolFlags["MethodExcludes"] = 103359] = "MethodExcludes";
4554         SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 46015] = "GetAccessorExcludes";
4555         SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 78783] = "SetAccessorExcludes";
4556         SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 526824] = "TypeParameterExcludes";
4557         SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 788968] = "TypeAliasExcludes";
4558         SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
4559         SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
4560         SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
4561         SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
4562         SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
4563         SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
4564         /* @internal */
4565         SymbolFlags[SymbolFlags["ExportSupportsDefaultModifier"] = 112] = "ExportSupportsDefaultModifier";
4566         /* @internal */
4567         SymbolFlags[SymbolFlags["ExportDoesNotSupportDefaultModifier"] = -113] = "ExportDoesNotSupportDefaultModifier";
4568         /* @internal */
4569         // The set of things we consider semantically classifiable.  Used to speed up the LS during
4570         // classification.
4571         SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
4572         /* @internal */
4573         SymbolFlags[SymbolFlags["LateBindingContainer"] = 6256] = "LateBindingContainer";
4574     })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
4575     /* @internal */
4576     var EnumKind;
4577     (function (EnumKind) {
4578         EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
4579         EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type)
4580     })(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
4581     /* @internal */
4582     var CheckFlags;
4583     (function (CheckFlags) {
4584         CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
4585         CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
4586         CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
4587         CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
4588         CheckFlags[CheckFlags["ReadPartial"] = 16] = "ReadPartial";
4589         CheckFlags[CheckFlags["WritePartial"] = 32] = "WritePartial";
4590         CheckFlags[CheckFlags["HasNonUniformType"] = 64] = "HasNonUniformType";
4591         CheckFlags[CheckFlags["HasLiteralType"] = 128] = "HasLiteralType";
4592         CheckFlags[CheckFlags["ContainsPublic"] = 256] = "ContainsPublic";
4593         CheckFlags[CheckFlags["ContainsProtected"] = 512] = "ContainsProtected";
4594         CheckFlags[CheckFlags["ContainsPrivate"] = 1024] = "ContainsPrivate";
4595         CheckFlags[CheckFlags["ContainsStatic"] = 2048] = "ContainsStatic";
4596         CheckFlags[CheckFlags["Late"] = 4096] = "Late";
4597         CheckFlags[CheckFlags["ReverseMapped"] = 8192] = "ReverseMapped";
4598         CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter";
4599         CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter";
4600         CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType";
4601         CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType";
4602         CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped";
4603         CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional";
4604         CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
4605         CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant";
4606         CheckFlags[CheckFlags["Partial"] = 48] = "Partial";
4607     })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
4608     var InternalSymbolName;
4609     (function (InternalSymbolName) {
4610         InternalSymbolName["Call"] = "__call";
4611         InternalSymbolName["Constructor"] = "__constructor";
4612         InternalSymbolName["New"] = "__new";
4613         InternalSymbolName["Index"] = "__index";
4614         InternalSymbolName["ExportStar"] = "__export";
4615         InternalSymbolName["Global"] = "__global";
4616         InternalSymbolName["Missing"] = "__missing";
4617         InternalSymbolName["Type"] = "__type";
4618         InternalSymbolName["Object"] = "__object";
4619         InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
4620         InternalSymbolName["Class"] = "__class";
4621         InternalSymbolName["Function"] = "__function";
4622         InternalSymbolName["Computed"] = "__computed";
4623         InternalSymbolName["Resolving"] = "__resolving__";
4624         InternalSymbolName["ExportEquals"] = "export=";
4625         InternalSymbolName["Default"] = "default";
4626         InternalSymbolName["This"] = "this";
4627     })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
4628     /* @internal */
4629     var NodeCheckFlags;
4630     (function (NodeCheckFlags) {
4631         NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
4632         NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
4633         NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
4634         NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
4635         NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
4636         NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
4637         NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
4638         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper";
4639         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding";
4640         NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments";
4641         NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed";
4642         NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass";
4643         NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding";
4644         NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding";
4645         NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding";
4646         NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop";
4647         NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding";
4648         NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding";
4649         NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter";
4650         NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked";
4651         NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference";
4652         NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass";
4653         NodeCheckFlags[NodeCheckFlags["ContainsClassWithPrivateIdentifiers"] = 67108864] = "ContainsClassWithPrivateIdentifiers";
4654     })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
4655     var TypeFlags;
4656     (function (TypeFlags) {
4657         TypeFlags[TypeFlags["Any"] = 1] = "Any";
4658         TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown";
4659         TypeFlags[TypeFlags["String"] = 4] = "String";
4660         TypeFlags[TypeFlags["Number"] = 8] = "Number";
4661         TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean";
4662         TypeFlags[TypeFlags["Enum"] = 32] = "Enum";
4663         TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt";
4664         TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral";
4665         TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral";
4666         TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral";
4667         TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral";
4668         TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral";
4669         TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol";
4670         TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol";
4671         TypeFlags[TypeFlags["Void"] = 16384] = "Void";
4672         TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined";
4673         TypeFlags[TypeFlags["Null"] = 65536] = "Null";
4674         TypeFlags[TypeFlags["Never"] = 131072] = "Never";
4675         TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter";
4676         TypeFlags[TypeFlags["Object"] = 524288] = "Object";
4677         TypeFlags[TypeFlags["Union"] = 1048576] = "Union";
4678         TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection";
4679         TypeFlags[TypeFlags["Index"] = 4194304] = "Index";
4680         TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess";
4681         TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional";
4682         TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
4683         TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
4684         TypeFlags[TypeFlags["TemplateLiteral"] = 134217728] = "TemplateLiteral";
4685         TypeFlags[TypeFlags["StringMapping"] = 268435456] = "StringMapping";
4686         /* @internal */
4687         TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
4688         /* @internal */
4689         TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
4690         TypeFlags[TypeFlags["Literal"] = 2944] = "Literal";
4691         TypeFlags[TypeFlags["Unit"] = 109440] = "Unit";
4692         TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral";
4693         /* @internal */
4694         TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique";
4695         /* @internal */
4696         TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy";
4697         TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy";
4698         /* @internal */
4699         TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic";
4700         /* @internal */
4701         TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive";
4702         TypeFlags[TypeFlags["StringLike"] = 402653316] = "StringLike";
4703         TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike";
4704         TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike";
4705         TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike";
4706         TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike";
4707         TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike";
4708         TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike";
4709         /* @internal */
4710         TypeFlags[TypeFlags["DisjointDomains"] = 469892092] = "DisjointDomains";
4711         TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection";
4712         TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType";
4713         TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable";
4714         TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive";
4715         TypeFlags[TypeFlags["InstantiablePrimitive"] = 406847488] = "InstantiablePrimitive";
4716         TypeFlags[TypeFlags["Instantiable"] = 465829888] = "Instantiable";
4717         TypeFlags[TypeFlags["StructuredOrInstantiable"] = 469499904] = "StructuredOrInstantiable";
4718         /* @internal */
4719         TypeFlags[TypeFlags["ObjectFlagsType"] = 3899393] = "ObjectFlagsType";
4720         /* @internal */
4721         TypeFlags[TypeFlags["Simplifiable"] = 25165824] = "Simplifiable";
4722         /* @internal */
4723         TypeFlags[TypeFlags["Substructure"] = 469237760] = "Substructure";
4724         // 'Narrowable' types are types where narrowing actually narrows.
4725         // This *should* be every type other than null, undefined, void, and never
4726         TypeFlags[TypeFlags["Narrowable"] = 536624127] = "Narrowable";
4727         /* @internal */
4728         TypeFlags[TypeFlags["NotPrimitiveUnion"] = 468598819] = "NotPrimitiveUnion";
4729         // The following flags are aggregated during union and intersection type construction
4730         /* @internal */
4731         TypeFlags[TypeFlags["IncludesMask"] = 205258751] = "IncludesMask";
4732         // The following flags are used for different purposes during union and intersection type construction
4733         /* @internal */
4734         TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
4735         /* @internal */
4736         TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType";
4737         /* @internal */
4738         TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard";
4739         /* @internal */
4740         TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject";
4741     })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
4742     var ObjectFlags;
4743     (function (ObjectFlags) {
4744         ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
4745         ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface";
4746         ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference";
4747         ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple";
4748         ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous";
4749         ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped";
4750         ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated";
4751         ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
4752         ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
4753         ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
4754         ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread";
4755         ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped";
4756         ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes";
4757         ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
4758         ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
4759         ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
4760         ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral";
4761         ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType";
4762         /* @internal */
4763         ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion";
4764         /* @internal */
4765         ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType";
4766         /* @internal */
4767         ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral";
4768         /* @internal */
4769         ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType";
4770         /* @internal */
4771         ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed";
4772         /* @internal */
4773         ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType";
4774         /* @internal */
4775         ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed";
4776         /* @internal */
4777         ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType";
4778         /* @internal */
4779         ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed";
4780         /* @internal */
4781         ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables";
4782         /* @internal */
4783         ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections";
4784         /* @internal */
4785         ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed";
4786         /* @internal */
4787         ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection";
4788         /* @internal */
4789         ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 1073741824] = "IsClassInstanceClone";
4790         ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
4791         /* @internal */
4792         ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening";
4793         /* @internal */
4794         ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags";
4795         // Object flags that uniquely identify the kind of ObjectType
4796         /* @internal */
4797         ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 2367] = "ObjectTypeKindMask";
4798     })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
4799     /* @internal */
4800     var VarianceFlags;
4801     (function (VarianceFlags) {
4802         VarianceFlags[VarianceFlags["Invariant"] = 0] = "Invariant";
4803         VarianceFlags[VarianceFlags["Covariant"] = 1] = "Covariant";
4804         VarianceFlags[VarianceFlags["Contravariant"] = 2] = "Contravariant";
4805         VarianceFlags[VarianceFlags["Bivariant"] = 3] = "Bivariant";
4806         VarianceFlags[VarianceFlags["Independent"] = 4] = "Independent";
4807         VarianceFlags[VarianceFlags["VarianceMask"] = 7] = "VarianceMask";
4808         VarianceFlags[VarianceFlags["Unmeasurable"] = 8] = "Unmeasurable";
4809         VarianceFlags[VarianceFlags["Unreliable"] = 16] = "Unreliable";
4810         VarianceFlags[VarianceFlags["AllowsStructuralFallback"] = 24] = "AllowsStructuralFallback";
4811     })(VarianceFlags = ts.VarianceFlags || (ts.VarianceFlags = {}));
4812     var ElementFlags;
4813     (function (ElementFlags) {
4814         ElementFlags[ElementFlags["Required"] = 1] = "Required";
4815         ElementFlags[ElementFlags["Optional"] = 2] = "Optional";
4816         ElementFlags[ElementFlags["Rest"] = 4] = "Rest";
4817         ElementFlags[ElementFlags["Variadic"] = 8] = "Variadic";
4818         ElementFlags[ElementFlags["Fixed"] = 3] = "Fixed";
4819         ElementFlags[ElementFlags["Variable"] = 12] = "Variable";
4820         ElementFlags[ElementFlags["NonRequired"] = 14] = "NonRequired";
4821         ElementFlags[ElementFlags["NonRest"] = 11] = "NonRest";
4822     })(ElementFlags = ts.ElementFlags || (ts.ElementFlags = {}));
4823     /* @internal */
4824     var JsxReferenceKind;
4825     (function (JsxReferenceKind) {
4826         JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component";
4827         JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function";
4828         JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed";
4829     })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {}));
4830     var SignatureKind;
4831     (function (SignatureKind) {
4832         SignatureKind[SignatureKind["Call"] = 0] = "Call";
4833         SignatureKind[SignatureKind["Construct"] = 1] = "Construct";
4834     })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {}));
4835     /* @internal */
4836     var SignatureFlags;
4837     (function (SignatureFlags) {
4838         SignatureFlags[SignatureFlags["None"] = 0] = "None";
4839         // Propagating flags
4840         SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter";
4841         SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes";
4842         SignatureFlags[SignatureFlags["Abstract"] = 4] = "Abstract";
4843         // Non-propagating flags
4844         SignatureFlags[SignatureFlags["IsInnerCallChain"] = 8] = "IsInnerCallChain";
4845         SignatureFlags[SignatureFlags["IsOuterCallChain"] = 16] = "IsOuterCallChain";
4846         SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 32] = "IsUntypedSignatureInJSFile";
4847         // We do not propagate `IsInnerCallChain` or `IsOuterCallChain` to instantiated signatures, as that would result in us
4848         // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when
4849         // instantiating the return type.
4850         SignatureFlags[SignatureFlags["PropagatingFlags"] = 39] = "PropagatingFlags";
4851         SignatureFlags[SignatureFlags["CallChainFlags"] = 24] = "CallChainFlags";
4852     })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {}));
4853     var IndexKind;
4854     (function (IndexKind) {
4855         IndexKind[IndexKind["String"] = 0] = "String";
4856         IndexKind[IndexKind["Number"] = 1] = "Number";
4857     })(IndexKind = ts.IndexKind || (ts.IndexKind = {}));
4858     /* @internal */
4859     var TypeMapKind;
4860     (function (TypeMapKind) {
4861         TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple";
4862         TypeMapKind[TypeMapKind["Array"] = 1] = "Array";
4863         TypeMapKind[TypeMapKind["Function"] = 2] = "Function";
4864         TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite";
4865         TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged";
4866     })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {}));
4867     var InferencePriority;
4868     (function (InferencePriority) {
4869         InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
4870         InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple";
4871         InferencePriority[InferencePriority["HomomorphicMappedType"] = 4] = "HomomorphicMappedType";
4872         InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 8] = "PartialHomomorphicMappedType";
4873         InferencePriority[InferencePriority["MappedTypeConstraint"] = 16] = "MappedTypeConstraint";
4874         InferencePriority[InferencePriority["ContravariantConditional"] = 32] = "ContravariantConditional";
4875         InferencePriority[InferencePriority["ReturnType"] = 64] = "ReturnType";
4876         InferencePriority[InferencePriority["LiteralKeyof"] = 128] = "LiteralKeyof";
4877         InferencePriority[InferencePriority["NoConstraints"] = 256] = "NoConstraints";
4878         InferencePriority[InferencePriority["AlwaysStrict"] = 512] = "AlwaysStrict";
4879         InferencePriority[InferencePriority["MaxValue"] = 1024] = "MaxValue";
4880         InferencePriority[InferencePriority["PriorityImpliesCombination"] = 208] = "PriorityImpliesCombination";
4881         InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity";
4882     })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
4883     /* @internal */
4884     var InferenceFlags;
4885     (function (InferenceFlags) {
4886         InferenceFlags[InferenceFlags["None"] = 0] = "None";
4887         InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
4888         InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
4889         InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
4890     })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
4891     /**
4892      * Ternary values are defined such that
4893      * x & y picks the lesser in the order False < Unknown < Maybe < True, and
4894      * x | y picks the greater in the order False < Unknown < Maybe < True.
4895      * Generally, Ternary.Maybe is used as the result of a relation that depends on itself, and
4896      * Ternary.Unknown is used as the result of a variance check that depends on itself. We make
4897      * a distinction because we don't want to cache circular variance check results.
4898      */
4899     /* @internal */
4900     var Ternary;
4901     (function (Ternary) {
4902         Ternary[Ternary["False"] = 0] = "False";
4903         Ternary[Ternary["Unknown"] = 1] = "Unknown";
4904         Ternary[Ternary["Maybe"] = 3] = "Maybe";
4905         Ternary[Ternary["True"] = -1] = "True";
4906     })(Ternary = ts.Ternary || (ts.Ternary = {}));
4907     /* @internal */
4908     var AssignmentDeclarationKind;
4909     (function (AssignmentDeclarationKind) {
4910         AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None";
4911         /// exports.name = expr
4912         /// module.exports.name = expr
4913         AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty";
4914         /// module.exports = expr
4915         AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports";
4916         /// className.prototype.name = expr
4917         AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty";
4918         /// this.name = expr
4919         AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty";
4920         // F.name = expr
4921         AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property";
4922         // F.prototype = { ... }
4923         AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype";
4924         // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) });
4925         // Object.defineProperty(x, 'name', { get: Function, set: Function });
4926         // Object.defineProperty(x, 'name', { get: Function });
4927         // Object.defineProperty(x, 'name', { set: Function });
4928         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue";
4929         // Object.defineProperty(exports || module.exports, 'name', ...);
4930         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports";
4931         // Object.defineProperty(Foo.prototype, 'name', ...);
4932         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty";
4933     })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {}));
4934     var DiagnosticCategory;
4935     (function (DiagnosticCategory) {
4936         DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
4937         DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
4938         DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
4939         DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
4940     })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
4941     /* @internal */
4942     function diagnosticCategoryName(d, lowerCase) {
4943         if (lowerCase === void 0) { lowerCase = true; }
4944         var name = DiagnosticCategory[d.category];
4945         return lowerCase ? name.toLowerCase() : name;
4946     }
4947     ts.diagnosticCategoryName = diagnosticCategoryName;
4948     var ModuleResolutionKind;
4949     (function (ModuleResolutionKind) {
4950         ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
4951         ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs";
4952     })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {}));
4953     var WatchFileKind;
4954     (function (WatchFileKind) {
4955         WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval";
4956         WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval";
4957         WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4958         WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents";
4959         WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory";
4960     })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {}));
4961     var WatchDirectoryKind;
4962     (function (WatchDirectoryKind) {
4963         WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents";
4964         WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval";
4965         WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4966     })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {}));
4967     var PollingWatchKind;
4968     (function (PollingWatchKind) {
4969         PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval";
4970         PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval";
4971         PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority";
4972     })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {}));
4973     var ModuleKind;
4974     (function (ModuleKind) {
4975         ModuleKind[ModuleKind["None"] = 0] = "None";
4976         ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS";
4977         ModuleKind[ModuleKind["AMD"] = 2] = "AMD";
4978         ModuleKind[ModuleKind["UMD"] = 3] = "UMD";
4979         ModuleKind[ModuleKind["System"] = 4] = "System";
4980         // NOTE: ES module kinds should be contiguous to more easily check whether a module kind is *any* ES module kind.
4981         //       Non-ES module kinds should not come between ES2015 (the earliest ES module kind) and ESNext (the last ES
4982         //       module kind).
4983         ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
4984         ModuleKind[ModuleKind["ES2020"] = 6] = "ES2020";
4985         ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext";
4986     })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
4987     var JsxEmit;
4988     (function (JsxEmit) {
4989         JsxEmit[JsxEmit["None"] = 0] = "None";
4990         JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
4991         JsxEmit[JsxEmit["React"] = 2] = "React";
4992         JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
4993         JsxEmit[JsxEmit["ReactJSX"] = 4] = "ReactJSX";
4994         JsxEmit[JsxEmit["ReactJSXDev"] = 5] = "ReactJSXDev";
4995     })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
4996     var ImportsNotUsedAsValues;
4997     (function (ImportsNotUsedAsValues) {
4998         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Remove"] = 0] = "Remove";
4999         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Preserve"] = 1] = "Preserve";
5000         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Error"] = 2] = "Error";
5001     })(ImportsNotUsedAsValues = ts.ImportsNotUsedAsValues || (ts.ImportsNotUsedAsValues = {}));
5002     var NewLineKind;
5003     (function (NewLineKind) {
5004         NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
5005         NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
5006     })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {}));
5007     var ScriptKind;
5008     (function (ScriptKind) {
5009         ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
5010         ScriptKind[ScriptKind["JS"] = 1] = "JS";
5011         ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
5012         ScriptKind[ScriptKind["TS"] = 3] = "TS";
5013         ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
5014         ScriptKind[ScriptKind["External"] = 5] = "External";
5015         ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
5016         /**
5017          * Used on extensions that doesn't define the ScriptKind but the content defines it.
5018          * Deferred extensions are going to be included in all project contexts.
5019          */
5020         ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
5021     })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
5022     var ScriptTarget;
5023     (function (ScriptTarget) {
5024         ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
5025         ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
5026         ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
5027         ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
5028         ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
5029         ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
5030         ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
5031         ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020";
5032         ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext";
5033         ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
5034         ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest";
5035     })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
5036     var LanguageVariant;
5037     (function (LanguageVariant) {
5038         LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard";
5039         LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX";
5040     })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {}));
5041     var WatchDirectoryFlags;
5042     (function (WatchDirectoryFlags) {
5043         WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
5044         WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
5045     })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
5046     /* @internal */
5047     var CharacterCodes;
5048     (function (CharacterCodes) {
5049         CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
5050         CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
5051         CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
5052         CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
5053         CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
5054         CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
5055         CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
5056         // Unicode 3.0 space characters
5057         CharacterCodes[CharacterCodes["space"] = 32] = "space";
5058         CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
5059         CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
5060         CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
5061         CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
5062         CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
5063         CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
5064         CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
5065         CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
5066         CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
5067         CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
5068         CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
5069         CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
5070         CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
5071         CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
5072         CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
5073         CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
5074         CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
5075         CharacterCodes[CharacterCodes["_"] = 95] = "_";
5076         CharacterCodes[CharacterCodes["$"] = 36] = "$";
5077         CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
5078         CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
5079         CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
5080         CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
5081         CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
5082         CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
5083         CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
5084         CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
5085         CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
5086         CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
5087         CharacterCodes[CharacterCodes["a"] = 97] = "a";
5088         CharacterCodes[CharacterCodes["b"] = 98] = "b";
5089         CharacterCodes[CharacterCodes["c"] = 99] = "c";
5090         CharacterCodes[CharacterCodes["d"] = 100] = "d";
5091         CharacterCodes[CharacterCodes["e"] = 101] = "e";
5092         CharacterCodes[CharacterCodes["f"] = 102] = "f";
5093         CharacterCodes[CharacterCodes["g"] = 103] = "g";
5094         CharacterCodes[CharacterCodes["h"] = 104] = "h";
5095         CharacterCodes[CharacterCodes["i"] = 105] = "i";
5096         CharacterCodes[CharacterCodes["j"] = 106] = "j";
5097         CharacterCodes[CharacterCodes["k"] = 107] = "k";
5098         CharacterCodes[CharacterCodes["l"] = 108] = "l";
5099         CharacterCodes[CharacterCodes["m"] = 109] = "m";
5100         CharacterCodes[CharacterCodes["n"] = 110] = "n";
5101         CharacterCodes[CharacterCodes["o"] = 111] = "o";
5102         CharacterCodes[CharacterCodes["p"] = 112] = "p";
5103         CharacterCodes[CharacterCodes["q"] = 113] = "q";
5104         CharacterCodes[CharacterCodes["r"] = 114] = "r";
5105         CharacterCodes[CharacterCodes["s"] = 115] = "s";
5106         CharacterCodes[CharacterCodes["t"] = 116] = "t";
5107         CharacterCodes[CharacterCodes["u"] = 117] = "u";
5108         CharacterCodes[CharacterCodes["v"] = 118] = "v";
5109         CharacterCodes[CharacterCodes["w"] = 119] = "w";
5110         CharacterCodes[CharacterCodes["x"] = 120] = "x";
5111         CharacterCodes[CharacterCodes["y"] = 121] = "y";
5112         CharacterCodes[CharacterCodes["z"] = 122] = "z";
5113         CharacterCodes[CharacterCodes["A"] = 65] = "A";
5114         CharacterCodes[CharacterCodes["B"] = 66] = "B";
5115         CharacterCodes[CharacterCodes["C"] = 67] = "C";
5116         CharacterCodes[CharacterCodes["D"] = 68] = "D";
5117         CharacterCodes[CharacterCodes["E"] = 69] = "E";
5118         CharacterCodes[CharacterCodes["F"] = 70] = "F";
5119         CharacterCodes[CharacterCodes["G"] = 71] = "G";
5120         CharacterCodes[CharacterCodes["H"] = 72] = "H";
5121         CharacterCodes[CharacterCodes["I"] = 73] = "I";
5122         CharacterCodes[CharacterCodes["J"] = 74] = "J";
5123         CharacterCodes[CharacterCodes["K"] = 75] = "K";
5124         CharacterCodes[CharacterCodes["L"] = 76] = "L";
5125         CharacterCodes[CharacterCodes["M"] = 77] = "M";
5126         CharacterCodes[CharacterCodes["N"] = 78] = "N";
5127         CharacterCodes[CharacterCodes["O"] = 79] = "O";
5128         CharacterCodes[CharacterCodes["P"] = 80] = "P";
5129         CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
5130         CharacterCodes[CharacterCodes["R"] = 82] = "R";
5131         CharacterCodes[CharacterCodes["S"] = 83] = "S";
5132         CharacterCodes[CharacterCodes["T"] = 84] = "T";
5133         CharacterCodes[CharacterCodes["U"] = 85] = "U";
5134         CharacterCodes[CharacterCodes["V"] = 86] = "V";
5135         CharacterCodes[CharacterCodes["W"] = 87] = "W";
5136         CharacterCodes[CharacterCodes["X"] = 88] = "X";
5137         CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
5138         CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
5139         CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
5140         CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
5141         CharacterCodes[CharacterCodes["at"] = 64] = "at";
5142         CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
5143         CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
5144         CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
5145         CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
5146         CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
5147         CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
5148         CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
5149         CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
5150         CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
5151         CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
5152         CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
5153         CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
5154         CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
5155         CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
5156         CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
5157         CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
5158         CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
5159         CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
5160         CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
5161         CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
5162         CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
5163         CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
5164         CharacterCodes[CharacterCodes["question"] = 63] = "question";
5165         CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
5166         CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
5167         CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
5168         CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
5169         CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
5170         CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
5171         CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
5172         CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
5173         CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
5174     })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {}));
5175     var Extension;
5176     (function (Extension) {
5177         Extension["Ts"] = ".ts";
5178         Extension["Tsx"] = ".tsx";
5179         Extension["Dts"] = ".d.ts";
5180         Extension["Js"] = ".js";
5181         Extension["Jsx"] = ".jsx";
5182         Extension["Json"] = ".json";
5183         Extension["TsBuildInfo"] = ".tsbuildinfo";
5184     })(Extension = ts.Extension || (ts.Extension = {}));
5185     /* @internal */
5186     var TransformFlags;
5187     (function (TransformFlags) {
5188         TransformFlags[TransformFlags["None"] = 0] = "None";
5189         // Facts
5190         // - Flags used to indicate that a node or subtree contains syntax that requires transformation.
5191         TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
5192         TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
5193         TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
5194         TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020";
5195         TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019";
5196         TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018";
5197         TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017";
5198         TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016";
5199         TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015";
5200         TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
5201         TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment";
5202         // Markers
5203         // - Flags used to indicate that a subtree contains a specific transformation.
5204         TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax";
5205         TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis";
5206         TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread";
5207         TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread";
5208         TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName";
5209         TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding";
5210         TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern";
5211         TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield";
5212         TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait";
5213         TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion";
5214         TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport";
5215         TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields";
5216         TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 8388608] = "ContainsPossibleTopLevelAwait";
5217         // Please leave this as 1 << 29.
5218         // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
5219         // It is a good reminder of how much room we have left
5220         TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
5221         // Assertions
5222         // - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
5223         TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
5224         TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
5225         TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
5226         TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020";
5227         TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019";
5228         TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018";
5229         TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017";
5230         TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016";
5231         TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015";
5232         TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator";
5233         TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment";
5234         // Scope Exclusions
5235         // - Bitmasks that exclude flags from propagating out of a specific context
5236         //   into the subtree flags of their container.
5237         TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
5238         TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
5239         TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
5240         TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 547309568] = "ArrowFunctionExcludes";
5241         TransformFlags[TransformFlags["FunctionExcludes"] = 547313664] = "FunctionExcludes";
5242         TransformFlags[TransformFlags["ConstructorExcludes"] = 547311616] = "ConstructorExcludes";
5243         TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes";
5244         TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes";
5245         TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes";
5246         TransformFlags[TransformFlags["ModuleExcludes"] = 546379776] = "ModuleExcludes";
5247         TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
5248         TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes";
5249         TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes";
5250         TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes";
5251         TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
5252         TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes";
5253         TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes";
5254         // Propagating flags
5255         // - Bitmasks for flags that should propagate from a child
5256         TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags";
5257         // Masks
5258         // - Additional bitmasks
5259     })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
5260     var EmitFlags;
5261     (function (EmitFlags) {
5262         EmitFlags[EmitFlags["None"] = 0] = "None";
5263         EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
5264         EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode";
5265         EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution";
5266         EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis";
5267         EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap";
5268         EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap";
5269         EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap";
5270         EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps";
5271         EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps";
5272         EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps";
5273         EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps";
5274         EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments";
5275         EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments";
5276         EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments";
5277         EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments";
5278         EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName";
5279         EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName";
5280         EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName";
5281         EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName";
5282         EmitFlags[EmitFlags["Indented"] = 65536] = "Indented";
5283         EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation";
5284         EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody";
5285         EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope";
5286         EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue";
5287         EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting";
5288         EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
5289         EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
5290         EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
5291         /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
5292         /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
5293         /*@internal*/ EmitFlags[EmitFlags["IgnoreSourceNewlines"] = 134217728] = "IgnoreSourceNewlines";
5294     })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
5295     /**
5296      * Used by the checker, this enum keeps track of external emit helpers that should be type
5297      * checked.
5298      */
5299     /* @internal */
5300     var ExternalEmitHelpers;
5301     (function (ExternalEmitHelpers) {
5302         ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
5303         ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
5304         ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
5305         ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
5306         ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
5307         ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
5308         ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
5309         ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
5310         ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
5311         ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
5312         ExternalEmitHelpers[ExternalEmitHelpers["SpreadArray"] = 1024] = "SpreadArray";
5313         ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 2048] = "Await";
5314         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 4096] = "AsyncGenerator";
5315         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 8192] = "AsyncDelegator";
5316         ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 16384] = "AsyncValues";
5317         ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 32768] = "ExportStar";
5318         ExternalEmitHelpers[ExternalEmitHelpers["ImportStar"] = 65536] = "ImportStar";
5319         ExternalEmitHelpers[ExternalEmitHelpers["ImportDefault"] = 131072] = "ImportDefault";
5320         ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 262144] = "MakeTemplateObject";
5321         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 524288] = "ClassPrivateFieldGet";
5322         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 1048576] = "ClassPrivateFieldSet";
5323         ExternalEmitHelpers[ExternalEmitHelpers["CreateBinding"] = 2097152] = "CreateBinding";
5324         ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
5325         ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 2097152] = "LastEmitHelper";
5326         // Helpers included by ES2015 for..of
5327         ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
5328         // Helpers included by ES2017 for..await..of
5329         ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 16384] = "ForAwaitOfIncludes";
5330         // Helpers included by ES2017 async generators
5331         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 6144] = "AsyncGeneratorIncludes";
5332         // Helpers included by yield* in ES2017 async generators
5333         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 26624] = "AsyncDelegatorIncludes";
5334         // Helpers included by ES2015 spread
5335         ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
5336     })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
5337     var EmitHint;
5338     (function (EmitHint) {
5339         EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
5340         EmitHint[EmitHint["Expression"] = 1] = "Expression";
5341         EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
5342         EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter";
5343         EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
5344         EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
5345         EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue";
5346     })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
5347     var OuterExpressionKinds;
5348     (function (OuterExpressionKinds) {
5349         OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses";
5350         OuterExpressionKinds[OuterExpressionKinds["TypeAssertions"] = 2] = "TypeAssertions";
5351         OuterExpressionKinds[OuterExpressionKinds["NonNullAssertions"] = 4] = "NonNullAssertions";
5352         OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 8] = "PartiallyEmittedExpressions";
5353         OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 6] = "Assertions";
5354         OuterExpressionKinds[OuterExpressionKinds["All"] = 15] = "All";
5355     })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {}));
5356     /* @internal */
5357     var LexicalEnvironmentFlags;
5358     (function (LexicalEnvironmentFlags) {
5359         LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None";
5360         LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters";
5361         LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list
5362     })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {}));
5363     /*@internal*/
5364     var BundleFileSectionKind;
5365     (function (BundleFileSectionKind) {
5366         BundleFileSectionKind["Prologue"] = "prologue";
5367         BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
5368         BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
5369         BundleFileSectionKind["Reference"] = "reference";
5370         BundleFileSectionKind["Type"] = "type";
5371         BundleFileSectionKind["Lib"] = "lib";
5372         BundleFileSectionKind["Prepend"] = "prepend";
5373         BundleFileSectionKind["Text"] = "text";
5374         BundleFileSectionKind["Internal"] = "internal";
5375         // comments?
5376     })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
5377     var ListFormat;
5378     (function (ListFormat) {
5379         ListFormat[ListFormat["None"] = 0] = "None";
5380         // Line separators
5381         ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
5382         ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
5383         ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
5384         ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
5385         // Delimiters
5386         ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
5387         ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
5388         ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
5389         ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
5390         ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited";
5391         ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask";
5392         ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma";
5393         // Whitespace
5394         ListFormat[ListFormat["Indented"] = 128] = "Indented";
5395         ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces";
5396         ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings";
5397         // Brackets/Braces
5398         ListFormat[ListFormat["Braces"] = 1024] = "Braces";
5399         ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis";
5400         ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets";
5401         ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets";
5402         ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask";
5403         ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined";
5404         ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty";
5405         ListFormat[ListFormat["Optional"] = 49152] = "Optional";
5406         // Other
5407         ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine";
5408         ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine";
5409         ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments";
5410         ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty";
5411         ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement";
5412         ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList";
5413         // Precomputed Formats
5414         ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers";
5415         ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses";
5416         ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers";
5417         ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers";
5418         ListFormat[ListFormat["SingleLineTupleTypeElements"] = 528] = "SingleLineTupleTypeElements";
5419         ListFormat[ListFormat["MultiLineTupleTypeElements"] = 657] = "MultiLineTupleTypeElements";
5420         ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents";
5421         ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents";
5422         ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements";
5423         ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements";
5424         ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties";
5425         ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements";
5426         ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements";
5427         ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments";
5428         ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments";
5429         ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans";
5430         ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements";
5431         ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements";
5432         ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList";
5433         ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements";
5434         ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
5435         ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses";
5436         ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers";
5437         ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers";
5438         ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers";
5439         ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses";
5440         ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements";
5441         ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren";
5442         ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes";
5443         ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements";
5444         ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes";
5445         ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements";
5446         ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators";
5447         ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments";
5448         ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters";
5449         ListFormat[ListFormat["Parameters"] = 2576] = "Parameters";
5450         ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters";
5451         ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment";
5452     })(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
5453     /* @internal */
5454     var PragmaKindFlags;
5455     (function (PragmaKindFlags) {
5456         PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
5457         /**
5458          * Triple slash comment of the form
5459          * /// <pragma-name argname="value" />
5460          */
5461         PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
5462         /**
5463          * Single line comment of the form
5464          * // @pragma-name argval1 argval2
5465          * or
5466          * /// @pragma-name argval1 argval2
5467          */
5468         PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
5469         /**
5470          * Multiline non-jsdoc pragma of the form
5471          * /* @pragma-name argval1 argval2 * /
5472          */
5473         PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
5474         PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
5475         PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
5476     })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
5477     // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
5478     //  fancy effectively defining it twice, once in value-space and once in type-space
5479     /* @internal */
5480     ts.commentPragmas = {
5481         "reference": {
5482             args: [
5483                 { name: "types", optional: true, captureSpan: true },
5484                 { name: "lib", optional: true, captureSpan: true },
5485                 { name: "path", optional: true, captureSpan: true },
5486                 { name: "no-default-lib", optional: true }
5487             ],
5488             kind: 1 /* TripleSlashXML */
5489         },
5490         "amd-dependency": {
5491             args: [{ name: "path" }, { name: "name", optional: true }],
5492             kind: 1 /* TripleSlashXML */
5493         },
5494         "amd-module": {
5495             args: [{ name: "name" }],
5496             kind: 1 /* TripleSlashXML */
5497         },
5498         "ts-check": {
5499             kind: 2 /* SingleLine */
5500         },
5501         "ts-nocheck": {
5502             kind: 2 /* SingleLine */
5503         },
5504         "jsx": {
5505             args: [{ name: "factory" }],
5506             kind: 4 /* MultiLine */
5507         },
5508         "jsxfrag": {
5509             args: [{ name: "factory" }],
5510             kind: 4 /* MultiLine */
5511         },
5512         "jsximportsource": {
5513             args: [{ name: "factory" }],
5514             kind: 4 /* MultiLine */
5515         },
5516         "jsxruntime": {
5517             args: [{ name: "factory" }],
5518             kind: 4 /* MultiLine */
5519         },
5520     };
5521 })(ts || (ts = {}));
5522 /* @internal */
5523 var ts;
5524 (function (ts) {
5525     /**
5526      * Internally, we represent paths as strings with '/' as the directory separator.
5527      * When we make system calls (eg: LanguageServiceHost.getDirectory()),
5528      * we expect the host to correctly handle paths in our specified format.
5529      */
5530     ts.directorySeparator = "/";
5531     ts.altDirectorySeparator = "\\";
5532     var urlSchemeSeparator = "://";
5533     var backslashRegExp = /\\/g;
5534     //// Path Tests
5535     /**
5536      * Determines whether a charCode corresponds to `/` or `\`.
5537      */
5538     function isAnyDirectorySeparator(charCode) {
5539         return charCode === 47 /* slash */ || charCode === 92 /* backslash */;
5540     }
5541     ts.isAnyDirectorySeparator = isAnyDirectorySeparator;
5542     /**
5543      * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
5544      */
5545     function isUrl(path) {
5546         return getEncodedRootLength(path) < 0;
5547     }
5548     ts.isUrl = isUrl;
5549     /**
5550      * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
5551      * like `c:`, `c:\` or `c:/`).
5552      */
5553     function isRootedDiskPath(path) {
5554         return getEncodedRootLength(path) > 0;
5555     }
5556     ts.isRootedDiskPath = isRootedDiskPath;
5557     /**
5558      * Determines whether a path consists only of a path root.
5559      */
5560     function isDiskPathRoot(path) {
5561         var rootLength = getEncodedRootLength(path);
5562         return rootLength > 0 && rootLength === path.length;
5563     }
5564     ts.isDiskPathRoot = isDiskPathRoot;
5565     /**
5566      * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
5567      *
5568      * ```ts
5569      * // POSIX
5570      * pathIsAbsolute("/path/to/file.ext") === true
5571      * // DOS
5572      * pathIsAbsolute("c:/path/to/file.ext") === true
5573      * // URL
5574      * pathIsAbsolute("file:///path/to/file.ext") === true
5575      * // Non-absolute
5576      * pathIsAbsolute("path/to/file.ext") === false
5577      * pathIsAbsolute("./path/to/file.ext") === false
5578      * ```
5579      */
5580     function pathIsAbsolute(path) {
5581         return getEncodedRootLength(path) !== 0;
5582     }
5583     ts.pathIsAbsolute = pathIsAbsolute;
5584     /**
5585      * Determines whether a path starts with a relative path component (i.e. `.` or `..`).
5586      */
5587     function pathIsRelative(path) {
5588         return /^\.\.?($|[\\/])/.test(path);
5589     }
5590     ts.pathIsRelative = pathIsRelative;
5591     /**
5592      * Determines whether a path is neither relative nor absolute, e.g. "path/to/file".
5593      * Also known misleadingly as "non-relative".
5594      */
5595     function pathIsBareSpecifier(path) {
5596         return !pathIsAbsolute(path) && !pathIsRelative(path);
5597     }
5598     ts.pathIsBareSpecifier = pathIsBareSpecifier;
5599     function hasExtension(fileName) {
5600         return ts.stringContains(getBaseFileName(fileName), ".");
5601     }
5602     ts.hasExtension = hasExtension;
5603     function fileExtensionIs(path, extension) {
5604         return path.length > extension.length && ts.endsWith(path, extension);
5605     }
5606     ts.fileExtensionIs = fileExtensionIs;
5607     function fileExtensionIsOneOf(path, extensions) {
5608         for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
5609             var extension = extensions_1[_i];
5610             if (fileExtensionIs(path, extension)) {
5611                 return true;
5612             }
5613         }
5614         return false;
5615     }
5616     ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
5617     /**
5618      * Determines whether a path has a trailing separator (`/` or `\\`).
5619      */
5620     function hasTrailingDirectorySeparator(path) {
5621         return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
5622     }
5623     ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
5624     //// Path Parsing
5625     function isVolumeCharacter(charCode) {
5626         return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
5627             (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
5628     }
5629     function getFileUrlVolumeSeparatorEnd(url, start) {
5630         var ch0 = url.charCodeAt(start);
5631         if (ch0 === 58 /* colon */)
5632             return start + 1;
5633         if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
5634             var ch2 = url.charCodeAt(start + 2);
5635             if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
5636                 return start + 3;
5637         }
5638         return -1;
5639     }
5640     /**
5641      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
5642      * If the root is part of a URL, the twos-complement of the root length is returned.
5643      */
5644     function getEncodedRootLength(path) {
5645         if (!path)
5646             return 0;
5647         var ch0 = path.charCodeAt(0);
5648         // POSIX or UNC
5649         if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
5650             if (path.charCodeAt(1) !== ch0)
5651                 return 1; // POSIX: "/" (or non-normalized "\")
5652             var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : ts.altDirectorySeparator, 2);
5653             if (p1 < 0)
5654                 return path.length; // UNC: "//server" or "\\server"
5655             return p1 + 1; // UNC: "//server/" or "\\server\"
5656         }
5657         // DOS
5658         if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
5659             var ch2 = path.charCodeAt(2);
5660             if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
5661                 return 3; // DOS: "c:/" or "c:\"
5662             if (path.length === 2)
5663                 return 2; // DOS: "c:" (but not "c:d")
5664         }
5665         // URL
5666         var schemeEnd = path.indexOf(urlSchemeSeparator);
5667         if (schemeEnd !== -1) {
5668             var authorityStart = schemeEnd + urlSchemeSeparator.length;
5669             var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
5670             if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
5671                 // For local "file" URLs, include the leading DOS volume (if present).
5672                 // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
5673                 // special case interpreted as "the machine from which the URL is being interpreted".
5674                 var scheme = path.slice(0, schemeEnd);
5675                 var authority = path.slice(authorityStart, authorityEnd);
5676                 if (scheme === "file" && (authority === "" || authority === "localhost") &&
5677                     isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
5678                     var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
5679                     if (volumeSeparatorEnd !== -1) {
5680                         if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
5681                             // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
5682                             return ~(volumeSeparatorEnd + 1);
5683                         }
5684                         if (volumeSeparatorEnd === path.length) {
5685                             // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
5686                             // but not "file:///c:d" or "file:///c%3ad"
5687                             return ~volumeSeparatorEnd;
5688                         }
5689                     }
5690                 }
5691                 return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
5692             }
5693             return ~path.length; // URL: "file://server", "http://server"
5694         }
5695         // relative
5696         return 0;
5697     }
5698     /**
5699      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
5700      *
5701      * For example:
5702      * ```ts
5703      * getRootLength("a") === 0                   // ""
5704      * getRootLength("/") === 1                   // "/"
5705      * getRootLength("c:") === 2                  // "c:"
5706      * getRootLength("c:d") === 0                 // ""
5707      * getRootLength("c:/") === 3                 // "c:/"
5708      * getRootLength("c:\\") === 3                // "c:\\"
5709      * getRootLength("//server") === 7            // "//server"
5710      * getRootLength("//server/share") === 8      // "//server/"
5711      * getRootLength("\\\\server") === 7          // "\\\\server"
5712      * getRootLength("\\\\server\\share") === 8   // "\\\\server\\"
5713      * getRootLength("file:///path") === 8        // "file:///"
5714      * getRootLength("file:///c:") === 10         // "file:///c:"
5715      * getRootLength("file:///c:d") === 8         // "file:///"
5716      * getRootLength("file:///c:/path") === 11    // "file:///c:/"
5717      * getRootLength("file://server") === 13      // "file://server"
5718      * getRootLength("file://server/path") === 14 // "file://server/"
5719      * getRootLength("http://server") === 13      // "http://server"
5720      * getRootLength("http://server/path") === 14 // "http://server/"
5721      * ```
5722      */
5723     function getRootLength(path) {
5724         var rootLength = getEncodedRootLength(path);
5725         return rootLength < 0 ? ~rootLength : rootLength;
5726     }
5727     ts.getRootLength = getRootLength;
5728     function getDirectoryPath(path) {
5729         path = normalizeSlashes(path);
5730         // If the path provided is itself the root, then return it.
5731         var rootLength = getRootLength(path);
5732         if (rootLength === path.length)
5733             return path;
5734         // return the leading portion of the path up to the last (non-terminal) directory separator
5735         // but not including any trailing directory separator.
5736         path = removeTrailingDirectorySeparator(path);
5737         return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
5738     }
5739     ts.getDirectoryPath = getDirectoryPath;
5740     function getBaseFileName(path, extensions, ignoreCase) {
5741         path = normalizeSlashes(path);
5742         // if the path provided is itself the root, then it has not file name.
5743         var rootLength = getRootLength(path);
5744         if (rootLength === path.length)
5745             return "";
5746         // return the trailing portion of the path starting after the last (non-terminal) directory
5747         // separator but not including any trailing directory separator.
5748         path = removeTrailingDirectorySeparator(path);
5749         var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
5750         var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
5751         return extension ? name.slice(0, name.length - extension.length) : name;
5752     }
5753     ts.getBaseFileName = getBaseFileName;
5754     function tryGetExtensionFromPath(path, extension, stringEqualityComparer) {
5755         if (!ts.startsWith(extension, "."))
5756             extension = "." + extension;
5757         if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) {
5758             var pathExtension = path.slice(path.length - extension.length);
5759             if (stringEqualityComparer(pathExtension, extension)) {
5760                 return pathExtension;
5761             }
5762         }
5763     }
5764     function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
5765         if (typeof extensions === "string") {
5766             return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
5767         }
5768         for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
5769             var extension = extensions_2[_i];
5770             var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
5771             if (result)
5772                 return result;
5773         }
5774         return "";
5775     }
5776     function getAnyExtensionFromPath(path, extensions, ignoreCase) {
5777         // Retrieves any string from the final "." onwards from a base file name.
5778         // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
5779         if (extensions) {
5780             return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
5781         }
5782         var baseFileName = getBaseFileName(path);
5783         var extensionIndex = baseFileName.lastIndexOf(".");
5784         if (extensionIndex >= 0) {
5785             return baseFileName.substring(extensionIndex);
5786         }
5787         return "";
5788     }
5789     ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
5790     function pathComponents(path, rootLength) {
5791         var root = path.substring(0, rootLength);
5792         var rest = path.substring(rootLength).split(ts.directorySeparator);
5793         if (rest.length && !ts.lastOrUndefined(rest))
5794             rest.pop();
5795         return __spreadArray([root], rest);
5796     }
5797     /**
5798      * Parse a path into an array containing a root component (at index 0) and zero or more path
5799      * components (at indices > 0). The result is not normalized.
5800      * If the path is relative, the root component is `""`.
5801      * If the path is absolute, the root component includes the first path separator (`/`).
5802      *
5803      * ```ts
5804      * // POSIX
5805      * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
5806      * getPathComponents("/path/to/") === ["/", "path", "to"]
5807      * getPathComponents("/") === ["/"]
5808      * // DOS
5809      * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
5810      * getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
5811      * getPathComponents("c:/") === ["c:/"]
5812      * getPathComponents("c:") === ["c:"]
5813      * // URL
5814      * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
5815      * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
5816      * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
5817      * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
5818      * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
5819      * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
5820      * getPathComponents("file://server/") === ["file://server/"]
5821      * getPathComponents("file://server") === ["file://server"]
5822      * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
5823      * getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
5824      * getPathComponents("file:///") === ["file:///"]
5825      * getPathComponents("file://") === ["file://"]
5826      */
5827     function getPathComponents(path, currentDirectory) {
5828         if (currentDirectory === void 0) { currentDirectory = ""; }
5829         path = combinePaths(currentDirectory, path);
5830         return pathComponents(path, getRootLength(path));
5831     }
5832     ts.getPathComponents = getPathComponents;
5833     //// Path Formatting
5834     /**
5835      * Formats a parsed path consisting of a root component (at index 0) and zero or more path
5836      * segments (at indices > 0).
5837      *
5838      * ```ts
5839      * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
5840      * ```
5841      */
5842     function getPathFromPathComponents(pathComponents) {
5843         if (pathComponents.length === 0)
5844             return "";
5845         var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
5846         return root + pathComponents.slice(1).join(ts.directorySeparator);
5847     }
5848     ts.getPathFromPathComponents = getPathFromPathComponents;
5849     //// Path Normalization
5850     /**
5851      * Normalize path separators, converting `\` into `/`.
5852      */
5853     function normalizeSlashes(path) {
5854         return path.replace(backslashRegExp, ts.directorySeparator);
5855     }
5856     ts.normalizeSlashes = normalizeSlashes;
5857     /**
5858      * Reduce an array of path components to a more simplified path by navigating any
5859      * `"."` or `".."` entries in the path.
5860      */
5861     function reducePathComponents(components) {
5862         if (!ts.some(components))
5863             return [];
5864         var reduced = [components[0]];
5865         for (var i = 1; i < components.length; i++) {
5866             var component = components[i];
5867             if (!component)
5868                 continue;
5869             if (component === ".")
5870                 continue;
5871             if (component === "..") {
5872                 if (reduced.length > 1) {
5873                     if (reduced[reduced.length - 1] !== "..") {
5874                         reduced.pop();
5875                         continue;
5876                     }
5877                 }
5878                 else if (reduced[0])
5879                     continue;
5880             }
5881             reduced.push(component);
5882         }
5883         return reduced;
5884     }
5885     ts.reducePathComponents = reducePathComponents;
5886     /**
5887      * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
5888      *
5889      * ```ts
5890      * // Non-rooted
5891      * combinePaths("path", "to", "file.ext") === "path/to/file.ext"
5892      * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
5893      * // POSIX
5894      * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
5895      * combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
5896      * // DOS
5897      * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
5898      * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
5899      * // URL
5900      * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
5901      * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
5902      * ```
5903      */
5904     function combinePaths(path) {
5905         var paths = [];
5906         for (var _i = 1; _i < arguments.length; _i++) {
5907             paths[_i - 1] = arguments[_i];
5908         }
5909         if (path)
5910             path = normalizeSlashes(path);
5911         for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
5912             var relativePath = paths_1[_a];
5913             if (!relativePath)
5914                 continue;
5915             relativePath = normalizeSlashes(relativePath);
5916             if (!path || getRootLength(relativePath) !== 0) {
5917                 path = relativePath;
5918             }
5919             else {
5920                 path = ensureTrailingDirectorySeparator(path) + relativePath;
5921             }
5922         }
5923         return path;
5924     }
5925     ts.combinePaths = combinePaths;
5926     /**
5927      * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
5928      * `.` and `..` path components are resolved. Trailing directory separators are preserved.
5929      *
5930      * ```ts
5931      * resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
5932      * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
5933      * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
5934      * ```
5935      */
5936     function resolvePath(path) {
5937         var paths = [];
5938         for (var _i = 1; _i < arguments.length; _i++) {
5939             paths[_i - 1] = arguments[_i];
5940         }
5941         return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArray([path], paths)) : normalizeSlashes(path));
5942     }
5943     ts.resolvePath = resolvePath;
5944     /**
5945      * Parse a path into an array containing a root component (at index 0) and zero or more path
5946      * components (at indices > 0). The result is normalized.
5947      * If the path is relative, the root component is `""`.
5948      * If the path is absolute, the root component includes the first path separator (`/`).
5949      *
5950      * ```ts
5951      * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
5952      * ```
5953      */
5954     function getNormalizedPathComponents(path, currentDirectory) {
5955         return reducePathComponents(getPathComponents(path, currentDirectory));
5956     }
5957     ts.getNormalizedPathComponents = getNormalizedPathComponents;
5958     function getNormalizedAbsolutePath(fileName, currentDirectory) {
5959         return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
5960     }
5961     ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
5962     function normalizePath(path) {
5963         path = normalizeSlashes(path);
5964         var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
5965         return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
5966     }
5967     ts.normalizePath = normalizePath;
5968     function getPathWithoutRoot(pathComponents) {
5969         if (pathComponents.length === 0)
5970             return "";
5971         return pathComponents.slice(1).join(ts.directorySeparator);
5972     }
5973     function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) {
5974         return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
5975     }
5976     ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot;
5977     function toPath(fileName, basePath, getCanonicalFileName) {
5978         var nonCanonicalizedPath = isRootedDiskPath(fileName)
5979             ? normalizePath(fileName)
5980             : getNormalizedAbsolutePath(fileName, basePath);
5981         return getCanonicalFileName(nonCanonicalizedPath);
5982     }
5983     ts.toPath = toPath;
5984     function normalizePathAndParts(path) {
5985         path = normalizeSlashes(path);
5986         var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
5987         if (parts.length) {
5988             var joinedParts = root + parts.join(ts.directorySeparator);
5989             return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
5990         }
5991         else {
5992             return { path: root, parts: parts };
5993         }
5994     }
5995     ts.normalizePathAndParts = normalizePathAndParts;
5996     function removeTrailingDirectorySeparator(path) {
5997         if (hasTrailingDirectorySeparator(path)) {
5998             return path.substr(0, path.length - 1);
5999         }
6000         return path;
6001     }
6002     ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
6003     function ensureTrailingDirectorySeparator(path) {
6004         if (!hasTrailingDirectorySeparator(path)) {
6005             return path + ts.directorySeparator;
6006         }
6007         return path;
6008     }
6009     ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
6010     /**
6011      * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
6012      * with `./` or `../`) so as not to be confused with an unprefixed module name.
6013      *
6014      * ```ts
6015      * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext"
6016      * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext"
6017      * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext"
6018      * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext"
6019      * ```
6020      */
6021     function ensurePathIsNonModuleName(path) {
6022         return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path;
6023     }
6024     ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
6025     function changeAnyExtension(path, ext, extensions, ignoreCase) {
6026         var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
6027         return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path;
6028     }
6029     ts.changeAnyExtension = changeAnyExtension;
6030     //// Path Comparisons
6031     // check path for these segments: '', '.'. '..'
6032     var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
6033     function comparePathsWorker(a, b, componentComparer) {
6034         if (a === b)
6035             return 0 /* EqualTo */;
6036         if (a === undefined)
6037             return -1 /* LessThan */;
6038         if (b === undefined)
6039             return 1 /* GreaterThan */;
6040         // NOTE: Performance optimization - shortcut if the root segments differ as there would be no
6041         //       need to perform path reduction.
6042         var aRoot = a.substring(0, getRootLength(a));
6043         var bRoot = b.substring(0, getRootLength(b));
6044         var result = ts.compareStringsCaseInsensitive(aRoot, bRoot);
6045         if (result !== 0 /* EqualTo */) {
6046             return result;
6047         }
6048         // NOTE: Performance optimization - shortcut if there are no relative path segments in
6049         //       the non-root portion of the path
6050         var aRest = a.substring(aRoot.length);
6051         var bRest = b.substring(bRoot.length);
6052         if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
6053             return componentComparer(aRest, bRest);
6054         }
6055         // The path contains a relative path segment. Normalize the paths and perform a slower component
6056         // by component comparison.
6057         var aComponents = reducePathComponents(getPathComponents(a));
6058         var bComponents = reducePathComponents(getPathComponents(b));
6059         var sharedLength = Math.min(aComponents.length, bComponents.length);
6060         for (var i = 1; i < sharedLength; i++) {
6061             var result_2 = componentComparer(aComponents[i], bComponents[i]);
6062             if (result_2 !== 0 /* EqualTo */) {
6063                 return result_2;
6064             }
6065         }
6066         return ts.compareValues(aComponents.length, bComponents.length);
6067     }
6068     /**
6069      * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively.
6070      */
6071     function comparePathsCaseSensitive(a, b) {
6072         return comparePathsWorker(a, b, ts.compareStringsCaseSensitive);
6073     }
6074     ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
6075     /**
6076      * Performs a case-insensitive comparison of two paths.
6077      */
6078     function comparePathsCaseInsensitive(a, b) {
6079         return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive);
6080     }
6081     ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
6082     function comparePaths(a, b, currentDirectory, ignoreCase) {
6083         if (typeof currentDirectory === "string") {
6084             a = combinePaths(currentDirectory, a);
6085             b = combinePaths(currentDirectory, b);
6086         }
6087         else if (typeof currentDirectory === "boolean") {
6088             ignoreCase = currentDirectory;
6089         }
6090         return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase));
6091     }
6092     ts.comparePaths = comparePaths;
6093     function containsPath(parent, child, currentDirectory, ignoreCase) {
6094         if (typeof currentDirectory === "string") {
6095             parent = combinePaths(currentDirectory, parent);
6096             child = combinePaths(currentDirectory, child);
6097         }
6098         else if (typeof currentDirectory === "boolean") {
6099             ignoreCase = currentDirectory;
6100         }
6101         if (parent === undefined || child === undefined)
6102             return false;
6103         if (parent === child)
6104             return true;
6105         var parentComponents = reducePathComponents(getPathComponents(parent));
6106         var childComponents = reducePathComponents(getPathComponents(child));
6107         if (childComponents.length < parentComponents.length) {
6108             return false;
6109         }
6110         var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive;
6111         for (var i = 0; i < parentComponents.length; i++) {
6112             var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer;
6113             if (!equalityComparer(parentComponents[i], childComponents[i])) {
6114                 return false;
6115             }
6116         }
6117         return true;
6118     }
6119     ts.containsPath = containsPath;
6120     /**
6121      * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
6122      * Comparison is case-sensitive between the canonical paths.
6123      *
6124      * Use `containsPath` if file names are not already reduced and absolute.
6125      */
6126     function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
6127         var canonicalFileName = getCanonicalFileName(fileName);
6128         var canonicalDirectoryName = getCanonicalFileName(directoryName);
6129         return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\");
6130     }
6131     ts.startsWithDirectory = startsWithDirectory;
6132     //// Relative Paths
6133     function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
6134         var fromComponents = reducePathComponents(getPathComponents(from));
6135         var toComponents = reducePathComponents(getPathComponents(to));
6136         var start;
6137         for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
6138             var fromComponent = getCanonicalFileName(fromComponents[start]);
6139             var toComponent = getCanonicalFileName(toComponents[start]);
6140             var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer;
6141             if (!comparer(fromComponent, toComponent))
6142                 break;
6143         }
6144         if (start === 0) {
6145             return toComponents;
6146         }
6147         var components = toComponents.slice(start);
6148         var relative = [];
6149         for (; start < fromComponents.length; start++) {
6150             relative.push("..");
6151         }
6152         return __spreadArray(__spreadArray([""], relative), components);
6153     }
6154     ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
6155     function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
6156         ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
6157         var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity;
6158         var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
6159         var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName);
6160         return getPathFromPathComponents(pathComponents);
6161     }
6162     ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
6163     function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
6164         return !isRootedDiskPath(absoluteOrRelativePath)
6165             ? absoluteOrRelativePath
6166             : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
6167     }
6168     ts.convertToRelativePath = convertToRelativePath;
6169     function getRelativePathFromFile(from, to, getCanonicalFileName) {
6170         return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
6171     }
6172     ts.getRelativePathFromFile = getRelativePathFromFile;
6173     function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
6174         var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName);
6175         var firstComponent = pathComponents[0];
6176         if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
6177             var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
6178             pathComponents[0] = prefix + firstComponent;
6179         }
6180         return getPathFromPathComponents(pathComponents);
6181     }
6182     ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
6183     function forEachAncestorDirectory(directory, callback) {
6184         while (true) {
6185             var result = callback(directory);
6186             if (result !== undefined) {
6187                 return result;
6188             }
6189             var parentPath = getDirectoryPath(directory);
6190             if (parentPath === directory) {
6191                 return undefined;
6192             }
6193             directory = parentPath;
6194         }
6195     }
6196     ts.forEachAncestorDirectory = forEachAncestorDirectory;
6197     function isNodeModulesDirectory(dirPath) {
6198         return ts.endsWith(dirPath, "/node_modules");
6199     }
6200     ts.isNodeModulesDirectory = isNodeModulesDirectory;
6201 })(ts || (ts = {}));
6202 var ts;
6203 (function (ts) {
6204     /**
6205      * djb2 hashing algorithm
6206      * http://www.cse.yorku.ca/~oz/hash.html
6207      */
6208     /* @internal */
6209     function generateDjb2Hash(data) {
6210         var acc = 5381;
6211         for (var i = 0; i < data.length; i++) {
6212             acc = ((acc << 5) + acc) + data.charCodeAt(i);
6213         }
6214         return acc.toString();
6215     }
6216     ts.generateDjb2Hash = generateDjb2Hash;
6217     /**
6218      * Set a high stack trace limit to provide more information in case of an error.
6219      * Called for command-line and server use cases.
6220      * Not called if TypeScript is used as a library.
6221      */
6222     /* @internal */
6223     function setStackTraceLimit() {
6224         if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
6225             Error.stackTraceLimit = 100;
6226         }
6227     }
6228     ts.setStackTraceLimit = setStackTraceLimit;
6229     var FileWatcherEventKind;
6230     (function (FileWatcherEventKind) {
6231         FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created";
6232         FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed";
6233         FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted";
6234     })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {}));
6235     /* @internal */
6236     var PollingInterval;
6237     (function (PollingInterval) {
6238         PollingInterval[PollingInterval["High"] = 2000] = "High";
6239         PollingInterval[PollingInterval["Medium"] = 500] = "Medium";
6240         PollingInterval[PollingInterval["Low"] = 250] = "Low";
6241     })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {}));
6242     /* @internal */
6243     ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
6244     function createPollingIntervalBasedLevels(levels) {
6245         var _a;
6246         return _a = {},
6247             _a[PollingInterval.Low] = levels.Low,
6248             _a[PollingInterval.Medium] = levels.Medium,
6249             _a[PollingInterval.High] = levels.High,
6250             _a;
6251     }
6252     var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
6253     var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
6254     /* @internal */
6255     ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels);
6256     /* @internal */
6257     function setCustomPollingValues(system) {
6258         if (!system.getEnvironmentVariable) {
6259             return;
6260         }
6261         var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval);
6262         pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize;
6263         ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds;
6264         function getLevel(envVar, level) {
6265             return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase());
6266         }
6267         function getCustomLevels(baseVariable) {
6268             var customLevels;
6269             setCustomLevel("Low");
6270             setCustomLevel("Medium");
6271             setCustomLevel("High");
6272             return customLevels;
6273             function setCustomLevel(level) {
6274                 var customLevel = getLevel(baseVariable, level);
6275                 if (customLevel) {
6276                     (customLevels || (customLevels = {}))[level] = Number(customLevel);
6277                 }
6278             }
6279         }
6280         function setCustomLevels(baseVariable, levels) {
6281             var customLevels = getCustomLevels(baseVariable);
6282             if (customLevels) {
6283                 setLevel("Low");
6284                 setLevel("Medium");
6285                 setLevel("High");
6286                 return true;
6287             }
6288             return false;
6289             function setLevel(level) {
6290                 levels[level] = customLevels[level] || levels[level];
6291             }
6292         }
6293         function getCustomPollingBasedLevels(baseVariable, defaultLevels) {
6294             var customLevels = getCustomLevels(baseVariable);
6295             return (pollingIntervalChanged || customLevels) &&
6296                 createPollingIntervalBasedLevels(customLevels ? __assign(__assign({}, defaultLevels), customLevels) : defaultLevels);
6297         }
6298     }
6299     ts.setCustomPollingValues = setCustomPollingValues;
6300     /* @internal */
6301     function createDynamicPriorityPollingWatchFile(host) {
6302         var watchedFiles = [];
6303         var changedFilesInLastPoll = [];
6304         var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low);
6305         var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium);
6306         var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High);
6307         return watchFile;
6308         function watchFile(fileName, callback, defaultPollingInterval) {
6309             var file = {
6310                 fileName: fileName,
6311                 callback: callback,
6312                 unchangedPolls: 0,
6313                 mtime: getModifiedTime(fileName)
6314             };
6315             watchedFiles.push(file);
6316             addToPollingIntervalQueue(file, defaultPollingInterval);
6317             return {
6318                 close: function () {
6319                     file.isClosed = true;
6320                     // Remove from watchedFiles
6321                     ts.unorderedRemoveItem(watchedFiles, file);
6322                     // Do not update polling interval queue since that will happen as part of polling
6323                 }
6324             };
6325         }
6326         function createPollingIntervalQueue(pollingInterval) {
6327             var queue = [];
6328             queue.pollingInterval = pollingInterval;
6329             queue.pollIndex = 0;
6330             queue.pollScheduled = false;
6331             return queue;
6332         }
6333         function pollPollingIntervalQueue(queue) {
6334             queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]);
6335             // Set the next polling index and timeout
6336             if (queue.length) {
6337                 scheduleNextPoll(queue.pollingInterval);
6338             }
6339             else {
6340                 ts.Debug.assert(queue.pollIndex === 0);
6341                 queue.pollScheduled = false;
6342             }
6343         }
6344         function pollLowPollingIntervalQueue(queue) {
6345             // Always poll complete list of changedFilesInLastPoll
6346             pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length);
6347             // Finally do the actual polling of the queue
6348             pollPollingIntervalQueue(queue);
6349             // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue
6350             // as pollPollingIntervalQueue wont schedule for next poll
6351             if (!queue.pollScheduled && changedFilesInLastPoll.length) {
6352                 scheduleNextPoll(PollingInterval.Low);
6353             }
6354         }
6355         function pollQueue(queue, pollingInterval, pollIndex, chunkSize) {
6356             // Max visit would be all elements of the queue
6357             var needsVisit = queue.length;
6358             var definedValueCopyToIndex = pollIndex;
6359             for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) {
6360                 var watchedFile = queue[pollIndex];
6361                 if (!watchedFile) {
6362                     continue;
6363                 }
6364                 else if (watchedFile.isClosed) {
6365                     queue[pollIndex] = undefined;
6366                     continue;
6367                 }
6368                 polled++;
6369                 var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName));
6370                 if (watchedFile.isClosed) {
6371                     // Closed watcher as part of callback
6372                     queue[pollIndex] = undefined;
6373                 }
6374                 else if (fileChanged) {
6375                     watchedFile.unchangedPolls = 0;
6376                     // Changed files go to changedFilesInLastPoll queue
6377                     if (queue !== changedFilesInLastPoll) {
6378                         queue[pollIndex] = undefined;
6379                         addChangedFileToLowPollingIntervalQueue(watchedFile);
6380                     }
6381                 }
6382                 else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) {
6383                     watchedFile.unchangedPolls++;
6384                 }
6385                 else if (queue === changedFilesInLastPoll) {
6386                     // Restart unchangedPollCount for unchanged file and move to low polling interval queue
6387                     watchedFile.unchangedPolls = 1;
6388                     queue[pollIndex] = undefined;
6389                     addToPollingIntervalQueue(watchedFile, PollingInterval.Low);
6390                 }
6391                 else if (pollingInterval !== PollingInterval.High) {
6392                     watchedFile.unchangedPolls++;
6393                     queue[pollIndex] = undefined;
6394                     addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High);
6395                 }
6396                 if (queue[pollIndex]) {
6397                     // Copy this file to the non hole location
6398                     if (definedValueCopyToIndex < pollIndex) {
6399                         queue[definedValueCopyToIndex] = watchedFile;
6400                         queue[pollIndex] = undefined;
6401                     }
6402                     definedValueCopyToIndex++;
6403                 }
6404             }
6405             // Return next poll index
6406             return pollIndex;
6407             function nextPollIndex() {
6408                 pollIndex++;
6409                 if (pollIndex === queue.length) {
6410                     if (definedValueCopyToIndex < pollIndex) {
6411                         // There are holes from nextDefinedValueIndex to end of queue, change queue size
6412                         queue.length = definedValueCopyToIndex;
6413                     }
6414                     pollIndex = 0;
6415                     definedValueCopyToIndex = 0;
6416                 }
6417             }
6418         }
6419         function pollingIntervalQueue(pollingInterval) {
6420             switch (pollingInterval) {
6421                 case PollingInterval.Low:
6422                     return lowPollingIntervalQueue;
6423                 case PollingInterval.Medium:
6424                     return mediumPollingIntervalQueue;
6425                 case PollingInterval.High:
6426                     return highPollingIntervalQueue;
6427             }
6428         }
6429         function addToPollingIntervalQueue(file, pollingInterval) {
6430             pollingIntervalQueue(pollingInterval).push(file);
6431             scheduleNextPollIfNotAlreadyScheduled(pollingInterval);
6432         }
6433         function addChangedFileToLowPollingIntervalQueue(file) {
6434             changedFilesInLastPoll.push(file);
6435             scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low);
6436         }
6437         function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) {
6438             if (!pollingIntervalQueue(pollingInterval).pollScheduled) {
6439                 scheduleNextPoll(pollingInterval);
6440             }
6441         }
6442         function scheduleNextPoll(pollingInterval) {
6443             pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
6444         }
6445         function getModifiedTime(fileName) {
6446             return host.getModifiedTime(fileName) || ts.missingFileModifiedTime;
6447         }
6448     }
6449     ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
6450     function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) {
6451         // One file can have multiple watchers
6452         var fileWatcherCallbacks = ts.createMultiMap();
6453         var dirWatchers = new ts.Map();
6454         var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
6455         return nonPollingWatchFile;
6456         function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) {
6457             var filePath = toCanonicalName(fileName);
6458             fileWatcherCallbacks.add(filePath, callback);
6459             var dirPath = ts.getDirectoryPath(filePath) || ".";
6460             var watcher = dirWatchers.get(dirPath) ||
6461                 createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath, fallbackOptions);
6462             watcher.referenceCount++;
6463             return {
6464                 close: function () {
6465                     if (watcher.referenceCount === 1) {
6466                         watcher.close();
6467                         dirWatchers.delete(dirPath);
6468                     }
6469                     else {
6470                         watcher.referenceCount--;
6471                     }
6472                     fileWatcherCallbacks.remove(filePath, callback);
6473                 }
6474             };
6475         }
6476         function createDirectoryWatcher(dirName, dirPath, fallbackOptions) {
6477             var watcher = fsWatch(dirName, 1 /* Directory */, function (_eventName, relativeFileName) {
6478                 // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
6479                 if (!ts.isString(relativeFileName)) {
6480                     return;
6481                 }
6482                 var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName);
6483                 // Some applications save a working file via rename operations
6484                 var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName));
6485                 if (callbacks) {
6486                     for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
6487                         var fileCallback = callbacks_1[_i];
6488                         fileCallback(fileName, FileWatcherEventKind.Changed);
6489                     }
6490                 }
6491             }, 
6492             /*recursive*/ false, PollingInterval.Medium, fallbackOptions);
6493             watcher.referenceCount = 0;
6494             dirWatchers.set(dirPath, watcher);
6495             return watcher;
6496         }
6497     }
6498     /* @internal */
6499     function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) {
6500         var cache = new ts.Map();
6501         var callbacksCache = ts.createMultiMap();
6502         var toCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
6503         return function (fileName, callback, pollingInterval, options) {
6504             var path = toCanonicalFileName(fileName);
6505             var existing = cache.get(path);
6506             if (existing) {
6507                 existing.refCount++;
6508             }
6509             else {
6510                 cache.set(path, {
6511                     watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options),
6512                     refCount: 1
6513                 });
6514             }
6515             callbacksCache.add(path, callback);
6516             return {
6517                 close: function () {
6518                     var watcher = ts.Debug.checkDefined(cache.get(path));
6519                     callbacksCache.remove(path, callback);
6520                     watcher.refCount--;
6521                     if (watcher.refCount)
6522                         return;
6523                     cache.delete(path);
6524                     ts.closeFileWatcherOf(watcher);
6525                 }
6526             };
6527         };
6528     }
6529     ts.createSingleFileWatcherPerName = createSingleFileWatcherPerName;
6530     /**
6531      * Returns true if file status changed
6532      */
6533     /*@internal*/
6534     function onWatchedFileStat(watchedFile, modifiedTime) {
6535         var oldTime = watchedFile.mtime.getTime();
6536         var newTime = modifiedTime.getTime();
6537         if (oldTime !== newTime) {
6538             watchedFile.mtime = modifiedTime;
6539             watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
6540             return true;
6541         }
6542         return false;
6543     }
6544     ts.onWatchedFileStat = onWatchedFileStat;
6545     /*@internal*/
6546     function getFileWatcherEventKind(oldTime, newTime) {
6547         return oldTime === 0
6548             ? FileWatcherEventKind.Created
6549             : newTime === 0
6550                 ? FileWatcherEventKind.Deleted
6551                 : FileWatcherEventKind.Changed;
6552     }
6553     ts.getFileWatcherEventKind = getFileWatcherEventKind;
6554     /*@internal*/
6555     ts.ignoredPaths = ["/node_modules/.", "/.git", "/.#"];
6556     /*@internal*/
6557     ts.sysLog = ts.noop; // eslint-disable-line prefer-const
6558     /*@internal*/
6559     function setSysLog(logger) {
6560         ts.sysLog = logger;
6561     }
6562     ts.setSysLog = setSysLog;
6563     /**
6564      * Watch the directory recursively using host provided method to watch child directories
6565      * that means if this is recursive watcher, watch the children directories as well
6566      * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile)
6567      */
6568     /*@internal*/
6569     function createDirectoryWatcherSupportingRecursive(_a) {
6570         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;
6571         var cache = new ts.Map();
6572         var callbackCache = ts.createMultiMap();
6573         var cacheToUpdateChildWatches = new ts.Map();
6574         var timerToUpdateChildWatches;
6575         var filePathComparer = ts.getStringComparer(!useCaseSensitiveFileNames);
6576         var toCanonicalFilePath = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
6577         return function (dirName, callback, recursive, options) { return recursive ?
6578             createDirectoryWatcher(dirName, options, callback) :
6579             watchDirectory(dirName, callback, recursive, options); };
6580         /**
6581          * Create the directory watcher for the dirPath.
6582          */
6583         function createDirectoryWatcher(dirName, options, callback) {
6584             var dirPath = toCanonicalFilePath(dirName);
6585             var directoryWatcher = cache.get(dirPath);
6586             if (directoryWatcher) {
6587                 directoryWatcher.refCount++;
6588             }
6589             else {
6590                 directoryWatcher = {
6591                     watcher: watchDirectory(dirName, function (fileName) {
6592                         if (isIgnoredPath(fileName, options))
6593                             return;
6594                         if (options === null || options === void 0 ? void 0 : options.synchronousWatchDirectory) {
6595                             // Call the actual callback
6596                             invokeCallbacks(dirPath, fileName);
6597                             // Iterate through existing children and update the watches if needed
6598                             updateChildWatches(dirName, dirPath, options);
6599                         }
6600                         else {
6601                             nonSyncUpdateChildWatches(dirName, dirPath, fileName, options);
6602                         }
6603                     }, /*recursive*/ false, options),
6604                     refCount: 1,
6605                     childWatches: ts.emptyArray
6606                 };
6607                 cache.set(dirPath, directoryWatcher);
6608                 updateChildWatches(dirName, dirPath, options);
6609             }
6610             var callbackToAdd = callback && { dirName: dirName, callback: callback };
6611             if (callbackToAdd) {
6612                 callbackCache.add(dirPath, callbackToAdd);
6613             }
6614             return {
6615                 dirName: dirName,
6616                 close: function () {
6617                     var directoryWatcher = ts.Debug.checkDefined(cache.get(dirPath));
6618                     if (callbackToAdd)
6619                         callbackCache.remove(dirPath, callbackToAdd);
6620                     directoryWatcher.refCount--;
6621                     if (directoryWatcher.refCount)
6622                         return;
6623                     cache.delete(dirPath);
6624                     ts.closeFileWatcherOf(directoryWatcher);
6625                     directoryWatcher.childWatches.forEach(ts.closeFileWatcher);
6626                 }
6627             };
6628         }
6629         function invokeCallbacks(dirPath, fileNameOrInvokeMap, fileNames) {
6630             var fileName;
6631             var invokeMap;
6632             if (ts.isString(fileNameOrInvokeMap)) {
6633                 fileName = fileNameOrInvokeMap;
6634             }
6635             else {
6636                 invokeMap = fileNameOrInvokeMap;
6637             }
6638             // Call the actual callback
6639             callbackCache.forEach(function (callbacks, rootDirName) {
6640                 var _a;
6641                 if (invokeMap && invokeMap.get(rootDirName) === true)
6642                     return;
6643                 if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
6644                     if (invokeMap) {
6645                         if (fileNames) {
6646                             var existing = invokeMap.get(rootDirName);
6647                             if (existing) {
6648                                 (_a = existing).push.apply(_a, fileNames);
6649                             }
6650                             else {
6651                                 invokeMap.set(rootDirName, fileNames.slice());
6652                             }
6653                         }
6654                         else {
6655                             invokeMap.set(rootDirName, true);
6656                         }
6657                     }
6658                     else {
6659                         callbacks.forEach(function (_a) {
6660                             var callback = _a.callback;
6661                             return callback(fileName);
6662                         });
6663                     }
6664                 }
6665             });
6666         }
6667         function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) {
6668             // Iterate through existing children and update the watches if needed
6669             var parentWatcher = cache.get(dirPath);
6670             if (parentWatcher && directoryExists(dirName)) {
6671                 // Schedule the update and postpone invoke for callbacks
6672                 scheduleUpdateChildWatches(dirName, dirPath, fileName, options);
6673                 return;
6674             }
6675             // Call the actual callbacks and remove child watches
6676             invokeCallbacks(dirPath, fileName);
6677             removeChildWatches(parentWatcher);
6678         }
6679         function scheduleUpdateChildWatches(dirName, dirPath, fileName, options) {
6680             var existing = cacheToUpdateChildWatches.get(dirPath);
6681             if (existing) {
6682                 existing.fileNames.push(fileName);
6683             }
6684             else {
6685                 cacheToUpdateChildWatches.set(dirPath, { dirName: dirName, options: options, fileNames: [fileName] });
6686             }
6687             if (timerToUpdateChildWatches) {
6688                 clearTimeout(timerToUpdateChildWatches);
6689                 timerToUpdateChildWatches = undefined;
6690             }
6691             timerToUpdateChildWatches = setTimeout(onTimerToUpdateChildWatches, 1000);
6692         }
6693         function onTimerToUpdateChildWatches() {
6694             timerToUpdateChildWatches = undefined;
6695             ts.sysLog("sysLog:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size);
6696             var start = ts.timestamp();
6697             var invokeMap = new ts.Map();
6698             while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) {
6699                 var result = cacheToUpdateChildWatches.entries().next();
6700                 ts.Debug.assert(!result.done);
6701                 var _a = result.value, dirPath = _a[0], _b = _a[1], dirName = _b.dirName, options = _b.options, fileNames = _b.fileNames;
6702                 cacheToUpdateChildWatches.delete(dirPath);
6703                 // Because the child refresh is fresh, we would need to invalidate whole root directory being watched
6704                 // to ensure that all the changes are reflected at this time
6705                 var hasChanges = updateChildWatches(dirName, dirPath, options);
6706                 invokeCallbacks(dirPath, invokeMap, hasChanges ? undefined : fileNames);
6707             }
6708             ts.sysLog("sysLog:: invokingWatchers:: Elapsed:: " + (ts.timestamp() - start) + "ms:: " + cacheToUpdateChildWatches.size);
6709             callbackCache.forEach(function (callbacks, rootDirName) {
6710                 var existing = invokeMap.get(rootDirName);
6711                 if (existing) {
6712                     callbacks.forEach(function (_a) {
6713                         var callback = _a.callback, dirName = _a.dirName;
6714                         if (ts.isArray(existing)) {
6715                             existing.forEach(callback);
6716                         }
6717                         else {
6718                             callback(dirName);
6719                         }
6720                     });
6721                 }
6722             });
6723             var elapsed = ts.timestamp() - start;
6724             ts.sysLog("sysLog:: Elapsed:: " + elapsed + "ms:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size + " " + timerToUpdateChildWatches);
6725         }
6726         function removeChildWatches(parentWatcher) {
6727             if (!parentWatcher)
6728                 return;
6729             var existingChildWatches = parentWatcher.childWatches;
6730             parentWatcher.childWatches = ts.emptyArray;
6731             for (var _i = 0, existingChildWatches_1 = existingChildWatches; _i < existingChildWatches_1.length; _i++) {
6732                 var childWatcher = existingChildWatches_1[_i];
6733                 childWatcher.close();
6734                 removeChildWatches(cache.get(toCanonicalFilePath(childWatcher.dirName)));
6735             }
6736         }
6737         function updateChildWatches(parentDir, parentDirPath, options) {
6738             // Iterate through existing children and update the watches if needed
6739             var parentWatcher = cache.get(parentDirPath);
6740             if (!parentWatcher)
6741                 return false;
6742             var newChildWatches;
6743             var hasChanges = ts.enumerateInsertsAndDeletes(directoryExists(parentDir) ? ts.mapDefined(getAccessibleSortedChildDirectories(parentDir), function (child) {
6744                 var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
6745                 // Filter our the symbolic link directories since those arent included in recursive watch
6746                 // which is same behaviour when recursive: true is passed to fs.watch
6747                 return !isIgnoredPath(childFullName, options) && filePathComparer(childFullName, ts.normalizePath(realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
6748             }) : ts.emptyArray, parentWatcher.childWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
6749             parentWatcher.childWatches = newChildWatches || ts.emptyArray;
6750             return hasChanges;
6751             /**
6752              * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list
6753              */
6754             function createAndAddChildDirectoryWatcher(childName) {
6755                 var result = createDirectoryWatcher(childName, options);
6756                 addChildDirectoryWatcher(result);
6757             }
6758             /**
6759              * Add child directory watcher to the new ChildDirectoryWatcher list
6760              */
6761             function addChildDirectoryWatcher(childWatcher) {
6762                 (newChildWatches || (newChildWatches = [])).push(childWatcher);
6763             }
6764         }
6765         function isIgnoredPath(path, options) {
6766             return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); }) ||
6767                 isIgnoredByWatchOptions(path, options, useCaseSensitiveFileNames, getCurrentDirectory);
6768         }
6769         function isInPath(path, searchPath) {
6770             if (ts.stringContains(path, searchPath))
6771                 return true;
6772             if (useCaseSensitiveFileNames)
6773                 return false;
6774             return ts.stringContains(toCanonicalFilePath(path), searchPath);
6775         }
6776     }
6777     ts.createDirectoryWatcherSupportingRecursive = createDirectoryWatcherSupportingRecursive;
6778     /*@internal*/
6779     var FileSystemEntryKind;
6780     (function (FileSystemEntryKind) {
6781         FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
6782         FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
6783     })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {}));
6784     /*@internal*/
6785     function createFileWatcherCallback(callback) {
6786         return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); };
6787     }
6788     ts.createFileWatcherCallback = createFileWatcherCallback;
6789     function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) {
6790         return function (eventName) {
6791             if (eventName === "rename") {
6792                 callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
6793             }
6794             else {
6795                 // Change
6796                 callback(fileName, FileWatcherEventKind.Changed);
6797             }
6798         };
6799     }
6800     function isIgnoredByWatchOptions(pathToCheck, options, useCaseSensitiveFileNames, getCurrentDirectory) {
6801         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()) ||
6802             ts.matchesExclude(pathToCheck, options === null || options === void 0 ? void 0 : options.excludeDirectories, useCaseSensitiveFileNames, getCurrentDirectory()));
6803     }
6804     function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory) {
6805         return function (eventName, relativeFileName) {
6806             // In watchDirectory we only care about adding and removing files (when event name is
6807             // "rename"); changes made within files are handled by corresponding fileWatchers (when
6808             // event name is "change")
6809             if (eventName === "rename") {
6810                 // When deleting a file, the passed baseFileName is null
6811                 var fileName = !relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName));
6812                 if (!relativeFileName || !isIgnoredByWatchOptions(fileName, options, useCaseSensitiveFileNames, getCurrentDirectory)) {
6813                     callback(fileName);
6814                 }
6815             }
6816         };
6817     }
6818     /*@internal*/
6819     function createSystemWatchFunctions(_a) {
6820         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;
6821         var dynamicPollingWatchFile;
6822         var nonPollingWatchFile;
6823         var hostRecursiveDirectoryWatcher;
6824         return {
6825             watchFile: watchFile,
6826             watchDirectory: watchDirectory
6827         };
6828         function watchFile(fileName, callback, pollingInterval, options) {
6829             options = updateOptionsForWatchFile(options, useNonPollingWatchers);
6830             var watchFileKind = ts.Debug.checkDefined(options.watchFile);
6831             switch (watchFileKind) {
6832                 case ts.WatchFileKind.FixedPollingInterval:
6833                     return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined);
6834                 case ts.WatchFileKind.PriorityPollingInterval:
6835                     return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined);
6836                 case ts.WatchFileKind.DynamicPriorityPolling:
6837                     return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined);
6838                 case ts.WatchFileKind.UseFsEvents:
6839                     return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), 
6840                     /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options));
6841                 case ts.WatchFileKind.UseFsEventsOnParentDirectory:
6842                     if (!nonPollingWatchFile) {
6843                         nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames);
6844                     }
6845                     return nonPollingWatchFile(fileName, callback, pollingInterval, ts.getFallbackOptions(options));
6846                 default:
6847                     ts.Debug.assertNever(watchFileKind);
6848             }
6849         }
6850         function ensureDynamicPollingWatchFile() {
6851             return dynamicPollingWatchFile ||
6852                 (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }));
6853         }
6854         function updateOptionsForWatchFile(options, useNonPollingWatchers) {
6855             if (options && options.watchFile !== undefined)
6856                 return options;
6857             switch (tscWatchFile) {
6858                 case "PriorityPollingInterval":
6859                     // Use polling interval based on priority when create watch using host.watchFile
6860                     return { watchFile: ts.WatchFileKind.PriorityPollingInterval };
6861                 case "DynamicPriorityPolling":
6862                     // Use polling interval but change the interval depending on file changes and their default polling interval
6863                     return { watchFile: ts.WatchFileKind.DynamicPriorityPolling };
6864                 case "UseFsEvents":
6865                     // Use notifications from FS to watch with falling back to fs.watchFile
6866                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.PriorityInterval, options);
6867                 case "UseFsEventsWithFallbackDynamicPolling":
6868                     // Use notifications from FS to watch with falling back to dynamic watch file
6869                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.DynamicPriority, options);
6870                 case "UseFsEventsOnParentDirectory":
6871                     useNonPollingWatchers = true;
6872                 // fall through
6873                 default:
6874                     return useNonPollingWatchers ?
6875                         // Use notifications from FS to watch with falling back to fs.watchFile
6876                         generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) :
6877                         // Default to do not use fixed polling interval
6878                         { watchFile: ts.WatchFileKind.FixedPollingInterval };
6879             }
6880         }
6881         function generateWatchFileOptions(watchFile, fallbackPolling, options) {
6882             var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
6883             return {
6884                 watchFile: watchFile,
6885                 fallbackPolling: defaultFallbackPolling === undefined ?
6886                     fallbackPolling :
6887                     defaultFallbackPolling
6888             };
6889         }
6890         function watchDirectory(directoryName, callback, recursive, options) {
6891             if (fsSupportsRecursiveFsWatch) {
6892                 return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
6893             }
6894             if (!hostRecursiveDirectoryWatcher) {
6895                 hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({
6896                     useCaseSensitiveFileNames: useCaseSensitiveFileNames,
6897                     getCurrentDirectory: getCurrentDirectory,
6898                     directoryExists: directoryExists,
6899                     getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories,
6900                     watchDirectory: nonRecursiveWatchDirectory,
6901                     realpath: realpath,
6902                     setTimeout: setTimeout,
6903                     clearTimeout: clearTimeout
6904                 });
6905             }
6906             return hostRecursiveDirectoryWatcher(directoryName, callback, recursive, options);
6907         }
6908         function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) {
6909             ts.Debug.assert(!recursive);
6910             var watchDirectoryOptions = updateOptionsForWatchDirectory(options);
6911             var watchDirectoryKind = ts.Debug.checkDefined(watchDirectoryOptions.watchDirectory);
6912             switch (watchDirectoryKind) {
6913                 case ts.WatchDirectoryKind.FixedPollingInterval:
6914                     return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
6915                     /*options*/ undefined);
6916                 case ts.WatchDirectoryKind.DynamicPriorityPolling:
6917                     return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
6918                     /*options*/ undefined);
6919                 case ts.WatchDirectoryKind.UseFsEvents:
6920                     return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback, options, useCaseSensitiveFileNames, getCurrentDirectory), recursive, PollingInterval.Medium, ts.getFallbackOptions(watchDirectoryOptions));
6921                 default:
6922                     ts.Debug.assertNever(watchDirectoryKind);
6923             }
6924         }
6925         function updateOptionsForWatchDirectory(options) {
6926             if (options && options.watchDirectory !== undefined)
6927                 return options;
6928             switch (tscWatchDirectory) {
6929                 case "RecursiveDirectoryUsingFsWatchFile":
6930                     // Use polling interval based on priority when create watch using host.watchFile
6931                     return { watchDirectory: ts.WatchDirectoryKind.FixedPollingInterval };
6932                 case "RecursiveDirectoryUsingDynamicPriorityPolling":
6933                     // Use polling interval but change the interval depending on file changes and their default polling interval
6934                     return { watchDirectory: ts.WatchDirectoryKind.DynamicPriorityPolling };
6935                 default:
6936                     var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
6937                     return {
6938                         watchDirectory: ts.WatchDirectoryKind.UseFsEvents,
6939                         fallbackPolling: defaultFallbackPolling !== undefined ?
6940                             defaultFallbackPolling :
6941                             undefined
6942                     };
6943             }
6944         }
6945     }
6946     ts.createSystemWatchFunctions = createSystemWatchFunctions;
6947     /**
6948      * patch writefile to create folder before writing the file
6949      */
6950     /*@internal*/
6951     function patchWriteFileEnsuringDirectory(sys) {
6952         // patch writefile to create folder before writing the file
6953         var originalWriteFile = sys.writeFile;
6954         sys.writeFile = function (path, data, writeBom) {
6955             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); });
6956         };
6957     }
6958     ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory;
6959     function getNodeMajorVersion() {
6960         if (typeof process === "undefined") {
6961             return undefined;
6962         }
6963         var version = process.version;
6964         if (!version) {
6965             return undefined;
6966         }
6967         var dot = version.indexOf(".");
6968         if (dot === -1) {
6969             return undefined;
6970         }
6971         return parseInt(version.substring(1, dot));
6972     }
6973     ts.getNodeMajorVersion = getNodeMajorVersion;
6974     // TODO: GH#18217 this is used as if it's certainly defined in many places.
6975     // eslint-disable-next-line prefer-const
6976     ts.sys = (function () {
6977         // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual
6978         // byte order mark from the specified encoding. Using any other byte order mark does
6979         // not actually work.
6980         var byteOrderMarkIndicator = "\uFEFF";
6981         function getNodeSystem() {
6982             var _a;
6983             var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/;
6984             var _fs = require("fs");
6985             var _path = require("path");
6986             var _os = require("os");
6987             // crypto can be absent on reduced node installations
6988             var _crypto;
6989             try {
6990                 _crypto = require("crypto");
6991             }
6992             catch (_b) {
6993                 _crypto = undefined;
6994             }
6995             var activeSession;
6996             var profilePath = "./profile.cpuprofile";
6997             var realpathSync = (_a = _fs.realpathSync.native) !== null && _a !== void 0 ? _a : _fs.realpathSync;
6998             var Buffer = require("buffer").Buffer;
6999             var nodeVersion = getNodeMajorVersion();
7000             var isNode4OrLater = nodeVersion >= 4;
7001             var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin";
7002             var platform = _os.platform();
7003             var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
7004             var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
7005             var getCurrentDirectory = ts.memoize(function () { return process.cwd(); });
7006             var _c = createSystemWatchFunctions({
7007                 pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames),
7008                 getModifiedTime: getModifiedTime,
7009                 setTimeout: setTimeout,
7010                 clearTimeout: clearTimeout,
7011                 fsWatch: fsWatch,
7012                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
7013                 getCurrentDirectory: getCurrentDirectory,
7014                 fileExists: fileExists,
7015                 // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
7016                 // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
7017                 fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch,
7018                 directoryExists: directoryExists,
7019                 getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; },
7020                 realpath: realpath,
7021                 tscWatchFile: process.env.TSC_WATCHFILE,
7022                 useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER,
7023                 tscWatchDirectory: process.env.TSC_WATCHDIRECTORY,
7024             }), watchFile = _c.watchFile, watchDirectory = _c.watchDirectory;
7025             var nodeSystem = {
7026                 args: process.argv.slice(2),
7027                 newLine: _os.EOL,
7028                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
7029                 write: function (s) {
7030                     process.stdout.write(s);
7031                 },
7032                 writeOutputIsTTY: function () {
7033                     return process.stdout.isTTY;
7034                 },
7035                 readFile: readFile,
7036                 writeFile: writeFile,
7037                 watchFile: watchFile,
7038                 watchDirectory: watchDirectory,
7039                 resolvePath: function (path) { return _path.resolve(path); },
7040                 fileExists: fileExists,
7041                 directoryExists: directoryExists,
7042                 createDirectory: function (directoryName) {
7043                     if (!nodeSystem.directoryExists(directoryName)) {
7044                         // Wrapped in a try-catch to prevent crashing if we are in a race
7045                         // with another copy of ourselves to create the same directory
7046                         try {
7047                             _fs.mkdirSync(directoryName);
7048                         }
7049                         catch (e) {
7050                             if (e.code !== "EEXIST") {
7051                                 // Failed for some other reason (access denied?); still throw
7052                                 throw e;
7053                             }
7054                         }
7055                     }
7056                 },
7057                 getExecutingFilePath: function () {
7058                     return __filename;
7059                 },
7060                 getCurrentDirectory: getCurrentDirectory,
7061                 getDirectories: getDirectories,
7062                 getEnvironmentVariable: function (name) {
7063                     return process.env[name] || "";
7064                 },
7065                 readDirectory: readDirectory,
7066                 getModifiedTime: getModifiedTime,
7067                 setModifiedTime: setModifiedTime,
7068                 deleteFile: deleteFile,
7069                 createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
7070                 createSHA256Hash: _crypto ? createSHA256Hash : undefined,
7071                 getMemoryUsage: function () {
7072                     if (global.gc) {
7073                         global.gc();
7074                     }
7075                     return process.memoryUsage().heapUsed;
7076                 },
7077                 getFileSize: function (path) {
7078                     try {
7079                         var stat = statSync(path);
7080                         if (stat === null || stat === void 0 ? void 0 : stat.isFile()) {
7081                             return stat.size;
7082                         }
7083                     }
7084                     catch ( /*ignore*/_a) { /*ignore*/ }
7085                     return 0;
7086                 },
7087                 exit: function (exitCode) {
7088                     disableCPUProfiler(function () { return process.exit(exitCode); });
7089                 },
7090                 enableCPUProfiler: enableCPUProfiler,
7091                 disableCPUProfiler: disableCPUProfiler,
7092                 cpuProfilingEnabled: function () { return !!activeSession || ts.contains(process.execArgv, "--cpu-prof") || ts.contains(process.execArgv, "--prof"); },
7093                 realpath: realpath,
7094                 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); }),
7095                 tryEnableSourceMapsForHost: function () {
7096                     try {
7097                         require("source-map-support").install();
7098                     }
7099                     catch (_a) {
7100                         // Could not enable source maps.
7101                     }
7102                 },
7103                 setTimeout: setTimeout,
7104                 clearTimeout: clearTimeout,
7105                 clearScreen: function () {
7106                     process.stdout.write("\x1Bc");
7107                 },
7108                 setBlocking: function () {
7109                     if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) {
7110                         process.stdout._handle.setBlocking(true);
7111                     }
7112                 },
7113                 bufferFrom: bufferFrom,
7114                 base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); },
7115                 base64encode: function (input) { return bufferFrom(input).toString("base64"); },
7116                 require: function (baseDir, moduleName) {
7117                     try {
7118                         var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem);
7119                         return { module: require(modulePath), modulePath: modulePath, error: undefined };
7120                     }
7121                     catch (error) {
7122                         return { module: undefined, modulePath: undefined, error: error };
7123                     }
7124                 }
7125             };
7126             return nodeSystem;
7127             /**
7128              * `throwIfNoEntry` was added so recently that it's not in the node types.
7129              * This helper encapsulates the mitigating usage of `any`.
7130              * See https://github.com/nodejs/node/pull/33716
7131              */
7132             function statSync(path) {
7133                 // throwIfNoEntry will be ignored by older versions of node
7134                 return _fs.statSync(path, { throwIfNoEntry: false });
7135             }
7136             /**
7137              * Uses the builtin inspector APIs to capture a CPU profile
7138              * See https://nodejs.org/api/inspector.html#inspector_example_usage for details
7139              */
7140             function enableCPUProfiler(path, cb) {
7141                 if (activeSession) {
7142                     cb();
7143                     return false;
7144                 }
7145                 var inspector = require("inspector");
7146                 if (!inspector || !inspector.Session) {
7147                     cb();
7148                     return false;
7149                 }
7150                 var session = new inspector.Session();
7151                 session.connect();
7152                 session.post("Profiler.enable", function () {
7153                     session.post("Profiler.start", function () {
7154                         activeSession = session;
7155                         profilePath = path;
7156                         cb();
7157                     });
7158                 });
7159                 return true;
7160             }
7161             /**
7162              * Strips non-TS paths from the profile, so users with private projects shouldn't
7163              * need to worry about leaking paths by submitting a cpu profile to us
7164              */
7165             function cleanupPaths(profile) {
7166                 var externalFileCounter = 0;
7167                 var remappedPaths = new ts.Map();
7168                 var normalizedDir = ts.normalizeSlashes(__dirname);
7169                 // Windows rooted dir names need an extra `/` prepended to be valid file:/// urls
7170                 var fileUrlRoot = "file://" + (ts.getRootLength(normalizedDir) === 1 ? "" : "/") + normalizedDir;
7171                 for (var _i = 0, _a = profile.nodes; _i < _a.length; _i++) {
7172                     var node = _a[_i];
7173                     if (node.callFrame.url) {
7174                         var url = ts.normalizeSlashes(node.callFrame.url);
7175                         if (ts.containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) {
7176                             node.callFrame.url = ts.getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, ts.createGetCanonicalFileName(useCaseSensitiveFileNames), /*isAbsolutePathAnUrl*/ true);
7177                         }
7178                         else if (!nativePattern.test(url)) {
7179                             node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, "external" + externalFileCounter + ".js")).get(url);
7180                             externalFileCounter++;
7181                         }
7182                     }
7183                 }
7184                 return profile;
7185             }
7186             function disableCPUProfiler(cb) {
7187                 if (activeSession && activeSession !== "stopping") {
7188                     var s_1 = activeSession;
7189                     activeSession.post("Profiler.stop", function (err, _a) {
7190                         var _b;
7191                         var profile = _a.profile;
7192                         if (!err) {
7193                             try {
7194                                 if ((_b = statSync(profilePath)) === null || _b === void 0 ? void 0 : _b.isDirectory()) {
7195                                     profilePath = _path.join(profilePath, (new Date()).toISOString().replace(/:/g, "-") + "+P" + process.pid + ".cpuprofile");
7196                                 }
7197                             }
7198                             catch (_c) {
7199                                 // do nothing and ignore fallible fs operation
7200                             }
7201                             try {
7202                                 _fs.mkdirSync(_path.dirname(profilePath), { recursive: true });
7203                             }
7204                             catch (_d) {
7205                                 // do nothing and ignore fallible fs operation
7206                             }
7207                             _fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile)));
7208                         }
7209                         activeSession = undefined;
7210                         s_1.disconnect();
7211                         cb();
7212                     });
7213                     activeSession = "stopping";
7214                     return true;
7215                 }
7216                 else {
7217                     cb();
7218                     return false;
7219                 }
7220             }
7221             function bufferFrom(input, encoding) {
7222                 // See https://github.com/Microsoft/TypeScript/issues/25652
7223                 return Buffer.from && Buffer.from !== Int8Array.from
7224                     ? Buffer.from(input, encoding)
7225                     : new Buffer(input, encoding);
7226             }
7227             function isFileSystemCaseSensitive() {
7228                 // win32\win64 are case insensitive platforms
7229                 if (platform === "win32" || platform === "win64") {
7230                     return false;
7231                 }
7232                 // If this file exists under a different case, we must be case-insensitve.
7233                 return !fileExists(swapCase(__filename));
7234             }
7235             /** Convert all lowercase chars to uppercase, and vice-versa */
7236             function swapCase(s) {
7237                 return s.replace(/\w/g, function (ch) {
7238                     var up = ch.toUpperCase();
7239                     return ch === up ? ch.toLowerCase() : up;
7240                 });
7241             }
7242             function fsWatchFileWorker(fileName, callback, pollingInterval) {
7243                 _fs.watchFile(fileName, { persistent: true, interval: pollingInterval }, fileChanged);
7244                 var eventKind;
7245                 return {
7246                     close: function () { return _fs.unwatchFile(fileName, fileChanged); }
7247                 };
7248                 function fileChanged(curr, prev) {
7249                     // 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)
7250                     // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation
7251                     var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted;
7252                     if (+curr.mtime === 0) {
7253                         if (isPreviouslyDeleted) {
7254                             // Already deleted file, no need to callback again
7255                             return;
7256                         }
7257                         eventKind = FileWatcherEventKind.Deleted;
7258                     }
7259                     else if (isPreviouslyDeleted) {
7260                         eventKind = FileWatcherEventKind.Created;
7261                     }
7262                     // If there is no change in modified time, ignore the event
7263                     else if (+curr.mtime === +prev.mtime) {
7264                         return;
7265                     }
7266                     else {
7267                         // File changed
7268                         eventKind = FileWatcherEventKind.Changed;
7269                     }
7270                     callback(fileName, eventKind);
7271                 }
7272             }
7273             function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) {
7274                 var options;
7275                 var lastDirectoryPartWithDirectorySeparator;
7276                 var lastDirectoryPart;
7277                 if (isLinuxOrMacOs) {
7278                     lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator));
7279                     lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length);
7280                 }
7281                 /** Watcher for the file system entry depending on whether it is missing or present */
7282                 var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ?
7283                     watchMissingFileSystemEntry() :
7284                     watchPresentFileSystemEntry();
7285                 return {
7286                     close: function () {
7287                         // Close the watcher (either existing file system entry watcher or missing file system entry watcher)
7288                         watcher.close();
7289                         watcher = undefined;
7290                     }
7291                 };
7292                 /**
7293                  * Invoke the callback with rename and update the watcher if not closed
7294                  * @param createWatcher
7295                  */
7296                 function invokeCallbackAndUpdateWatcher(createWatcher) {
7297                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing watcher to " + (createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing") + "FileSystemEntryWatcher");
7298                     // Call the callback for current directory
7299                     callback("rename", "");
7300                     // If watcher is not closed, update it
7301                     if (watcher) {
7302                         watcher.close();
7303                         watcher = createWatcher();
7304                     }
7305                 }
7306                 /**
7307                  * Watch the file or directory that is currently present
7308                  * and when the watched file or directory is deleted, switch to missing file system entry watcher
7309                  */
7310                 function watchPresentFileSystemEntry() {
7311                     // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
7312                     // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
7313                     if (options === undefined) {
7314                         if (fsSupportsRecursiveFsWatch) {
7315                             options = { persistent: true, recursive: !!recursive };
7316                         }
7317                         else {
7318                             options = { persistent: true };
7319                         }
7320                     }
7321                     try {
7322                         var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ?
7323                             callbackChangingToMissingFileSystemEntry :
7324                             callback);
7325                         // Watch the missing file or directory or error
7326                         presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); });
7327                         return presentWatcher;
7328                     }
7329                     catch (e) {
7330                         // Catch the exception and use polling instead
7331                         // 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
7332                         // so instead of throwing error, use fs.watchFile
7333                         return watchPresentFileSystemEntryWithFsWatchFile();
7334                     }
7335                 }
7336                 function callbackChangingToMissingFileSystemEntry(event, relativeName) {
7337                     // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations
7338                     // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path
7339                     return event === "rename" &&
7340                         (!relativeName ||
7341                             relativeName === lastDirectoryPart ||
7342                             (relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) !== -1 && relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length)) &&
7343                         !fileSystemEntryExists(fileOrDirectory, entryKind) ?
7344                         invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) :
7345                         callback(event, relativeName);
7346                 }
7347                 /**
7348                  * Watch the file or directory using fs.watchFile since fs.watch threw exception
7349                  * 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
7350                  */
7351                 function watchPresentFileSystemEntryWithFsWatchFile() {
7352                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing to fsWatchFile");
7353                     return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions);
7354                 }
7355                 /**
7356                  * Watch the file or directory that is missing
7357                  * and switch to existing file or directory when the missing filesystem entry is created
7358                  */
7359                 function watchMissingFileSystemEntry() {
7360                     return watchFile(fileOrDirectory, function (_fileName, eventKind) {
7361                         if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) {
7362                             // Call the callback for current file or directory
7363                             // For now it could be callback for the inner directory creation,
7364                             // but just return current directory, better than current no-op
7365                             invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry);
7366                         }
7367                     }, fallbackPollingInterval, fallbackOptions);
7368                 }
7369             }
7370             function readFileWorker(fileName, _encoding) {
7371                 var buffer;
7372                 try {
7373                     buffer = _fs.readFileSync(fileName);
7374                 }
7375                 catch (e) {
7376                     return undefined;
7377                 }
7378                 var len = buffer.length;
7379                 if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
7380                     // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
7381                     // flip all byte pairs and treat as little endian.
7382                     len &= ~1; // Round down to a multiple of 2
7383                     for (var i = 0; i < len; i += 2) {
7384                         var temp = buffer[i];
7385                         buffer[i] = buffer[i + 1];
7386                         buffer[i + 1] = temp;
7387                     }
7388                     return buffer.toString("utf16le", 2);
7389                 }
7390                 if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
7391                     // Little endian UTF-16 byte order mark detected
7392                     return buffer.toString("utf16le", 2);
7393                 }
7394                 if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
7395                     // UTF-8 byte order mark detected
7396                     return buffer.toString("utf8", 3);
7397                 }
7398                 // Default is UTF-8 with no byte order mark
7399                 return buffer.toString("utf8");
7400             }
7401             function readFile(fileName, _encoding) {
7402                 ts.perfLogger.logStartReadFile(fileName);
7403                 var file = readFileWorker(fileName, _encoding);
7404                 ts.perfLogger.logStopReadFile();
7405                 return file;
7406             }
7407             function writeFile(fileName, data, writeByteOrderMark) {
7408                 ts.perfLogger.logEvent("WriteFile: " + fileName);
7409                 // If a BOM is required, emit one
7410                 if (writeByteOrderMark) {
7411                     data = byteOrderMarkIndicator + data;
7412                 }
7413                 var fd;
7414                 try {
7415                     fd = _fs.openSync(fileName, "w");
7416                     _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
7417                 }
7418                 finally {
7419                     if (fd !== undefined) {
7420                         _fs.closeSync(fd);
7421                     }
7422                 }
7423             }
7424             function getAccessibleFileSystemEntries(path) {
7425                 ts.perfLogger.logEvent("ReadDir: " + (path || "."));
7426                 try {
7427                     var entries = _fs.readdirSync(path || ".", { withFileTypes: true });
7428                     var files = [];
7429                     var directories = [];
7430                     for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
7431                         var dirent = entries_1[_i];
7432                         // withFileTypes is not supported before Node 10.10.
7433                         var entry = typeof dirent === "string" ? dirent : dirent.name;
7434                         // This is necessary because on some file system node fails to exclude
7435                         // "." and "..". See https://github.com/nodejs/node/issues/4002
7436                         if (entry === "." || entry === "..") {
7437                             continue;
7438                         }
7439                         var stat = void 0;
7440                         if (typeof dirent === "string" || dirent.isSymbolicLink()) {
7441                             var name = ts.combinePaths(path, entry);
7442                             try {
7443                                 stat = statSync(name);
7444                                 if (!stat) {
7445                                     continue;
7446                                 }
7447                             }
7448                             catch (e) {
7449                                 continue;
7450                             }
7451                         }
7452                         else {
7453                             stat = dirent;
7454                         }
7455                         if (stat.isFile()) {
7456                             files.push(entry);
7457                         }
7458                         else if (stat.isDirectory()) {
7459                             directories.push(entry);
7460                         }
7461                     }
7462                     files.sort();
7463                     directories.sort();
7464                     return { files: files, directories: directories };
7465                 }
7466                 catch (e) {
7467                     return ts.emptyFileSystemEntries;
7468                 }
7469             }
7470             function readDirectory(path, extensions, excludes, includes, depth) {
7471                 return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
7472             }
7473             function fileSystemEntryExists(path, entryKind) {
7474                 // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve
7475                 // the CPU time performance.
7476                 var originalStackTraceLimit = Error.stackTraceLimit;
7477                 Error.stackTraceLimit = 0;
7478                 try {
7479                     var stat = statSync(path);
7480                     if (!stat) {
7481                         return false;
7482                     }
7483                     switch (entryKind) {
7484                         case 0 /* File */: return stat.isFile();
7485                         case 1 /* Directory */: return stat.isDirectory();
7486                         default: return false;
7487                     }
7488                 }
7489                 catch (e) {
7490                     return false;
7491                 }
7492                 finally {
7493                     Error.stackTraceLimit = originalStackTraceLimit;
7494                 }
7495             }
7496             function fileExists(path) {
7497                 return fileSystemEntryExists(path, 0 /* File */);
7498             }
7499             function directoryExists(path) {
7500                 return fileSystemEntryExists(path, 1 /* Directory */);
7501             }
7502             function getDirectories(path) {
7503                 return getAccessibleFileSystemEntries(path).directories.slice();
7504             }
7505             function realpath(path) {
7506                 try {
7507                     return realpathSync(path);
7508                 }
7509                 catch (_a) {
7510                     return path;
7511                 }
7512             }
7513             function getModifiedTime(path) {
7514                 var _a;
7515                 try {
7516                     return (_a = statSync(path)) === null || _a === void 0 ? void 0 : _a.mtime;
7517                 }
7518                 catch (e) {
7519                     return undefined;
7520                 }
7521             }
7522             function setModifiedTime(path, time) {
7523                 try {
7524                     _fs.utimesSync(path, time, time);
7525                 }
7526                 catch (e) {
7527                     return;
7528                 }
7529             }
7530             function deleteFile(path) {
7531                 try {
7532                     return _fs.unlinkSync(path);
7533                 }
7534                 catch (e) {
7535                     return;
7536                 }
7537             }
7538             function createSHA256Hash(data) {
7539                 var hash = _crypto.createHash("sha256");
7540                 hash.update(data);
7541                 return hash.digest("hex");
7542             }
7543         }
7544         var sys;
7545         if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
7546             // process and process.nextTick checks if current environment is node-like
7547             // process.browser check excludes webpack and browserify
7548             sys = getNodeSystem();
7549         }
7550         if (sys) {
7551             // patch writefile to create folder before writing the file
7552             patchWriteFileEnsuringDirectory(sys);
7553         }
7554         return sys;
7555     })();
7556     if (ts.sys && ts.sys.getEnvironmentVariable) {
7557         setCustomPollingValues(ts.sys);
7558         ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
7559             ? 1 /* Normal */
7560             : 0 /* None */);
7561     }
7562     if (ts.sys && ts.sys.debugMode) {
7563         ts.Debug.isDebugging = true;
7564     }
7565 })(ts || (ts = {}));
7566 // <auto-generated />
7567 // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler'
7568 /* @internal */
7569 var ts;
7570 (function (ts) {
7571     function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid, reportsDeprecated) {
7572         return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary, elidedInCompatabilityPyramid: elidedInCompatabilityPyramid, reportsDeprecated: reportsDeprecated };
7573     }
7574     ts.Diagnostics = {
7575         Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."),
7576         Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."),
7577         _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."),
7578         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."),
7579         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."),
7580         Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."),
7581         Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."),
7582         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."),
7583         Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."),
7584         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."),
7585         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."),
7586         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."),
7587         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."),
7588         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."),
7589         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."),
7590         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."),
7591         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."),
7592         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."),
7593         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."),
7594         An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."),
7595         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."),
7596         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."),
7597         Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."),
7598         _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."),
7599         _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."),
7600         _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."),
7601         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."),
7602         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."),
7603         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."),
7604         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."),
7605         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."),
7606         _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."),
7607         _0_modifier_cannot_be_used_with_a_class_declaration: diag(1041, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_with_a_class_declaration_1041", "'{0}' modifier cannot be used with a class declaration."),
7608         _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."),
7609         _0_modifier_cannot_appear_on_a_data_property: diag(1043, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_a_data_property_1043", "'{0}' modifier cannot appear on a data property."),
7610         _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."),
7611         A_0_modifier_cannot_be_used_with_an_interface_declaration: diag(1045, ts.DiagnosticCategory.Error, "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045", "A '{0}' modifier cannot be used with an interface declaration."),
7612         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."),
7613         A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."),
7614         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."),
7615         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."),
7616         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."),
7617         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."),
7618         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."),
7619         A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."),
7620         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."),
7621         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."),
7622         An_async_function_or_method_must_have_a_valid_awaitable_return_type: diag(1057, ts.DiagnosticCategory.Error, "An_async_function_or_method_must_have_a_valid_awaitable_return_type_1057", "An async function or method must have a valid awaitable return type."),
7623         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."),
7624         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."),
7625         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."),
7626         Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."),
7627         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."),
7628         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."),
7629         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}>'?"),
7630         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."),
7631         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."),
7632         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."),
7633         _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."),
7634         _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."),
7635         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."),
7636         Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."),
7637         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}'."),
7638         _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."),
7639         _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."),
7640         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."),
7641         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."),
7642         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."),
7643         An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."),
7644         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."),
7645         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."),
7646         _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."),
7647         Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."),
7648         Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."),
7649         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."),
7650         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."),
7651         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."),
7652         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."),
7653         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."),
7654         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."),
7655         Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
7656         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."),
7657         Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."),
7658         Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."),
7659         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."),
7660         Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."),
7661         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."),
7662         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."),
7663         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."),
7664         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."),
7665         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."),
7666         An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."),
7667         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."),
7668         Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."),
7669         Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."),
7670         Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."),
7671         Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."),
7672         Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."),
7673         Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."),
7674         Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."),
7675         case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."),
7676         Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."),
7677         Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."),
7678         Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."),
7679         Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."),
7680         Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."),
7681         Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."),
7682         Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."),
7683         Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."),
7684         Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."),
7685         String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."),
7686         Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."),
7687         or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."),
7688         Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."),
7689         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."),
7690         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'."),
7691         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."),
7692         const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."),
7693         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."),
7694         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."),
7695         Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."),
7696         Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."),
7697         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."),
7698         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."),
7699         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."),
7700         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."),
7701         A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type: diag(1166, ts.DiagnosticCategory.Error, "A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_1166", "A computed property name in a class property declaration must refer to an expression whose type is a literal type or a 'unique symbol' type."),
7702         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."),
7703         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."),
7704         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."),
7705         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."),
7706         extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."),
7707         extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."),
7708         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."),
7709         implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."),
7710         Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."),
7711         Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."),
7712         Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."),
7713         Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."),
7714         Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."),
7715         Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."),
7716         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."),
7717         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."),
7718         Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."),
7719         Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."),
7720         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."),
7721         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."),
7722         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."),
7723         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."),
7724         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."),
7725         An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."),
7726         Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."),
7727         An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."),
7728         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."),
7729         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."),
7730         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."),
7731         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."),
7732         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."),
7733         Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."),
7734         Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."),
7735         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."),
7736         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."),
7737         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'."),
7738         Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
7739         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."),
7740         _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."),
7741         Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode: diag(1210, ts.DiagnosticCategory.Error, "Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode_1210", "Invalid use of '{0}'. Class definitions are automatically in strict mode."),
7742         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."),
7743         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."),
7744         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."),
7745         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."),
7746         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."),
7747         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."),
7748         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'."),
7749         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."),
7750         Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: diag(1220, ts.DiagnosticCategory.Error, "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", "Generators are only available when targeting ECMAScript 2015 or higher."),
7751         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."),
7752         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."),
7753         _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."),
7754         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."),
7755         Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."),
7756         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}'."),
7757         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}'."),
7758         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."),
7759         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."),
7760         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."),
7761         An_export_assignment_can_only_be_used_in_a_module: diag(1231, ts.DiagnosticCategory.Error, "An_export_assignment_can_only_be_used_in_a_module_1231", "An export assignment can only be used in a module."),
7762         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."),
7763         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."),
7764         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."),
7765         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."),
7766         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'."),
7767         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'."),
7768         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."),
7769         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."),
7770         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."),
7771         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."),
7772         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."),
7773         _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."),
7774         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."),
7775         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."),
7776         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."),
7777         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."),
7778         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."),
7779         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."),
7780         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'."),
7781         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."),
7782         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."),
7783         _0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag: diag(1253, ts.DiagnosticCategory.Error, "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253", "'{0}' tag cannot be used independently as a top level JSDoc tag."),
7784         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."),
7785         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."),
7786         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."),
7787         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"),
7788         Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."),
7789         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."),
7790         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."),
7791         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."),
7792         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."),
7793         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."),
7794         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."),
7795         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."),
7796         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."),
7797         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."),
7798         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."),
7799         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."),
7800         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."),
7801         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."),
7802         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."),
7803         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."),
7804         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."),
7805         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."),
7806         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."),
7807         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."),
7808         Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system__1323", "Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'esnext', 'commonjs', 'amd', 'system', or 'umd'."),
7809         Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."),
7810         Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."),
7811         Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments."),
7812         String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."),
7813         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."),
7814         _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}()'?"),
7815         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'."),
7816         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'."),
7817         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'."),
7818         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."),
7819         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."),
7820         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."),
7821         An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."),
7822         An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."),
7823         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."),
7824         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."),
7825         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}')'?"),
7826         Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."),
7827         The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system_1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system'."),
7828         A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
7829         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."),
7830         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."),
7831         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."),
7832         Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
7833         use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
7834         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."),
7835         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."),
7836         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."),
7837         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."),
7838         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."),
7839         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."),
7840         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'?"),
7841         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 '}'."),
7842         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."),
7843         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."),
7844         Did_you_mean_to_parenthesize_this_function_type: diag(1360, ts.DiagnosticCategory.Error, "Did_you_mean_to_parenthesize_this_function_type_1360", "Did you mean to parenthesize this function type?"),
7845         _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'."),
7846         _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'."),
7847         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."),
7848         Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"),
7849         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"),
7850         Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"),
7851         Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"),
7852         Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types: diag(1368, ts.DiagnosticCategory.Message, "Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types_1368", "Specify emit/checking behavior for imports that are only used for types"),
7853         Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"),
7854         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'."),
7855         Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"),
7856         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"),
7857         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."),
7858         _0_was_imported_here: diag(1376, ts.DiagnosticCategory.Message, "_0_was_imported_here_1376", "'{0}' was imported here."),
7859         _0_was_exported_here: diag(1377, ts.DiagnosticCategory.Message, "_0_was_exported_here_1377", "'{0}' was exported here."),
7860         Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher: diag(1378, ts.DiagnosticCategory.Error, "Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_t_1378", "Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."),
7861         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'."),
7862         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'."),
7863         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;`?"),
7864         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;`?"),
7865         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'."),
7866         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."),
7867         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."),
7868         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."),
7869         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."),
7870         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."),
7871         _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."),
7872         Provides_a_root_package_name_when_using_outFile_with_declarations: diag(1390, ts.DiagnosticCategory.Message, "Provides_a_root_package_name_when_using_outFile_with_declarations_1390", "Provides a root package name when using outFile with declarations."),
7873         The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_declaration_emit: diag(1391, ts.DiagnosticCategory.Error, "The_bundledPackageName_option_must_be_provided_when_using_outFile_and_node_module_resolution_with_de_1391", "The `bundledPackageName` option must be provided when using outFile and node module resolution with declaration emit."),
7874         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'"),
7875         Imported_via_0_from_file_1: diag(1393, ts.DiagnosticCategory.Message, "Imported_via_0_from_file_1_1393", "Imported via {0} from file '{1}'"),
7876         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}'"),
7877         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"),
7878         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"),
7879         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"),
7880         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"),
7881         File_is_included_via_import_here: diag(1399, ts.DiagnosticCategory.Message, "File_is_included_via_import_here_1399", "File is included via import here."),
7882         Referenced_via_0_from_file_1: diag(1400, ts.DiagnosticCategory.Message, "Referenced_via_0_from_file_1_1400", "Referenced via '{0}' from file '{1}'"),
7883         File_is_included_via_reference_here: diag(1401, ts.DiagnosticCategory.Message, "File_is_included_via_reference_here_1401", "File is included via reference here."),
7884         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}'"),
7885         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}'"),
7886         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."),
7887         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}'"),
7888         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."),
7889         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}'"),
7890         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."),
7891         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"),
7892         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."),
7893         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"),
7894         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'"),
7895         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."),
7896         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"),
7897         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'"),
7898         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."),
7899         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"),
7900         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}'"),
7901         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."),
7902         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}'"),
7903         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}'"),
7904         Library_0_specified_in_compilerOptions: diag(1422, ts.DiagnosticCategory.Message, "Library_0_specified_in_compilerOptions_1422", "Library '{0}' specified in compilerOptions"),
7905         File_is_library_specified_here: diag(1423, ts.DiagnosticCategory.Message, "File_is_library_specified_here_1423", "File is library specified here."),
7906         Default_library: diag(1424, ts.DiagnosticCategory.Message, "Default_library_1424", "Default library"),
7907         Default_library_for_target_0: diag(1425, ts.DiagnosticCategory.Message, "Default_library_for_target_0_1425", "Default library for target '{0}'"),
7908         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."),
7909         Root_file_specified_for_compilation: diag(1427, ts.DiagnosticCategory.Message, "Root_file_specified_for_compilation_1427", "Root file specified for compilation"),
7910         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}'"),
7911         File_redirects_to_file_0: diag(1429, ts.DiagnosticCategory.Message, "File_redirects_to_file_0_1429", "File redirects to file '{0}'"),
7912         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:"),
7913         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."),
7914         Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_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_esnext_or_system_and_the_1432", "Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher."),
7915         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."),
7916         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."),
7917         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),
7918         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),
7919         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),
7920         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),
7921         Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
7922         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."),
7923         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."),
7924         Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."),
7925         Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."),
7926         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}'."),
7927         File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."),
7928         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."),
7929         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."),
7930         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."),
7931         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."),
7932         A_class_may_only_extend_another_class: diag(2311, ts.DiagnosticCategory.Error, "A_class_may_only_extend_another_class_2311", "A class may only extend another class."),
7933         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."),
7934         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."),
7935         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)."),
7936         Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
7937         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."),
7938         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)."),
7939         Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."),
7940         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."),
7941         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}'."),
7942         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}'."),
7943         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}'."),
7944         Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."),
7945         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}'."),
7946         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}'."),
7947         Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."),
7948         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}'."),
7949         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."),
7950         Index_signature_is_missing_in_type_0: diag(2329, ts.DiagnosticCategory.Error, "Index_signature_is_missing_in_type_0_2329", "Index signature is missing in type '{0}'."),
7951         Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."),
7952         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."),
7953         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."),
7954         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."),
7955         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."),
7956         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."),
7957         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."),
7958         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."),
7959         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."),
7960         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}'."),
7961         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."),
7962         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}'."),
7963         An_index_expression_argument_must_be_of_type_string_number_symbol_or_any: diag(2342, ts.DiagnosticCategory.Error, "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342", "An index expression argument must be of type 'string', 'number', 'symbol', or 'any'."),
7964         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}'."),
7965         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}'."),
7966         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}'."),
7967         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."),
7968         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."),
7969         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'?"),
7970         This_expression_is_not_callable: diag(2349, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_2349", "This expression is not callable."),
7971         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."),
7972         This_expression_is_not_constructable: diag(2351, ts.DiagnosticCategory.Error, "This_expression_is_not_constructable_2351", "This expression is not constructable."),
7973         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."),
7974         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}'."),
7975         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."),
7976         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."),
7977         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."),
7978         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."),
7979         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."),
7980         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."),
7981         The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol: diag(2360, ts.DiagnosticCategory.Error, "The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol_2360", "The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'."),
7982         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."),
7983         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."),
7984         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."),
7985         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."),
7986         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}'."),
7987         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'."),
7988         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."),
7989         Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."),
7990         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."),
7991         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."),
7992         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."),
7993         Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."),
7994         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."),
7995         Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."),
7996         Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."),
7997         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."),
7998         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."),
7999         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."),
8000         Getter_and_setter_accessors_do_not_agree_in_visibility: diag(2379, ts.DiagnosticCategory.Error, "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", "Getter and setter accessors do not agree in visibility."),
8001         get_and_set_accessor_must_have_the_same_type: diag(2380, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_type_2380", "'get' and 'set' accessor must have the same type."),
8002         A_signature_with_an_implementation_cannot_use_a_string_literal_type: diag(2381, ts.DiagnosticCategory.Error, "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", "A signature with an implementation cannot use a string literal type."),
8003         Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature: diag(2382, ts.DiagnosticCategory.Error, "Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature_2382", "Specialized overload signature is not assignable to any non-specialized signature."),
8004         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."),
8005         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."),
8006         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."),
8007         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."),
8008         Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."),
8009         Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."),
8010         Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."),
8011         Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."),
8012         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."),
8013         Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
8014         Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
8015         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."),
8016         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."),
8017         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."),
8018         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}'."),
8019         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."),
8020         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."),
8021         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."),
8022         Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference: diag(2401, ts.DiagnosticCategory.Error, "Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference_2401", "Duplicate identifier '_super'. Compiler uses '_super' to capture base class reference."),
8023         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."),
8024         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}'."),
8025         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."),
8026         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'."),
8027         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."),
8028         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}'."),
8029         Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."),
8030         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."),
8031         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'."),
8032         Property_0_of_type_1_is_not_assignable_to_string_index_type_2: diag(2411, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", "Property '{0}' of type '{1}' is not assignable to string index type '{2}'."),
8033         Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: diag(2412, ts.DiagnosticCategory.Error, "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'."),
8034         Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."),
8035         Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."),
8036         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}'."),
8037         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}'."),
8038         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}'."),
8039         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}'."),
8040         Types_of_construct_signatures_are_incompatible: diag(2419, ts.DiagnosticCategory.Error, "Types_of_construct_signatures_are_incompatible_2419", "Types of construct signatures are incompatible."),
8041         Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
8042         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."),
8043         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."),
8044         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."),
8045         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."),
8046         Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."),
8047         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."),
8048         Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."),
8049         Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."),
8050         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."),
8051         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."),
8052         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."),
8053         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."),
8054         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."),
8055         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."),
8056         Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."),
8057         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."),
8058         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}'."),
8059         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."),
8060         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}'."),
8061         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}'."),
8062         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}'."),
8063         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."),
8064         Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: diag(2446, ts.DiagnosticCategory.Error, "Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_2446", "Property '{0}' is protected and only accessible through an instance of class '{1}'."),
8065         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."),
8066         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."),
8067         Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."),
8068         Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."),
8069         Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."),
8070         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."),
8071         The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: diag(2453, ts.DiagnosticCategory.Error, "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453", "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly."),
8072         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."),
8073         Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: diag(2455, ts.DiagnosticCategory.Error, "Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0_2455", "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'."),
8074         Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."),
8075         Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."),
8076         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."),
8077         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."),
8078         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}'."),
8079         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."),
8080         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."),
8081         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."),
8082         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'."),
8083         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."),
8084         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."),
8085         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."),
8086         Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."),
8087         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'."),
8088         Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object: diag(2470, ts.DiagnosticCategory.Error, "Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object_2470", "'Symbol' reference does not refer to the global Symbol constructor object."),
8089         A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."),
8090         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."),
8091         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."),
8092         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."),
8093         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."),
8094         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."),
8095         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."),
8096         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'."),
8097         Property_0_does_not_exist_on_const_enum_1: diag(2479, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_const_enum_1_2479", "Property '{0}' does not exist on 'const' enum '{1}'."),
8098         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."),
8099         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}'."),
8100         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."),
8101         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}'."),
8102         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."),
8103         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."),
8104         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."),
8105         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."),
8106         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."),
8107         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."),
8108         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}'."),
8109         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."),
8110         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."),
8111         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."),
8112         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."),
8113         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 *'."),
8114         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."),
8115         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."),
8116         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."),
8117         _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."),
8118         Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."),
8119         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."),
8120         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."),
8121         _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."),
8122         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."),
8123         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."),
8124         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."),
8125         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."),
8126         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."),
8127         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."),
8128         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."),
8129         Classes_containing_abstract_methods_must_be_marked_abstract: diag(2514, ts.DiagnosticCategory.Error, "Classes_containing_abstract_methods_must_be_marked_abstract_2514", "Classes containing abstract methods must be marked abstract."),
8130         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}'."),
8131         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."),
8132         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."),
8133         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."),
8134         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."),
8135         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."),
8136         Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: diag(2521, ts.DiagnosticCategory.Error, "Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions_2521", "Expression resolves to variable declaration '{0}' that compiler uses to support async functions."),
8137         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."),
8138         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."),
8139         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."),
8140         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."),
8141         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."),
8142         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."),
8143         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."),
8144         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."),
8145         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."),
8146         Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."),
8147         Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."),
8148         Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."),
8149         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."),
8150         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."),
8151         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}'."),
8152         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}'."),
8153         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."),
8154         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."),
8155         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."),
8156         The_target_of_an_assignment_must_be_a_variable_or_a_property_access: diag(2541, ts.DiagnosticCategory.Error, "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541", "The target of an assignment must be a variable or a property access."),
8157         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."),
8158         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."),
8159         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."),
8160         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[]'."),
8161         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."),
8162         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."),
8163         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."),
8164         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."),
8165         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}'?"),
8166         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}'?"),
8167         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."),
8168         Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."),
8169         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}."),
8170         Expected_0_arguments_but_got_1_or_more: diag(2556, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_or_more_2556", "Expected {0} arguments, but got {1} or more."),
8171         Expected_at_least_0_arguments_but_got_1_or_more: diag(2557, ts.DiagnosticCategory.Error, "Expected_at_least_0_arguments_but_got_1_or_more_2557", "Expected at least {0} arguments, but got {1} or more."),
8172         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}."),
8173         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}'."),
8174         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?"),
8175         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}'?"),
8176         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."),
8177         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."),
8178         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."),
8179         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."),
8180         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."),
8181         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."),
8182         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."),
8183         Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."),
8184         Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."),
8185         Property_0_is_incompatible_with_rest_element_type: diag(2573, ts.DiagnosticCategory.Error, "Property_0_is_incompatible_with_rest_element_type_2573", "Property '{0}' is incompatible with rest element type."),
8186         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."),
8187         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."),
8188         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?"),
8189         Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
8190         Unused_ts_expect_error_directive: diag(2578, ts.DiagnosticCategory.Error, "Unused_ts_expect_error_directive_2578", "Unused '@ts-expect-error' directive."),
8191         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`."),
8192         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`."),
8193         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`."),
8194         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."),
8195         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'."),
8196         _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."),
8197         Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
8198         JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
8199         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."),
8200         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."),
8201         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."),
8202         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."),
8203         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."),
8204         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."),
8205         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."),
8206         _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."),
8207         _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."),
8208         _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."),
8209         _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."),
8210         JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."),
8211         The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."),
8212         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."),
8213         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}'."),
8214         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."),
8215         JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: diag(2605, ts.DiagnosticCategory.Error, "JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements_2605", "JSX element type '{0}' is not a constructor function for JSX elements."),
8216         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."),
8217         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."),
8218         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."),
8219         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."),
8220         _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."),
8221         _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."),
8222         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."),
8223         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?"),
8224         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?"),
8225         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}'."),
8226         _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."),
8227         _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."),
8228         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}."),
8229         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}."),
8230         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."),
8231         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."),
8232         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."),
8233         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."),
8234         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."),
8235         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."),
8236         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."),
8237         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."),
8238         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."),
8239         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."),
8240         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}'."),
8241         Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: diag(2654, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_pack_2654", "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition."),
8242         Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition: diag(2656, ts.DiagnosticCategory.Error, "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656", "Exported external package typings file '{0}' is not a module. Please contact the package author to update the package definition."),
8243         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."),
8244         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}'."),
8245         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."),
8246         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."),
8247         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."),
8248         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}'?"),
8249         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}'?"),
8250         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."),
8251         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."),
8252         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."),
8253         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."),
8254         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."),
8255         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."),
8256         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."),
8257         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."),
8258         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."),
8259         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."),
8260         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."),
8261         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."),
8262         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."),
8263         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."),
8264         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}'."),
8265         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'."),
8266         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."),
8267         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."),
8268         get_and_set_accessor_must_have_the_same_this_type: diag(2682, ts.DiagnosticCategory.Error, "get_and_set_accessor_must_have_the_same_this_type_2682", "'get' and 'set' accessor must have the same 'this' type."),
8269         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."),
8270         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}'."),
8271         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."),
8272         _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."),
8273         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."),
8274         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}'."),
8275         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'?"),
8276         _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}'?"),
8277         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."),
8278         _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."),
8279         _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."),
8280         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}'."),
8281         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),
8282         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?"),
8283         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."),
8284         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."),
8285         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}'."),
8286         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."),
8287         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."),
8288         _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."),
8289         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."),
8290         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."),
8291         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."),
8292         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."),
8293         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."),
8294         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."),
8295         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."),
8296         _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."),
8297         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."),
8298         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."),
8299         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}\"]'?"),
8300         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."),
8301         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."),
8302         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."),
8303         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}'."),
8304         Duplicate_property_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_property_0_2718", "Duplicate property '{0}'."),
8305         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."),
8306         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?"),
8307         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'."),
8308         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'."),
8309         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'."),
8310         _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}'?"),
8311         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}."),
8312         Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."),
8313         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}'?"),
8314         _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."),
8315         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."),
8316         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."),
8317         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(...)'."),
8318         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."),
8319         Property_0_was_also_declared_here: diag(2733, ts.DiagnosticCategory.Error, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."),
8320         Are_you_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "Are_you_missing_a_semicolon_2734", "Are you missing a semicolon?"),
8321         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}'?"),
8322         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}'."),
8323         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."),
8324         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."),
8325         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}"),
8326         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."),
8327         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}'."),
8328         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."),
8329         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."),
8330         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."),
8331         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."),
8332         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."),
8333         _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}'."),
8334         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."),
8335         _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}'?"),
8336         The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
8337         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."),
8338         The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
8339         Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
8340         super_may_not_use_type_arguments: diag(2754, ts.DiagnosticCategory.Error, "super_may_not_use_type_arguments_2754", "'super' may not use type arguments."),
8341         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."),
8342         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."),
8343         Type_0_has_no_call_signatures: diag(2757, ts.DiagnosticCategory.Error, "Type_0_has_no_call_signatures_2757", "Type '{0}' has no call signatures."),
8344         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."),
8345         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."),
8346         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."),
8347         Type_0_has_no_construct_signatures: diag(2761, ts.DiagnosticCategory.Error, "Type_0_has_no_construct_signatures_2761", "Type '{0}' has no construct signatures."),
8348         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."),
8349         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}'."),
8350         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}'."),
8351         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}'."),
8352         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}'."),
8353         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."),
8354         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."),
8355         No_overload_matches_this_call: diag(2769, ts.DiagnosticCategory.Error, "No_overload_matches_this_call_2769", "No overload matches this call."),
8356         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."),
8357         The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."),
8358         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."),
8359         Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"),
8360         This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead: diag(2774, ts.DiagnosticCategory.Error, "This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it__2774", "This condition will always return true since the function is always defined. Did you mean to call it instead?"),
8361         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."),
8362         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."),
8363         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."),
8364         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."),
8365         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."),
8366         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."),
8367         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."),
8368         _0_needs_an_explicit_type_annotation: diag(2782, ts.DiagnosticCategory.Message, "_0_needs_an_explicit_type_annotation_2782", "'{0}' needs an explicit type annotation."),
8369         _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."),
8370         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."),
8371         This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."),
8372         _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."),
8373         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."),
8374         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."),
8375         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."),
8376         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."),
8377         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."),
8378         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?"),
8379         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."),
8380         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'?"),
8381         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."),
8382         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."),
8383         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'."),
8384         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."),
8385         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."),
8386         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."),
8387         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}'."),
8388         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}'."),
8389         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}'."),
8390         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}'."),
8391         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}'."),
8392         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}'."),
8393         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}'."),
8394         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}'."),
8395         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}'."),
8396         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}'."),
8397         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}'."),
8398         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}'."),
8399         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}'."),
8400         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."),
8401         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}'."),
8402         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}'."),
8403         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."),
8404         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}'."),
8405         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}'."),
8406         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."),
8407         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}'."),
8408         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}'."),
8409         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}'."),
8410         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}'."),
8411         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}'."),
8412         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}'."),
8413         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}'."),
8414         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}'."),
8415         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."),
8416         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}'."),
8417         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}'."),
8418         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."),
8419         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}'."),
8420         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}'."),
8421         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}'."),
8422         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}'."),
8423         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}'."),
8424         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}'."),
8425         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}'."),
8426         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}'."),
8427         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."),
8428         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}'."),
8429         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}'."),
8430         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."),
8431         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}'."),
8432         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}'."),
8433         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}'."),
8434         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}'."),
8435         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."),
8436         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}'."),
8437         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}'."),
8438         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."),
8439         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}'."),
8440         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}'."),
8441         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}'."),
8442         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}'."),
8443         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}'."),
8444         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}'."),
8445         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."),
8446         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}'."),
8447         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}'."),
8448         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."),
8449         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}'."),
8450         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}'."),
8451         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}'."),
8452         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}'."),
8453         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."),
8454         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}'."),
8455         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}'."),
8456         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}'."),
8457         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}'."),
8458         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}'."),
8459         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}."),
8460         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."),
8461         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}'."),
8462         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}'."),
8463         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."),
8464         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."),
8465         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}'."),
8466         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}'."),
8467         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."),
8468         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}'."),
8469         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}'."),
8470         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}'."),
8471         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}'."),
8472         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}'."),
8473         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}'."),
8474         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."),
8475         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}'."),
8476         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}'."),
8477         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."),
8478         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."),
8479         Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."),
8480         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}']."),
8481         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."),
8482         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."),
8483         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}'."),
8484         Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."),
8485         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}."),
8486         Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."),
8487         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}."),
8488         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}'?"),
8489         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}."),
8490         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."),
8491         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."),
8492         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'."),
8493         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."),
8494         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}'."),
8495         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}'."),
8496         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}'."),
8497         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."),
8498         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."),
8499         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}'."),
8500         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}'."),
8501         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."),
8502         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."),
8503         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."),
8504         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."),
8505         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}'."),
8506         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}'."),
8507         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."),
8508         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."),
8509         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."),
8510         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}'."),
8511         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."),
8512         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'."),
8513         Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
8514         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}."),
8515         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."),
8516         _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}'."),
8517         _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."),
8518         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}'?"),
8519         Unknown_watch_option_0: diag(5078, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_5078", "Unknown watch option '{0}'."),
8520         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}'?"),
8521         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}."),
8522         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}."),
8523         _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}'."),
8524         Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."),
8525         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."),
8526         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."),
8527         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."),
8528         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."),
8529         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."),
8530         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}'."),
8531         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 './'?"),
8532         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."),
8533         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."),
8534         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."),
8535         Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
8536         Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: diag(6003, ts.DiagnosticCategory.Message, "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003", "Specify the location where debugger should locate map files instead of generated locations."),
8537         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."),
8538         Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
8539         Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
8540         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."),
8541         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."),
8542         Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
8543         Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
8544         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."),
8545         Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
8546         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."),
8547         Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
8548         Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT: diag(6015, ts.DiagnosticCategory.Message, "Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_6015", "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'."),
8549         Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext: diag(6016, ts.DiagnosticCategory.Message, "Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext_6016", "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'."),
8550         Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
8551         Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
8552         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'."),
8553         Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
8554         options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
8555         file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
8556         Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
8557         Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
8558         Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
8559         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."),
8560         Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
8561         File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
8562         KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
8563         FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
8564         VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
8565         LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
8566         DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
8567         STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
8568         FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
8569         Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
8570         Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
8571         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}'."),
8572         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}."),
8573         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}'."),
8574         Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."),
8575         Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
8576         Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
8577         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."),
8578         File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
8579         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}."),
8580         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."),
8581         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."),
8582         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."),
8583         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."),
8584         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)."),
8585         NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
8586         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."),
8587         Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
8588         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."),
8589         Enables_experimental_support_for_ES7_async_functions: diag(6068, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_async_functions_6068", "Enables experimental support for ES7 async functions."),
8590         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)."),
8591         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."),
8592         Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
8593         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."),
8594         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)."),
8595         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."),
8596         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."),
8597         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."),
8598         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."),
8599         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."),
8600         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."),
8601         Specify_JSX_code_generation_Colon_preserve_react_native_react_react_jsx_or_react_jsxdev: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_react_react_jsx_or_react_jsxdev_6080", "Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'."),
8602         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."),
8603         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}."),
8604         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."),
8605         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"),
8606         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."),
8607         Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
8608         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}'."),
8609         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}'."),
8610         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}'. ========"),
8611         Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
8612         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}'."),
8613         Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
8614         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}'."),
8615         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}'."),
8616         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}'."),
8617         File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
8618         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."),
8619         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}'."),
8620         Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
8621         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."),
8622         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}'."),
8623         Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
8624         Option_0_should_have_array_of_strings_as_a_value: diag(6103, ts.DiagnosticCategory.Error, "Option_0_should_have_array_of_strings_as_a_value_6103", "Option '{0}' should have array of strings as a value."),
8625         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}'."),
8626         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}'."),
8627         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}'."),
8628         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}'."),
8629         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}'."),
8630         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}'."),
8631         Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
8632         Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
8633         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."),
8634         Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
8635         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'?"),
8636         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."),
8637         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}'. ========"),
8638         Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."),
8639         Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."),
8640         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}. ========"),
8641         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. ========"),
8642         Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
8643         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."),
8644         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. ========"),
8645         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."),
8646         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}'."),
8647         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."),
8648         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}'. ========"),
8649         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. ========"),
8650         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}'."),
8651         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'."),
8652         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."),
8653         _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),
8654         Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."),
8655         Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."),
8656         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."),
8657         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}'."),
8658         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),
8659         Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."),
8660         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}'."),
8661         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."),
8662         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."),
8663         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}'."),
8664         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."),
8665         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'."),
8666         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}'."),
8667         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."),
8668         Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
8669         Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
8670         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."),
8671         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."),
8672         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')."),
8673         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."),
8674         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."),
8675         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')"),
8676         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."),
8677         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)."),
8678         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."),
8679         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."),
8680         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."),
8681         Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
8682         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."),
8683         Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files: diag(6164, ts.DiagnosticCategory.Message, "Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files_6164", "Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files."),
8684         Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
8685         Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
8686         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'."),
8687         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."),
8688         Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
8689         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"),
8690         Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
8691         Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"),
8692         Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"),
8693         Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"),
8694         Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"),
8695         Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"),
8696         Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"),
8697         Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"),
8698         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'."),
8699         Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
8700         List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
8701         Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
8702         Reusing_resolution_of_module_0_to_file_1_from_old_program: diag(6183, ts.DiagnosticCategory.Message, "Reusing_resolution_of_module_0_to_file_1_from_old_program_6183", "Reusing resolution of module '{0}' to file '{1}' from old program."),
8703         Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program: diag(6184, ts.DiagnosticCategory.Message, "Reusing_module_resolutions_originating_in_0_since_resolutions_are_unchanged_from_old_program_6184", "Reusing module resolutions originating in '{0}' since resolutions are unchanged from old program."),
8704         Disable_strict_checking_of_generic_signatures_in_function_types: diag(6185, ts.DiagnosticCategory.Message, "Disable_strict_checking_of_generic_signatures_in_function_types_6185", "Disable strict checking of generic signatures in function types."),
8705         Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
8706         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."),
8707         Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
8708         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."),
8709         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."),
8710         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),
8711         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."),
8712         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."),
8713         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)."),
8714         _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),
8715         Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
8716         All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
8717         All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
8718         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}"),
8719         Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
8720         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}"),
8721         _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
8722         and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
8723         All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused."),
8724         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."),
8725         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}'."),
8726         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}'."),
8727         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."),
8728         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."),
8729         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."),
8730         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?"),
8731         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?"),
8732         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."),
8733         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}'."),
8734         Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."),
8735         Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."),
8736         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}'. ========"),
8737         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}. ========"),
8738         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."),
8739         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."),
8740         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."),
8741         Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."),
8742         Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."),
8743         Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory: diag(6225, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_Dynami_6225", "Specify strategy for watching file: 'FixedPollingInterval' (default), 'PriorityPollingInterval', 'DynamicPriorityPolling', 'UseFsEvents', 'UseFsEventsOnParentDirectory'."),
8744         Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling: diag(6226, ts.DiagnosticCategory.Message, "Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively__6226", "Specify strategy for watching directory on platforms that don't support recursive watching natively: 'UseFsEvents' (default), 'FixedPollingInterval', 'DynamicPriorityPolling'."),
8745         Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority: diag(6227, ts.DiagnosticCategory.Message, "Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_6227", "Specify strategy for creating a polling watch when it fails to create using file system events: 'FixedInterval' (default), 'PriorityInterval', 'DynamicPriority'."),
8746         Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively: diag(6228, ts.DiagnosticCategory.Message, "Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_supp_6228", "Synchronously call callbacks and update the state of directory watchers on platforms that don't support recursive watching natively."),
8747         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}'."),
8748         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."),
8749         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}."),
8750         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."),
8751         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."),
8752         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 '()'?"),
8753         Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."),
8754         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."),
8755         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."),
8756         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"),
8757         Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
8758         Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
8759         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."),
8760         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}'."),
8761         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."),
8762         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."),
8763         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"),
8764         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"),
8765         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."),
8766         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}'"),
8767         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}'"),
8768         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"),
8769         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"),
8770         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"),
8771         Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
8772         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}"),
8773         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}'"),
8774         Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
8775         Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
8776         delete_this_Project_0_is_up_to_date_because_it_was_previously_built: diag(6360, ts.DiagnosticCategory.Message, "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360", "delete this - Project '{0}' is up to date because it was previously built"),
8777         Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
8778         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"),
8779         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"),
8780         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"),
8781         Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
8782         Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"),
8783         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')"),
8784         Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"),
8785         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."),
8786         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."),
8787         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}'..."),
8788         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"),
8789         Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
8790         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}'"),
8791         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}'"),
8792         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}'"),
8793         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}'"),
8794         Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
8795         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."),
8796         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"),
8797         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}'"),
8798         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"),
8799         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"),
8800         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."),
8801         _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true),
8802         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."),
8803         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),
8804         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}'"),
8805         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."),
8806         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."),
8807         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."),
8808         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?"),
8809         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."),
8810         Require_undeclared_properties_from_index_signatures_to_use_element_accesses: diag(6803, ts.DiagnosticCategory.Error, "Require_undeclared_properties_from_index_signatures_to_use_element_accesses_6803", "Require undeclared properties from index signatures to use element accesses."),
8811         Include_undefined_in_index_signature_results: diag(6800, ts.DiagnosticCategory.Message, "Include_undefined_in_index_signature_results_6800", "Include 'undefined' in index signature results"),
8812         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."),
8813         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."),
8814         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."),
8815         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."),
8816         _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."),
8817         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."),
8818         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."),
8819         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."),
8820         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'."),
8821         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."),
8822         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."),
8823         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."),
8824         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."),
8825         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."),
8826         _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."),
8827         _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."),
8828         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."),
8829         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."),
8830         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."),
8831         Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true),
8832         Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true),
8833         Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."),
8834         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."),
8835         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."),
8836         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."),
8837         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."),
8838         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."),
8839         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}';`"),
8840         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}'."),
8841         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'."),
8842         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."),
8843         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."),
8844         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}`"),
8845         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'."),
8846         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."),
8847         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."),
8848         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."),
8849         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."),
8850         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."),
8851         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."),
8852         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."),
8853         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."),
8854         _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."),
8855         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}'?"),
8856         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}'?"),
8857         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}'."),
8858         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}'."),
8859         _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."),
8860         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."),
8861         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."),
8862         You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
8863         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."),
8864         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."),
8865         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."),
8866         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."),
8867         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."),
8868         _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."),
8869         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."),
8870         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."),
8871         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."),
8872         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."),
8873         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."),
8874         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."),
8875         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."),
8876         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}'."),
8877         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}'."),
8878         Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
8879         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."),
8880         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."),
8881         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."),
8882         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."),
8883         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."),
8884         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."),
8885         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."),
8886         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."),
8887         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."),
8888         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."),
8889         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."),
8890         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."),
8891         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}'."),
8892         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."),
8893         The_tag_was_first_specified_here: diag(8034, ts.DiagnosticCategory.Error, "The_tag_was_first_specified_here_8034", "The tag was first specified here."),
8894         Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."),
8895         class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."),
8896         Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."),
8897         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."),
8898         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."),
8899         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'."),
8900         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."),
8901         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}'."),
8902         JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."),
8903         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."),
8904         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'."),
8905         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."),
8906         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."),
8907         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."),
8908         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."),
8909         Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
8910         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."),
8911         _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}'?"),
8912         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."),
8913         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."),
8914         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."),
8915         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."),
8916         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."),
8917         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}'?"),
8918         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}"),
8919         A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not: diag(18001, ts.DiagnosticCategory.Error, "A_path_in_an_extends_option_must_be_relative_or_rooted_but_0_is_not_18001", "A path in an 'extends' option must be relative or rooted, but '{0}' is not."),
8920         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."),
8921         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}'."),
8922         File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module: diag(80001, ts.DiagnosticCategory.Suggestion, "File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module_80001", "File is a CommonJS module; it may be converted to an ES6 module."),
8923         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."),
8924         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."),
8925         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."),
8926         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."),
8927         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."),
8928         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."),
8929         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."),
8930         Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
8931         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"),
8932         Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
8933         Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"),
8934         Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
8935         Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
8936         Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
8937         Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
8938         Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
8939         Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
8940         Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
8941         Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
8942         Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
8943         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}\""),
8944         Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
8945         Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
8946         Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
8947         Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
8948         Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
8949         Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
8950         Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
8951         Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
8952         Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
8953         Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
8954         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}'"),
8955         Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
8956         Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
8957         Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
8958         Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
8959         Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
8960         Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
8961         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}\""),
8962         Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
8963         Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"),
8964         Replace_0_with_Promise_1: diag(90036, ts.DiagnosticCategory.Message, "Replace_0_with_Promise_1_90036", "Replace '{0}' with 'Promise<{1}>'"),
8965         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"),
8966         Declare_private_method_0: diag(90038, ts.DiagnosticCategory.Message, "Declare_private_method_0_90038", "Declare private method '{0}'"),
8967         Remove_unused_destructuring_declaration: diag(90039, ts.DiagnosticCategory.Message, "Remove_unused_destructuring_declaration_90039", "Remove unused destructuring declaration"),
8968         Remove_unused_declarations_for_Colon_0: diag(90041, ts.DiagnosticCategory.Message, "Remove_unused_declarations_for_Colon_0_90041", "Remove unused declarations for: '{0}'"),
8969         Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."),
8970         Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
8971         Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"),
8972         Convert_0_to_1_in_0: diag(95003, ts.DiagnosticCategory.Message, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"),
8973         Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
8974         Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
8975         Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
8976         Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
8977         Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
8978         Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
8979         Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"),
8980         Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
8981         Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
8982         Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
8983         Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
8984         Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
8985         Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
8986         Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
8987         Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
8988         Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
8989         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}'"),
8990         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"),
8991         Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
8992         Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
8993         Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
8994         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"),
8995         Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
8996         Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
8997         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"),
8998         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"),
8999         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"),
9000         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)"),
9001         Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
9002         Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
9003         Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
9004         Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
9005         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"),
9006         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"),
9007         Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
9008         Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
9009         Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
9010         Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
9011         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"),
9012         Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
9013         Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
9014         Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
9015         Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
9016         Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
9017         Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
9018         Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
9019         Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
9020         Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
9021         Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
9022         Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
9023         Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
9024         Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
9025         Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
9026         Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
9027         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"),
9028         Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
9029         Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
9030         Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
9031         Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
9032         Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
9033         Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
9034         Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
9035         Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
9036         Add_missing_call_parentheses: diag(95067, ts.DiagnosticCategory.Message, "Add_missing_call_parentheses_95067", "Add missing call parentheses"),
9037         Add_all_missing_call_parentheses: diag(95068, ts.DiagnosticCategory.Message, "Add_all_missing_call_parentheses_95068", "Add all missing call parentheses"),
9038         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"),
9039         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"),
9040         Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
9041         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"),
9042         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"),
9043         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"),
9044         Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
9045         Allow_accessing_UMD_globals_from_modules: diag(95076, ts.DiagnosticCategory.Message, "Allow_accessing_UMD_globals_from_modules_95076", "Allow accessing UMD globals from modules."),
9046         Extract_type: diag(95077, ts.DiagnosticCategory.Message, "Extract_type_95077", "Extract type"),
9047         Extract_to_type_alias: diag(95078, ts.DiagnosticCategory.Message, "Extract_to_type_alias_95078", "Extract to type alias"),
9048         Extract_to_typedef: diag(95079, ts.DiagnosticCategory.Message, "Extract_to_typedef_95079", "Extract to typedef"),
9049         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"),
9050         Add_const_to_unresolved_variable: diag(95081, ts.DiagnosticCategory.Message, "Add_const_to_unresolved_variable_95081", "Add 'const' to unresolved variable"),
9051         Add_const_to_all_unresolved_variables: diag(95082, ts.DiagnosticCategory.Message, "Add_const_to_all_unresolved_variables_95082", "Add 'const' to all unresolved variables"),
9052         Add_await: diag(95083, ts.DiagnosticCategory.Message, "Add_await_95083", "Add 'await'"),
9053         Add_await_to_initializer_for_0: diag(95084, ts.DiagnosticCategory.Message, "Add_await_to_initializer_for_0_95084", "Add 'await' to initializer for '{0}'"),
9054         Fix_all_expressions_possibly_missing_await: diag(95085, ts.DiagnosticCategory.Message, "Fix_all_expressions_possibly_missing_await_95085", "Fix all expressions possibly missing 'await'"),
9055         Remove_unnecessary_await: diag(95086, ts.DiagnosticCategory.Message, "Remove_unnecessary_await_95086", "Remove unnecessary 'await'"),
9056         Remove_all_unnecessary_uses_of_await: diag(95087, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_uses_of_await_95087", "Remove all unnecessary uses of 'await'"),
9057         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"),
9058         Add_await_to_initializers: diag(95089, ts.DiagnosticCategory.Message, "Add_await_to_initializers_95089", "Add 'await' to initializers"),
9059         Extract_to_interface: diag(95090, ts.DiagnosticCategory.Message, "Extract_to_interface_95090", "Extract to interface"),
9060         Convert_to_a_bigint_numeric_literal: diag(95091, ts.DiagnosticCategory.Message, "Convert_to_a_bigint_numeric_literal_95091", "Convert to a bigint numeric literal"),
9061         Convert_all_to_bigint_numeric_literals: diag(95092, ts.DiagnosticCategory.Message, "Convert_all_to_bigint_numeric_literals_95092", "Convert all to bigint numeric literals"),
9062         Convert_const_to_let: diag(95093, ts.DiagnosticCategory.Message, "Convert_const_to_let_95093", "Convert 'const' to 'let'"),
9063         Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"),
9064         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'"),
9065         Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"),
9066         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"),
9067         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}'"),
9068         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}'"),
9069         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"),
9070         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"),
9071         Add_class_tag: diag(95102, ts.DiagnosticCategory.Message, "Add_class_tag_95102", "Add '@class' tag"),
9072         Add_this_tag: diag(95103, ts.DiagnosticCategory.Message, "Add_this_tag_95103", "Add '@this' tag"),
9073         Add_this_parameter: diag(95104, ts.DiagnosticCategory.Message, "Add_this_parameter_95104", "Add 'this' parameter."),
9074         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"),
9075         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"),
9076         Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"),
9077         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"),
9078         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"),
9079         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"),
9080         Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"),
9081         Remove_braces_from_arrow_function_body: diag(95112, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_body_95112", "Remove braces from arrow function body"),
9082         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"),
9083         Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"),
9084         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"),
9085         Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"),
9086         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"),
9087         Convert_overload_list_to_single_signature: diag(95118, ts.DiagnosticCategory.Message, "Convert_overload_list_to_single_signature_95118", "Convert overload list to single signature"),
9088         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"),
9089         Wrap_in_JSX_fragment: diag(95120, ts.DiagnosticCategory.Message, "Wrap_in_JSX_fragment_95120", "Wrap in JSX fragment"),
9090         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"),
9091         Convert_arrow_function_or_function_expression: diag(95122, ts.DiagnosticCategory.Message, "Convert_arrow_function_or_function_expression_95122", "Convert arrow function or function expression"),
9092         Convert_to_anonymous_function: diag(95123, ts.DiagnosticCategory.Message, "Convert_to_anonymous_function_95123", "Convert to anonymous function"),
9093         Convert_to_named_function: diag(95124, ts.DiagnosticCategory.Message, "Convert_to_named_function_95124", "Convert to named function"),
9094         Convert_to_arrow_function: diag(95125, ts.DiagnosticCategory.Message, "Convert_to_arrow_function_95125", "Convert to arrow function"),
9095         Remove_parentheses: diag(95126, ts.DiagnosticCategory.Message, "Remove_parentheses_95126", "Remove parentheses"),
9096         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"),
9097         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"),
9098         Could_not_find_export_statement: diag(95129, ts.DiagnosticCategory.Message, "Could_not_find_export_statement_95129", "Could not find export statement"),
9099         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"),
9100         Could_not_find_import_clause: diag(95131, ts.DiagnosticCategory.Message, "Could_not_find_import_clause_95131", "Could not find import clause"),
9101         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"),
9102         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"),
9103         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"),
9104         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"),
9105         Name_is_not_valid: diag(95136, ts.DiagnosticCategory.Message, "Name_is_not_valid_95136", "Name is not valid"),
9106         Can_only_convert_property_with_modifier: diag(95137, ts.DiagnosticCategory.Message, "Can_only_convert_property_with_modifier_95137", "Can only convert property with modifier"),
9107         Switch_each_misused_0_to_1: diag(95138, ts.DiagnosticCategory.Message, "Switch_each_misused_0_to_1_95138", "Switch each misused '{0}' to '{1}'"),
9108         Convert_to_optional_chain_expression: diag(95139, ts.DiagnosticCategory.Message, "Convert_to_optional_chain_expression_95139", "Convert to optional chain expression"),
9109         Could_not_find_convertible_access_expression: diag(95140, ts.DiagnosticCategory.Message, "Could_not_find_convertible_access_expression_95140", "Could not find convertible access expression"),
9110         Could_not_find_matching_access_expressions: diag(95141, ts.DiagnosticCategory.Message, "Could_not_find_matching_access_expressions_95141", "Could not find matching access expressions"),
9111         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"),
9112         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"),
9113         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"),
9114         Use_element_access_for_0: diag(95145, ts.DiagnosticCategory.Message, "Use_element_access_for_0_95145", "Use element access for '{0}'"),
9115         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."),
9116         Delete_all_unused_imports: diag(95147, ts.DiagnosticCategory.Message, "Delete_all_unused_imports_95147", "Delete all unused imports"),
9117         Infer_function_return_type: diag(95148, ts.DiagnosticCategory.Message, "Infer_function_return_type_95148", "Infer function return type"),
9118         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"),
9119         Could_not_determine_function_return_type: diag(95150, ts.DiagnosticCategory.Message, "Could_not_determine_function_return_type_95150", "Could not determine function return type"),
9120         Could_not_convert_to_arrow_function: diag(95151, ts.DiagnosticCategory.Message, "Could_not_convert_to_arrow_function_95151", "Could not convert to arrow function"),
9121         Could_not_convert_to_named_function: diag(95152, ts.DiagnosticCategory.Message, "Could_not_convert_to_named_function_95152", "Could not convert to named function"),
9122         Could_not_convert_to_anonymous_function: diag(95153, ts.DiagnosticCategory.Message, "Could_not_convert_to_anonymous_function_95153", "Could not convert to anonymous function"),
9123         Can_only_convert_string_concatenation: diag(95154, ts.DiagnosticCategory.Message, "Can_only_convert_string_concatenation_95154", "Can only convert string concatenation"),
9124         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"),
9125         Add_missing_function_declaration_0: diag(95156, ts.DiagnosticCategory.Message, "Add_missing_function_declaration_0_95156", "Add missing function declaration '{0}'"),
9126         Add_all_missing_function_declarations: diag(95157, ts.DiagnosticCategory.Message, "Add_all_missing_function_declarations_95157", "Add all missing function declarations"),
9127         Method_not_implemented: diag(95158, ts.DiagnosticCategory.Message, "Method_not_implemented_95158", "Method not implemented."),
9128         Function_not_implemented: diag(95159, ts.DiagnosticCategory.Message, "Function_not_implemented_95159", "Function not implemented."),
9129         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."),
9130         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'."),
9131         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?"),
9132         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."),
9133         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."),
9134         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."),
9135         constructor_is_a_reserved_word: diag(18012, ts.DiagnosticCategory.Error, "constructor_is_a_reserved_word_18012", "'#constructor' is a reserved word."),
9136         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."),
9137         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."),
9138         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}'."),
9139         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."),
9140         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"),
9141         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"),
9142         _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."),
9143         A_method_cannot_be_named_with_a_private_identifier: diag(18022, ts.DiagnosticCategory.Error, "A_method_cannot_be_named_with_a_private_identifier_18022", "A method cannot be named with a private identifier."),
9144         An_accessor_cannot_be_named_with_a_private_identifier: diag(18023, ts.DiagnosticCategory.Error, "An_accessor_cannot_be_named_with_a_private_identifier_18023", "An accessor cannot be named with a private identifier."),
9145         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."),
9146         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."),
9147         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."),
9148         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."),
9149         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."),
9150         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."),
9151         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."),
9152         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."),
9153         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."),
9154         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'."),
9155         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."),
9156     };
9157 })(ts || (ts = {}));
9158 var ts;
9159 (function (ts) {
9160     var _a;
9161     /* @internal */
9162     function tokenIsIdentifierOrKeyword(token) {
9163         return token >= 78 /* Identifier */;
9164     }
9165     ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
9166     /* @internal */
9167     function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
9168         return token === 31 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
9169     }
9170     ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
9171     var textToKeywordObj = (_a = {
9172             abstract: 125 /* AbstractKeyword */,
9173             any: 128 /* AnyKeyword */,
9174             as: 126 /* AsKeyword */,
9175             asserts: 127 /* AssertsKeyword */,
9176             bigint: 155 /* BigIntKeyword */,
9177             boolean: 131 /* BooleanKeyword */,
9178             break: 80 /* BreakKeyword */,
9179             case: 81 /* CaseKeyword */,
9180             catch: 82 /* CatchKeyword */,
9181             class: 83 /* ClassKeyword */,
9182             continue: 85 /* ContinueKeyword */,
9183             const: 84 /* ConstKeyword */
9184         },
9185         _a["" + "constructor"] = 132 /* ConstructorKeyword */,
9186         _a.debugger = 86 /* DebuggerKeyword */,
9187         _a.declare = 133 /* DeclareKeyword */,
9188         _a.default = 87 /* DefaultKeyword */,
9189         _a.delete = 88 /* DeleteKeyword */,
9190         _a.do = 89 /* DoKeyword */,
9191         _a.else = 90 /* ElseKeyword */,
9192         _a.enum = 91 /* EnumKeyword */,
9193         _a.export = 92 /* ExportKeyword */,
9194         _a.extends = 93 /* ExtendsKeyword */,
9195         _a.false = 94 /* FalseKeyword */,
9196         _a.finally = 95 /* FinallyKeyword */,
9197         _a.for = 96 /* ForKeyword */,
9198         _a.from = 153 /* FromKeyword */,
9199         _a.function = 97 /* FunctionKeyword */,
9200         _a.get = 134 /* GetKeyword */,
9201         _a.if = 98 /* IfKeyword */,
9202         _a.implements = 116 /* ImplementsKeyword */,
9203         _a.import = 99 /* ImportKeyword */,
9204         _a.in = 100 /* InKeyword */,
9205         _a.infer = 135 /* InferKeyword */,
9206         _a.instanceof = 101 /* InstanceOfKeyword */,
9207         _a.interface = 117 /* InterfaceKeyword */,
9208         _a.intrinsic = 136 /* IntrinsicKeyword */,
9209         _a.is = 137 /* IsKeyword */,
9210         _a.keyof = 138 /* KeyOfKeyword */,
9211         _a.let = 118 /* LetKeyword */,
9212         _a.module = 139 /* ModuleKeyword */,
9213         _a.namespace = 140 /* NamespaceKeyword */,
9214         _a.never = 141 /* NeverKeyword */,
9215         _a.new = 102 /* NewKeyword */,
9216         _a.null = 103 /* NullKeyword */,
9217         _a.number = 144 /* NumberKeyword */,
9218         _a.object = 145 /* ObjectKeyword */,
9219         _a.package = 119 /* PackageKeyword */,
9220         _a.private = 120 /* PrivateKeyword */,
9221         _a.protected = 121 /* ProtectedKeyword */,
9222         _a.public = 122 /* PublicKeyword */,
9223         _a.readonly = 142 /* ReadonlyKeyword */,
9224         _a.require = 143 /* RequireKeyword */,
9225         _a.global = 154 /* GlobalKeyword */,
9226         _a.return = 104 /* ReturnKeyword */,
9227         _a.set = 146 /* SetKeyword */,
9228         _a.static = 123 /* StaticKeyword */,
9229         _a.string = 147 /* StringKeyword */,
9230         _a.super = 105 /* SuperKeyword */,
9231         _a.switch = 106 /* SwitchKeyword */,
9232         _a.symbol = 148 /* SymbolKeyword */,
9233         _a.this = 107 /* ThisKeyword */,
9234         _a.throw = 108 /* ThrowKeyword */,
9235         _a.true = 109 /* TrueKeyword */,
9236         _a.try = 110 /* TryKeyword */,
9237         _a.type = 149 /* TypeKeyword */,
9238         _a.typeof = 111 /* TypeOfKeyword */,
9239         _a.undefined = 150 /* UndefinedKeyword */,
9240         _a.unique = 151 /* UniqueKeyword */,
9241         _a.unknown = 152 /* UnknownKeyword */,
9242         _a.var = 112 /* VarKeyword */,
9243         _a.void = 113 /* VoidKeyword */,
9244         _a.while = 114 /* WhileKeyword */,
9245         _a.with = 115 /* WithKeyword */,
9246         _a.yield = 124 /* YieldKeyword */,
9247         _a.async = 129 /* AsyncKeyword */,
9248         _a.await = 130 /* AwaitKeyword */,
9249         _a.of = 156 /* OfKeyword */,
9250         _a);
9251     var textToKeyword = new ts.Map(ts.getEntries(textToKeywordObj));
9252     var textToToken = new ts.Map(ts.getEntries(__assign(__assign({}, textToKeywordObj), { "{": 18 /* OpenBraceToken */, "}": 19 /* CloseBraceToken */, "(": 20 /* OpenParenToken */, ")": 21 /* CloseParenToken */, "[": 22 /* OpenBracketToken */, "]": 23 /* CloseBracketToken */, ".": 24 /* DotToken */, "...": 25 /* DotDotDotToken */, ";": 26 /* SemicolonToken */, ",": 27 /* CommaToken */, "<": 29 /* LessThanToken */, ">": 31 /* GreaterThanToken */, "<=": 32 /* LessThanEqualsToken */, ">=": 33 /* GreaterThanEqualsToken */, "==": 34 /* EqualsEqualsToken */, "!=": 35 /* ExclamationEqualsToken */, "===": 36 /* EqualsEqualsEqualsToken */, "!==": 37 /* ExclamationEqualsEqualsToken */, "=>": 38 /* EqualsGreaterThanToken */, "+": 39 /* PlusToken */, "-": 40 /* MinusToken */, "**": 42 /* AsteriskAsteriskToken */, "*": 41 /* AsteriskToken */, "/": 43 /* SlashToken */, "%": 44 /* PercentToken */, "++": 45 /* PlusPlusToken */, "--": 46 /* MinusMinusToken */, "<<": 47 /* LessThanLessThanToken */, "</": 30 /* LessThanSlashToken */, ">>": 48 /* GreaterThanGreaterThanToken */, ">>>": 49 /* GreaterThanGreaterThanGreaterThanToken */, "&": 50 /* AmpersandToken */, "|": 51 /* BarToken */, "^": 52 /* CaretToken */, "!": 53 /* ExclamationToken */, "~": 54 /* TildeToken */, "&&": 55 /* AmpersandAmpersandToken */, "||": 56 /* BarBarToken */, "?": 57 /* QuestionToken */, "??": 60 /* QuestionQuestionToken */, "?.": 28 /* QuestionDotToken */, ":": 58 /* ColonToken */, "=": 62 /* EqualsToken */, "+=": 63 /* PlusEqualsToken */, "-=": 64 /* MinusEqualsToken */, "*=": 65 /* AsteriskEqualsToken */, "**=": 66 /* AsteriskAsteriskEqualsToken */, "/=": 67 /* SlashEqualsToken */, "%=": 68 /* PercentEqualsToken */, "<<=": 69 /* LessThanLessThanEqualsToken */, ">>=": 70 /* GreaterThanGreaterThanEqualsToken */, ">>>=": 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */, "&=": 72 /* AmpersandEqualsToken */, "|=": 73 /* BarEqualsToken */, "^=": 77 /* CaretEqualsToken */, "||=": 74 /* BarBarEqualsToken */, "&&=": 75 /* AmpersandAmpersandEqualsToken */, "??=": 76 /* QuestionQuestionEqualsToken */, "@": 59 /* AtToken */, "`": 61 /* BacktickToken */ })));
9253     /*
9254         As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
9255         IdentifierStart ::
9256             Can contain Unicode 3.0.0 categories:
9257             Uppercase letter (Lu),
9258             Lowercase letter (Ll),
9259             Titlecase letter (Lt),
9260             Modifier letter (Lm),
9261             Other letter (Lo), or
9262             Letter number (Nl).
9263         IdentifierPart :: =
9264             Can contain IdentifierStart + Unicode 3.0.0 categories:
9265             Non-spacing mark (Mn),
9266             Combining spacing mark (Mc),
9267             Decimal number (Nd), or
9268             Connector punctuation (Pc).
9269
9270         Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
9271         http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
9272     */
9273     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,];
9274     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,];
9275     /*
9276         As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers
9277         IdentifierStart ::
9278             Can contain Unicode 6.2 categories:
9279             Uppercase letter (Lu),
9280             Lowercase letter (Ll),
9281             Titlecase letter (Lt),
9282             Modifier letter (Lm),
9283             Other letter (Lo), or
9284             Letter number (Nl).
9285         IdentifierPart ::
9286             Can contain IdentifierStart + Unicode 6.2 categories:
9287             Non-spacing mark (Mn),
9288             Combining spacing mark (Mc),
9289             Decimal number (Nd),
9290             Connector punctuation (Pc),
9291             <ZWNJ>, or
9292             <ZWJ>.
9293
9294         Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at:
9295         http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
9296     */
9297     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,];
9298     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,];
9299     /**
9300      * Generated by scripts/regenerate-unicode-identifier-parts.js on node v12.4.0 with unicode 12.1
9301      * based on http://www.unicode.org/reports/tr31/ and https://www.ecma-international.org/ecma-262/6.0/#sec-names-and-keywords
9302      * unicodeESNextIdentifierStart corresponds to the ID_Start and Other_ID_Start property, and
9303      * unicodeESNextIdentifierPart corresponds to ID_Continue, Other_ID_Continue, plus ID_Start and Other_ID_Start
9304      */
9305     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];
9306     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];
9307     /**
9308      * Test for whether a single line comment's text contains a directive.
9309      */
9310     var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/;
9311     /**
9312      * Test for whether a multi-line comment's last line contains a directive.
9313      */
9314     var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/;
9315     function lookupInUnicodeMap(code, map) {
9316         // Bail out quickly if it couldn't possibly be in the map.
9317         if (code < map[0]) {
9318             return false;
9319         }
9320         // Perform binary search in one of the Unicode range maps
9321         var lo = 0;
9322         var hi = map.length;
9323         var mid;
9324         while (lo + 1 < hi) {
9325             mid = lo + (hi - lo) / 2;
9326             // mid has to be even to catch a range's beginning
9327             mid -= mid % 2;
9328             if (map[mid] <= code && code <= map[mid + 1]) {
9329                 return true;
9330             }
9331             if (code < map[mid]) {
9332                 hi = mid;
9333             }
9334             else {
9335                 lo = mid + 2;
9336             }
9337         }
9338         return false;
9339     }
9340     /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
9341         return languageVersion >= 2 /* ES2015 */ ?
9342             lookupInUnicodeMap(code, unicodeESNextIdentifierStart) :
9343             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
9344                 lookupInUnicodeMap(code, unicodeES3IdentifierStart);
9345     }
9346     ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
9347     function isUnicodeIdentifierPart(code, languageVersion) {
9348         return languageVersion >= 2 /* ES2015 */ ?
9349             lookupInUnicodeMap(code, unicodeESNextIdentifierPart) :
9350             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
9351                 lookupInUnicodeMap(code, unicodeES3IdentifierPart);
9352     }
9353     function makeReverseMap(source) {
9354         var result = [];
9355         source.forEach(function (value, name) {
9356             result[value] = name;
9357         });
9358         return result;
9359     }
9360     var tokenStrings = makeReverseMap(textToToken);
9361     function tokenToString(t) {
9362         return tokenStrings[t];
9363     }
9364     ts.tokenToString = tokenToString;
9365     /* @internal */
9366     function stringToToken(s) {
9367         return textToToken.get(s);
9368     }
9369     ts.stringToToken = stringToToken;
9370     /* @internal */
9371     function computeLineStarts(text) {
9372         var result = new Array();
9373         var pos = 0;
9374         var lineStart = 0;
9375         while (pos < text.length) {
9376             var ch = text.charCodeAt(pos);
9377             pos++;
9378             switch (ch) {
9379                 case 13 /* carriageReturn */:
9380                     if (text.charCodeAt(pos) === 10 /* lineFeed */) {
9381                         pos++;
9382                     }
9383                 // falls through
9384                 case 10 /* lineFeed */:
9385                     result.push(lineStart);
9386                     lineStart = pos;
9387                     break;
9388                 default:
9389                     if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
9390                         result.push(lineStart);
9391                         lineStart = pos;
9392                     }
9393                     break;
9394             }
9395         }
9396         result.push(lineStart);
9397         return result;
9398     }
9399     ts.computeLineStarts = computeLineStarts;
9400     function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) {
9401         return sourceFile.getPositionOfLineAndCharacter ?
9402             sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) :
9403             computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits);
9404     }
9405     ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
9406     /* @internal */
9407     function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
9408         if (line < 0 || line >= lineStarts.length) {
9409             if (allowEdits) {
9410                 // Clamp line to nearest allowable value
9411                 line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
9412             }
9413             else {
9414                 ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
9415             }
9416         }
9417         var res = lineStarts[line] + character;
9418         if (allowEdits) {
9419             // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
9420             // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
9421             // apply them to the computed position to improve accuracy
9422             return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
9423         }
9424         if (line < lineStarts.length - 1) {
9425             ts.Debug.assert(res < lineStarts[line + 1]);
9426         }
9427         else if (debugText !== undefined) {
9428             ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
9429         }
9430         return res;
9431     }
9432     ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
9433     /* @internal */
9434     function getLineStarts(sourceFile) {
9435         return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
9436     }
9437     ts.getLineStarts = getLineStarts;
9438     /* @internal */
9439     function computeLineAndCharacterOfPosition(lineStarts, position) {
9440         var lineNumber = computeLineOfPosition(lineStarts, position);
9441         return {
9442             line: lineNumber,
9443             character: position - lineStarts[lineNumber]
9444         };
9445     }
9446     ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
9447     /**
9448      * @internal
9449      * We assume the first line starts at position 0 and 'position' is non-negative.
9450      */
9451     function computeLineOfPosition(lineStarts, position, lowerBound) {
9452         var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues, lowerBound);
9453         if (lineNumber < 0) {
9454             // If the actual position was not found,
9455             // the binary search returns the 2's-complement of the next line start
9456             // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
9457             // then the search will return -2.
9458             //
9459             // We want the index of the previous line start, so we subtract 1.
9460             // Review 2's-complement if this is confusing.
9461             lineNumber = ~lineNumber - 1;
9462             ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
9463         }
9464         return lineNumber;
9465     }
9466     ts.computeLineOfPosition = computeLineOfPosition;
9467     /** @internal */
9468     function getLinesBetweenPositions(sourceFile, pos1, pos2) {
9469         if (pos1 === pos2)
9470             return 0;
9471         var lineStarts = getLineStarts(sourceFile);
9472         var lower = Math.min(pos1, pos2);
9473         var isNegative = lower === pos2;
9474         var upper = isNegative ? pos1 : pos2;
9475         var lowerLine = computeLineOfPosition(lineStarts, lower);
9476         var upperLine = computeLineOfPosition(lineStarts, upper, lowerLine);
9477         return isNegative ? lowerLine - upperLine : upperLine - lowerLine;
9478     }
9479     ts.getLinesBetweenPositions = getLinesBetweenPositions;
9480     function getLineAndCharacterOfPosition(sourceFile, position) {
9481         return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
9482     }
9483     ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
9484     function isWhiteSpaceLike(ch) {
9485         return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
9486     }
9487     ts.isWhiteSpaceLike = isWhiteSpaceLike;
9488     /** Does not include line breaks. For that, see isWhiteSpaceLike. */
9489     function isWhiteSpaceSingleLine(ch) {
9490         // Note: nextLine is in the Zs space, and should be considered to be a whitespace.
9491         // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
9492         return ch === 32 /* space */ ||
9493             ch === 9 /* tab */ ||
9494             ch === 11 /* verticalTab */ ||
9495             ch === 12 /* formFeed */ ||
9496             ch === 160 /* nonBreakingSpace */ ||
9497             ch === 133 /* nextLine */ ||
9498             ch === 5760 /* ogham */ ||
9499             ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
9500             ch === 8239 /* narrowNoBreakSpace */ ||
9501             ch === 8287 /* mathematicalSpace */ ||
9502             ch === 12288 /* ideographicSpace */ ||
9503             ch === 65279 /* byteOrderMark */;
9504     }
9505     ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine;
9506     function isLineBreak(ch) {
9507         // ES5 7.3:
9508         // The ECMAScript line terminator characters are listed in Table 3.
9509         //     Table 3: Line Terminator Characters
9510         //     Code Unit Value     Name                    Formal Name
9511         //     \u000A              Line Feed               <LF>
9512         //     \u000D              Carriage Return         <CR>
9513         //     \u2028              Line separator          <LS>
9514         //     \u2029              Paragraph separator     <PS>
9515         // Only the characters in Table 3 are treated as line terminators. Other new line or line
9516         // breaking characters are treated as white space but not as line terminators.
9517         return ch === 10 /* lineFeed */ ||
9518             ch === 13 /* carriageReturn */ ||
9519             ch === 8232 /* lineSeparator */ ||
9520             ch === 8233 /* paragraphSeparator */;
9521     }
9522     ts.isLineBreak = isLineBreak;
9523     function isDigit(ch) {
9524         return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
9525     }
9526     function isHexDigit(ch) {
9527         return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */;
9528     }
9529     function isCodePoint(code) {
9530         return code <= 0x10FFFF;
9531     }
9532     /* @internal */
9533     function isOctalDigit(ch) {
9534         return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
9535     }
9536     ts.isOctalDigit = isOctalDigit;
9537     function couldStartTrivia(text, pos) {
9538         // Keep in sync with skipTrivia
9539         var ch = text.charCodeAt(pos);
9540         switch (ch) {
9541             case 13 /* carriageReturn */:
9542             case 10 /* lineFeed */:
9543             case 9 /* tab */:
9544             case 11 /* verticalTab */:
9545             case 12 /* formFeed */:
9546             case 32 /* space */:
9547             case 47 /* slash */:
9548             // starts of normal trivia
9549             // falls through
9550             case 60 /* lessThan */:
9551             case 124 /* bar */:
9552             case 61 /* equals */:
9553             case 62 /* greaterThan */:
9554                 // Starts of conflict marker trivia
9555                 return true;
9556             case 35 /* hash */:
9557                 // Only if its the beginning can we have #! trivia
9558                 return pos === 0;
9559             default:
9560                 return ch > 127 /* maxAsciiCharacter */;
9561         }
9562     }
9563     ts.couldStartTrivia = couldStartTrivia;
9564     /* @internal */
9565     function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) {
9566         if (stopAtComments === void 0) { stopAtComments = false; }
9567         if (ts.positionIsSynthesized(pos)) {
9568             return pos;
9569         }
9570         // Keep in sync with couldStartTrivia
9571         while (true) {
9572             var ch = text.charCodeAt(pos);
9573             switch (ch) {
9574                 case 13 /* carriageReturn */:
9575                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
9576                         pos++;
9577                     }
9578                 // falls through
9579                 case 10 /* lineFeed */:
9580                     pos++;
9581                     if (stopAfterLineBreak) {
9582                         return pos;
9583                     }
9584                     continue;
9585                 case 9 /* tab */:
9586                 case 11 /* verticalTab */:
9587                 case 12 /* formFeed */:
9588                 case 32 /* space */:
9589                     pos++;
9590                     continue;
9591                 case 47 /* slash */:
9592                     if (stopAtComments) {
9593                         break;
9594                     }
9595                     if (text.charCodeAt(pos + 1) === 47 /* slash */) {
9596                         pos += 2;
9597                         while (pos < text.length) {
9598                             if (isLineBreak(text.charCodeAt(pos))) {
9599                                 break;
9600                             }
9601                             pos++;
9602                         }
9603                         continue;
9604                     }
9605                     if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9606                         pos += 2;
9607                         while (pos < text.length) {
9608                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
9609                                 pos += 2;
9610                                 break;
9611                             }
9612                             pos++;
9613                         }
9614                         continue;
9615                     }
9616                     break;
9617                 case 60 /* lessThan */:
9618                 case 124 /* bar */:
9619                 case 61 /* equals */:
9620                 case 62 /* greaterThan */:
9621                     if (isConflictMarkerTrivia(text, pos)) {
9622                         pos = scanConflictMarkerTrivia(text, pos);
9623                         continue;
9624                     }
9625                     break;
9626                 case 35 /* hash */:
9627                     if (pos === 0 && isShebangTrivia(text, pos)) {
9628                         pos = scanShebangTrivia(text, pos);
9629                         continue;
9630                     }
9631                     break;
9632                 default:
9633                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
9634                         pos++;
9635                         continue;
9636                     }
9637                     break;
9638             }
9639             return pos;
9640         }
9641     }
9642     ts.skipTrivia = skipTrivia;
9643     // All conflict markers consist of the same character repeated seven times.  If it is
9644     // a <<<<<<< or >>>>>>> marker then it is also followed by a space.
9645     var mergeConflictMarkerLength = "<<<<<<<".length;
9646     function isConflictMarkerTrivia(text, pos) {
9647         ts.Debug.assert(pos >= 0);
9648         // Conflict markers must be at the start of a line.
9649         if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
9650             var ch = text.charCodeAt(pos);
9651             if ((pos + mergeConflictMarkerLength) < text.length) {
9652                 for (var i = 0; i < mergeConflictMarkerLength; i++) {
9653                     if (text.charCodeAt(pos + i) !== ch) {
9654                         return false;
9655                     }
9656                 }
9657                 return ch === 61 /* equals */ ||
9658                     text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
9659             }
9660         }
9661         return false;
9662     }
9663     function scanConflictMarkerTrivia(text, pos, error) {
9664         if (error) {
9665             error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
9666         }
9667         var ch = text.charCodeAt(pos);
9668         var len = text.length;
9669         if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
9670             while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
9671                 pos++;
9672             }
9673         }
9674         else {
9675             ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
9676             // Consume everything from the start of a ||||||| or ======= marker to the start
9677             // of the next ======= or >>>>>>> marker.
9678             while (pos < len) {
9679                 var currentChar = text.charCodeAt(pos);
9680                 if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
9681                     break;
9682                 }
9683                 pos++;
9684             }
9685         }
9686         return pos;
9687     }
9688     var shebangTriviaRegex = /^#!.*/;
9689     /*@internal*/
9690     function isShebangTrivia(text, pos) {
9691         // Shebangs check must only be done at the start of the file
9692         ts.Debug.assert(pos === 0);
9693         return shebangTriviaRegex.test(text);
9694     }
9695     ts.isShebangTrivia = isShebangTrivia;
9696     /*@internal*/
9697     function scanShebangTrivia(text, pos) {
9698         var shebang = shebangTriviaRegex.exec(text)[0];
9699         pos = pos + shebang.length;
9700         return pos;
9701     }
9702     ts.scanShebangTrivia = scanShebangTrivia;
9703     /**
9704      * Invokes a callback for each comment range following the provided position.
9705      *
9706      * Single-line comment ranges include the leading double-slash characters but not the ending
9707      * line break. Multi-line comment ranges include the leading slash-asterisk and trailing
9708      * asterisk-slash characters.
9709      *
9710      * @param reduce If true, accumulates the result of calling the callback in a fashion similar
9711      *      to reduceLeft. If false, iteration stops when the callback returns a truthy value.
9712      * @param text The source text to scan.
9713      * @param pos The position at which to start scanning.
9714      * @param trailing If false, whitespace is skipped until the first line break and comments
9715      *      between that location and the next token are returned. If true, comments occurring
9716      *      between the given position and the next line break are returned.
9717      * @param cb The callback to execute as each comment range is encountered.
9718      * @param state A state value to pass to each iteration of the callback.
9719      * @param initial An initial value to pass when accumulating results (when "reduce" is true).
9720      * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
9721      *      return value of the callback.
9722      */
9723     function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
9724         var pendingPos;
9725         var pendingEnd;
9726         var pendingKind;
9727         var pendingHasTrailingNewLine;
9728         var hasPendingCommentRange = false;
9729         var collecting = trailing;
9730         var accumulator = initial;
9731         if (pos === 0) {
9732             collecting = true;
9733             var shebang = getShebang(text);
9734             if (shebang) {
9735                 pos = shebang.length;
9736             }
9737         }
9738         scan: while (pos >= 0 && pos < text.length) {
9739             var ch = text.charCodeAt(pos);
9740             switch (ch) {
9741                 case 13 /* carriageReturn */:
9742                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
9743                         pos++;
9744                     }
9745                 // falls through
9746                 case 10 /* lineFeed */:
9747                     pos++;
9748                     if (trailing) {
9749                         break scan;
9750                     }
9751                     collecting = true;
9752                     if (hasPendingCommentRange) {
9753                         pendingHasTrailingNewLine = true;
9754                     }
9755                     continue;
9756                 case 9 /* tab */:
9757                 case 11 /* verticalTab */:
9758                 case 12 /* formFeed */:
9759                 case 32 /* space */:
9760                     pos++;
9761                     continue;
9762                 case 47 /* slash */:
9763                     var nextChar = text.charCodeAt(pos + 1);
9764                     var hasTrailingNewLine = false;
9765                     if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
9766                         var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
9767                         var startPos = pos;
9768                         pos += 2;
9769                         if (nextChar === 47 /* slash */) {
9770                             while (pos < text.length) {
9771                                 if (isLineBreak(text.charCodeAt(pos))) {
9772                                     hasTrailingNewLine = true;
9773                                     break;
9774                                 }
9775                                 pos++;
9776                             }
9777                         }
9778                         else {
9779                             while (pos < text.length) {
9780                                 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
9781                                     pos += 2;
9782                                     break;
9783                                 }
9784                                 pos++;
9785                             }
9786                         }
9787                         if (collecting) {
9788                             if (hasPendingCommentRange) {
9789                                 accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
9790                                 if (!reduce && accumulator) {
9791                                     // If we are not reducing and we have a truthy result, return it.
9792                                     return accumulator;
9793                                 }
9794                             }
9795                             pendingPos = startPos;
9796                             pendingEnd = pos;
9797                             pendingKind = kind;
9798                             pendingHasTrailingNewLine = hasTrailingNewLine;
9799                             hasPendingCommentRange = true;
9800                         }
9801                         continue;
9802                     }
9803                     break scan;
9804                 default:
9805                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
9806                         if (hasPendingCommentRange && isLineBreak(ch)) {
9807                             pendingHasTrailingNewLine = true;
9808                         }
9809                         pos++;
9810                         continue;
9811                     }
9812                     break scan;
9813             }
9814         }
9815         if (hasPendingCommentRange) {
9816             accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
9817         }
9818         return accumulator;
9819     }
9820     function forEachLeadingCommentRange(text, pos, cb, state) {
9821         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
9822     }
9823     ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
9824     function forEachTrailingCommentRange(text, pos, cb, state) {
9825         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
9826     }
9827     ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
9828     function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
9829         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
9830     }
9831     ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange;
9832     function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
9833         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
9834     }
9835     ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
9836     function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
9837         if (!comments) {
9838             comments = [];
9839         }
9840         comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
9841         return comments;
9842     }
9843     function getLeadingCommentRanges(text, pos) {
9844         return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
9845     }
9846     ts.getLeadingCommentRanges = getLeadingCommentRanges;
9847     function getTrailingCommentRanges(text, pos) {
9848         return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
9849     }
9850     ts.getTrailingCommentRanges = getTrailingCommentRanges;
9851     /** Optionally, get the shebang */
9852     function getShebang(text) {
9853         var match = shebangTriviaRegex.exec(text);
9854         if (match) {
9855             return match[0];
9856         }
9857     }
9858     ts.getShebang = getShebang;
9859     function isIdentifierStart(ch, languageVersion) {
9860         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
9861             ch === 36 /* $ */ || ch === 95 /* _ */ ||
9862             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
9863     }
9864     ts.isIdentifierStart = isIdentifierStart;
9865     function isIdentifierPart(ch, languageVersion, identifierVariant) {
9866         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
9867             ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
9868             // "-" and ":" are valid in JSX Identifiers
9869             (identifierVariant === 1 /* JSX */ ? (ch === 45 /* minus */ || ch === 58 /* colon */) : false) ||
9870             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
9871     }
9872     ts.isIdentifierPart = isIdentifierPart;
9873     /* @internal */
9874     function isIdentifierText(name, languageVersion, identifierVariant) {
9875         var ch = codePointAt(name, 0);
9876         if (!isIdentifierStart(ch, languageVersion)) {
9877             return false;
9878         }
9879         for (var i = charSize(ch); i < name.length; i += charSize(ch)) {
9880             if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion, identifierVariant)) {
9881                 return false;
9882             }
9883         }
9884         return true;
9885     }
9886     ts.isIdentifierText = isIdentifierText;
9887     // Creates a scanner over a (possibly unspecified) range of a piece of text.
9888     function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) {
9889         if (languageVariant === void 0) { languageVariant = 0 /* Standard */; }
9890         var text = textInitial;
9891         // Current position (end position of text of current token)
9892         var pos;
9893         // end of text
9894         var end;
9895         // Start position of whitespace before current token
9896         var startPos;
9897         // Start position of text of current token
9898         var tokenPos;
9899         var token;
9900         var tokenValue;
9901         var tokenFlags;
9902         var commentDirectives;
9903         var inJSDocType = 0;
9904         setText(text, start, length);
9905         var scanner = {
9906             getStartPos: function () { return startPos; },
9907             getTextPos: function () { return pos; },
9908             getToken: function () { return token; },
9909             getTokenPos: function () { return tokenPos; },
9910             getTokenText: function () { return text.substring(tokenPos, pos); },
9911             getTokenValue: function () { return tokenValue; },
9912             hasUnicodeEscape: function () { return (tokenFlags & 1024 /* UnicodeEscape */) !== 0; },
9913             hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
9914             hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
9915             hasPrecedingJSDocComment: function () { return (tokenFlags & 2 /* PrecedingJSDocComment */) !== 0; },
9916             isIdentifier: function () { return token === 78 /* Identifier */ || token > 115 /* LastReservedWord */; },
9917             isReservedWord: function () { return token >= 80 /* FirstReservedWord */ && token <= 115 /* LastReservedWord */; },
9918             isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
9919             getCommentDirectives: function () { return commentDirectives; },
9920             getNumericLiteralFlags: function () { return tokenFlags & 1008 /* NumericLiteralFlags */; },
9921             getTokenFlags: function () { return tokenFlags; },
9922             reScanGreaterToken: reScanGreaterToken,
9923             reScanAsteriskEqualsToken: reScanAsteriskEqualsToken,
9924             reScanSlashToken: reScanSlashToken,
9925             reScanTemplateToken: reScanTemplateToken,
9926             reScanTemplateHeadOrNoSubstitutionTemplate: reScanTemplateHeadOrNoSubstitutionTemplate,
9927             scanJsxIdentifier: scanJsxIdentifier,
9928             scanJsxAttributeValue: scanJsxAttributeValue,
9929             reScanJsxAttributeValue: reScanJsxAttributeValue,
9930             reScanJsxToken: reScanJsxToken,
9931             reScanLessThanToken: reScanLessThanToken,
9932             reScanQuestionToken: reScanQuestionToken,
9933             reScanInvalidIdentifier: reScanInvalidIdentifier,
9934             scanJsxToken: scanJsxToken,
9935             scanJsDocToken: scanJsDocToken,
9936             scan: scan,
9937             getText: getText,
9938             clearCommentDirectives: clearCommentDirectives,
9939             setText: setText,
9940             setScriptTarget: setScriptTarget,
9941             setLanguageVariant: setLanguageVariant,
9942             setOnError: setOnError,
9943             setTextPos: setTextPos,
9944             setInJSDocType: setInJSDocType,
9945             tryScan: tryScan,
9946             lookAhead: lookAhead,
9947             scanRange: scanRange,
9948         };
9949         if (ts.Debug.isDebugging) {
9950             Object.defineProperty(scanner, "__debugShowCurrentPositionInText", {
9951                 get: function () {
9952                     var text = scanner.getText();
9953                     return text.slice(0, scanner.getStartPos()) + "â•‘" + text.slice(scanner.getStartPos());
9954                 },
9955             });
9956         }
9957         return scanner;
9958         function error(message, errPos, length) {
9959             if (errPos === void 0) { errPos = pos; }
9960             if (onError) {
9961                 var oldPos = pos;
9962                 pos = errPos;
9963                 onError(message, length || 0);
9964                 pos = oldPos;
9965             }
9966         }
9967         function scanNumberFragment() {
9968             var start = pos;
9969             var allowSeparator = false;
9970             var isPreviousTokenSeparator = false;
9971             var result = "";
9972             while (true) {
9973                 var ch = text.charCodeAt(pos);
9974                 if (ch === 95 /* _ */) {
9975                     tokenFlags |= 512 /* ContainsSeparator */;
9976                     if (allowSeparator) {
9977                         allowSeparator = false;
9978                         isPreviousTokenSeparator = true;
9979                         result += text.substring(start, pos);
9980                     }
9981                     else if (isPreviousTokenSeparator) {
9982                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9983                     }
9984                     else {
9985                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9986                     }
9987                     pos++;
9988                     start = pos;
9989                     continue;
9990                 }
9991                 if (isDigit(ch)) {
9992                     allowSeparator = true;
9993                     isPreviousTokenSeparator = false;
9994                     pos++;
9995                     continue;
9996                 }
9997                 break;
9998             }
9999             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
10000                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
10001             }
10002             return result + text.substring(start, pos);
10003         }
10004         function scanNumber() {
10005             var start = pos;
10006             var mainFragment = scanNumberFragment();
10007             var decimalFragment;
10008             var scientificFragment;
10009             if (text.charCodeAt(pos) === 46 /* dot */) {
10010                 pos++;
10011                 decimalFragment = scanNumberFragment();
10012             }
10013             var end = pos;
10014             if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
10015                 pos++;
10016                 tokenFlags |= 16 /* Scientific */;
10017                 if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
10018                     pos++;
10019                 var preNumericPart = pos;
10020                 var finalFragment = scanNumberFragment();
10021                 if (!finalFragment) {
10022                     error(ts.Diagnostics.Digit_expected);
10023                 }
10024                 else {
10025                     scientificFragment = text.substring(end, preNumericPart) + finalFragment;
10026                     end = pos;
10027                 }
10028             }
10029             var result;
10030             if (tokenFlags & 512 /* ContainsSeparator */) {
10031                 result = mainFragment;
10032                 if (decimalFragment) {
10033                     result += "." + decimalFragment;
10034                 }
10035                 if (scientificFragment) {
10036                     result += scientificFragment;
10037                 }
10038             }
10039             else {
10040                 result = text.substring(start, end); // No need to use all the fragments; no _ removal needed
10041             }
10042             if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) {
10043                 checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */));
10044                 return {
10045                     type: 8 /* NumericLiteral */,
10046                     value: "" + +result // if value is not an integer, it can be safely coerced to a number
10047                 };
10048             }
10049             else {
10050                 tokenValue = result;
10051                 var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint
10052                 checkForIdentifierStartAfterNumericLiteral(start);
10053                 return { type: type, value: tokenValue };
10054             }
10055         }
10056         function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) {
10057             if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) {
10058                 return;
10059             }
10060             var identifierStart = pos;
10061             var length = scanIdentifierParts().length;
10062             if (length === 1 && text[identifierStart] === "n") {
10063                 if (isScientific) {
10064                     error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1);
10065                 }
10066                 else {
10067                     error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1);
10068                 }
10069             }
10070             else {
10071                 error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length);
10072                 pos = identifierStart;
10073             }
10074         }
10075         function scanOctalDigits() {
10076             var start = pos;
10077             while (isOctalDigit(text.charCodeAt(pos))) {
10078                 pos++;
10079             }
10080             return +(text.substring(start, pos));
10081         }
10082         /**
10083          * Scans the given number of hexadecimal digits in the text,
10084          * returning -1 if the given number is unavailable.
10085          */
10086         function scanExactNumberOfHexDigits(count, canHaveSeparators) {
10087             var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
10088             return valueString ? parseInt(valueString, 16) : -1;
10089         }
10090         /**
10091          * Scans as many hexadecimal digits as are available in the text,
10092          * returning "" if the given number of digits was unavailable.
10093          */
10094         function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
10095             return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
10096         }
10097         function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
10098             var valueChars = [];
10099             var allowSeparator = false;
10100             var isPreviousTokenSeparator = false;
10101             while (valueChars.length < minCount || scanAsManyAsPossible) {
10102                 var ch = text.charCodeAt(pos);
10103                 if (canHaveSeparators && ch === 95 /* _ */) {
10104                     tokenFlags |= 512 /* ContainsSeparator */;
10105                     if (allowSeparator) {
10106                         allowSeparator = false;
10107                         isPreviousTokenSeparator = true;
10108                     }
10109                     else if (isPreviousTokenSeparator) {
10110                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
10111                     }
10112                     else {
10113                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
10114                     }
10115                     pos++;
10116                     continue;
10117                 }
10118                 allowSeparator = canHaveSeparators;
10119                 if (ch >= 65 /* A */ && ch <= 70 /* F */) {
10120                     ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase
10121                 }
10122                 else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) ||
10123                     (ch >= 97 /* a */ && ch <= 102 /* f */))) {
10124                     break;
10125                 }
10126                 valueChars.push(ch);
10127                 pos++;
10128                 isPreviousTokenSeparator = false;
10129             }
10130             if (valueChars.length < minCount) {
10131                 valueChars = [];
10132             }
10133             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
10134                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
10135             }
10136             return String.fromCharCode.apply(String, valueChars);
10137         }
10138         function scanString(jsxAttributeString) {
10139             if (jsxAttributeString === void 0) { jsxAttributeString = false; }
10140             var quote = text.charCodeAt(pos);
10141             pos++;
10142             var result = "";
10143             var start = pos;
10144             while (true) {
10145                 if (pos >= end) {
10146                     result += text.substring(start, pos);
10147                     tokenFlags |= 4 /* Unterminated */;
10148                     error(ts.Diagnostics.Unterminated_string_literal);
10149                     break;
10150                 }
10151                 var ch = text.charCodeAt(pos);
10152                 if (ch === quote) {
10153                     result += text.substring(start, pos);
10154                     pos++;
10155                     break;
10156                 }
10157                 if (ch === 92 /* backslash */ && !jsxAttributeString) {
10158                     result += text.substring(start, pos);
10159                     result += scanEscapeSequence();
10160                     start = pos;
10161                     continue;
10162                 }
10163                 if (isLineBreak(ch) && !jsxAttributeString) {
10164                     result += text.substring(start, pos);
10165                     tokenFlags |= 4 /* Unterminated */;
10166                     error(ts.Diagnostics.Unterminated_string_literal);
10167                     break;
10168                 }
10169                 pos++;
10170             }
10171             return result;
10172         }
10173         /**
10174          * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
10175          * a literal component of a TemplateExpression.
10176          */
10177         function scanTemplateAndSetTokenValue(isTaggedTemplate) {
10178             var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
10179             pos++;
10180             var start = pos;
10181             var contents = "";
10182             var resultingToken;
10183             while (true) {
10184                 if (pos >= end) {
10185                     contents += text.substring(start, pos);
10186                     tokenFlags |= 4 /* Unterminated */;
10187                     error(ts.Diagnostics.Unterminated_template_literal);
10188                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
10189                     break;
10190                 }
10191                 var currChar = text.charCodeAt(pos);
10192                 // '`'
10193                 if (currChar === 96 /* backtick */) {
10194                     contents += text.substring(start, pos);
10195                     pos++;
10196                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
10197                     break;
10198                 }
10199                 // '${'
10200                 if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
10201                     contents += text.substring(start, pos);
10202                     pos += 2;
10203                     resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */;
10204                     break;
10205                 }
10206                 // Escape character
10207                 if (currChar === 92 /* backslash */) {
10208                     contents += text.substring(start, pos);
10209                     contents += scanEscapeSequence(isTaggedTemplate);
10210                     start = pos;
10211                     continue;
10212                 }
10213                 // Speculated ECMAScript 6 Spec 11.8.6.1:
10214                 // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values
10215                 if (currChar === 13 /* carriageReturn */) {
10216                     contents += text.substring(start, pos);
10217                     pos++;
10218                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
10219                         pos++;
10220                     }
10221                     contents += "\n";
10222                     start = pos;
10223                     continue;
10224                 }
10225                 pos++;
10226             }
10227             ts.Debug.assert(resultingToken !== undefined);
10228             tokenValue = contents;
10229             return resultingToken;
10230         }
10231         function scanEscapeSequence(isTaggedTemplate) {
10232             var start = pos;
10233             pos++;
10234             if (pos >= end) {
10235                 error(ts.Diagnostics.Unexpected_end_of_text);
10236                 return "";
10237             }
10238             var ch = text.charCodeAt(pos);
10239             pos++;
10240             switch (ch) {
10241                 case 48 /* _0 */:
10242                     // '\01'
10243                     if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) {
10244                         pos++;
10245                         tokenFlags |= 2048 /* ContainsInvalidEscape */;
10246                         return text.substring(start, pos);
10247                     }
10248                     return "\0";
10249                 case 98 /* b */:
10250                     return "\b";
10251                 case 116 /* t */:
10252                     return "\t";
10253                 case 110 /* n */:
10254                     return "\n";
10255                 case 118 /* v */:
10256                     return "\v";
10257                 case 102 /* f */:
10258                     return "\f";
10259                 case 114 /* r */:
10260                     return "\r";
10261                 case 39 /* singleQuote */:
10262                     return "\'";
10263                 case 34 /* doubleQuote */:
10264                     return "\"";
10265                 case 117 /* u */:
10266                     if (isTaggedTemplate) {
10267                         // '\u' or '\u0' or '\u00' or '\u000'
10268                         for (var escapePos = pos; escapePos < pos + 4; escapePos++) {
10269                             if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== 123 /* openBrace */) {
10270                                 pos = escapePos;
10271                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
10272                                 return text.substring(start, pos);
10273                             }
10274                         }
10275                     }
10276                     // '\u{DDDDDDDD}'
10277                     if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
10278                         pos++;
10279                         // '\u{'
10280                         if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) {
10281                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
10282                             return text.substring(start, pos);
10283                         }
10284                         if (isTaggedTemplate) {
10285                             var savePos = pos;
10286                             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
10287                             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
10288                             // '\u{Not Code Point' or '\u{CodePoint'
10289                             if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== 125 /* closeBrace */) {
10290                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
10291                                 return text.substring(start, pos);
10292                             }
10293                             else {
10294                                 pos = savePos;
10295                             }
10296                         }
10297                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10298                         return scanExtendedUnicodeEscape();
10299                     }
10300                     tokenFlags |= 1024 /* UnicodeEscape */;
10301                     // '\uDDDD'
10302                     return scanHexadecimalEscape(/*numDigits*/ 4);
10303                 case 120 /* x */:
10304                     if (isTaggedTemplate) {
10305                         if (!isHexDigit(text.charCodeAt(pos))) {
10306                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
10307                             return text.substring(start, pos);
10308                         }
10309                         else if (!isHexDigit(text.charCodeAt(pos + 1))) {
10310                             pos++;
10311                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
10312                             return text.substring(start, pos);
10313                         }
10314                     }
10315                     // '\xDD'
10316                     return scanHexadecimalEscape(/*numDigits*/ 2);
10317                 // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
10318                 // the line terminator is interpreted to be "the empty code unit sequence".
10319                 case 13 /* carriageReturn */:
10320                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
10321                         pos++;
10322                     }
10323                 // falls through
10324                 case 10 /* lineFeed */:
10325                 case 8232 /* lineSeparator */:
10326                 case 8233 /* paragraphSeparator */:
10327                     return "";
10328                 default:
10329                     return String.fromCharCode(ch);
10330             }
10331         }
10332         function scanHexadecimalEscape(numDigits) {
10333             var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
10334             if (escapedValue >= 0) {
10335                 return String.fromCharCode(escapedValue);
10336             }
10337             else {
10338                 error(ts.Diagnostics.Hexadecimal_digit_expected);
10339                 return "";
10340             }
10341         }
10342         function scanExtendedUnicodeEscape() {
10343             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
10344             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
10345             var isInvalidExtendedEscape = false;
10346             // Validate the value of the digit
10347             if (escapedValue < 0) {
10348                 error(ts.Diagnostics.Hexadecimal_digit_expected);
10349                 isInvalidExtendedEscape = true;
10350             }
10351             else if (escapedValue > 0x10FFFF) {
10352                 error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
10353                 isInvalidExtendedEscape = true;
10354             }
10355             if (pos >= end) {
10356                 error(ts.Diagnostics.Unexpected_end_of_text);
10357                 isInvalidExtendedEscape = true;
10358             }
10359             else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
10360                 // Only swallow the following character up if it's a '}'.
10361                 pos++;
10362             }
10363             else {
10364                 error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
10365                 isInvalidExtendedEscape = true;
10366             }
10367             if (isInvalidExtendedEscape) {
10368                 return "";
10369             }
10370             return utf16EncodeAsString(escapedValue);
10371         }
10372         // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX'
10373         // and return code point value if valid Unicode escape is found. Otherwise return -1.
10374         function peekUnicodeEscape() {
10375             if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
10376                 var start_1 = pos;
10377                 pos += 2;
10378                 var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
10379                 pos = start_1;
10380                 return value;
10381             }
10382             return -1;
10383         }
10384         function peekExtendedUnicodeEscape() {
10385             if (languageVersion >= 2 /* ES2015 */ && codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) {
10386                 var start_2 = pos;
10387                 pos += 3;
10388                 var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
10389                 var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
10390                 pos = start_2;
10391                 return escapedValue;
10392             }
10393             return -1;
10394         }
10395         function scanIdentifierParts() {
10396             var result = "";
10397             var start = pos;
10398             while (pos < end) {
10399                 var ch = codePointAt(text, pos);
10400                 if (isIdentifierPart(ch, languageVersion)) {
10401                     pos += charSize(ch);
10402                 }
10403                 else if (ch === 92 /* backslash */) {
10404                     ch = peekExtendedUnicodeEscape();
10405                     if (ch >= 0 && isIdentifierPart(ch, languageVersion)) {
10406                         pos += 3;
10407                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10408                         result += scanExtendedUnicodeEscape();
10409                         start = pos;
10410                         continue;
10411                     }
10412                     ch = peekUnicodeEscape();
10413                     if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
10414                         break;
10415                     }
10416                     tokenFlags |= 1024 /* UnicodeEscape */;
10417                     result += text.substring(start, pos);
10418                     result += utf16EncodeAsString(ch);
10419                     // Valid Unicode escape is always six characters
10420                     pos += 6;
10421                     start = pos;
10422                 }
10423                 else {
10424                     break;
10425                 }
10426             }
10427             result += text.substring(start, pos);
10428             return result;
10429         }
10430         function getIdentifierToken() {
10431             // Reserved words are between 2 and 12 characters long and start with a lowercase letter
10432             var len = tokenValue.length;
10433             if (len >= 2 && len <= 12) {
10434                 var ch = tokenValue.charCodeAt(0);
10435                 if (ch >= 97 /* a */ && ch <= 122 /* z */) {
10436                     var keyword = textToKeyword.get(tokenValue);
10437                     if (keyword !== undefined) {
10438                         return token = keyword;
10439                     }
10440                 }
10441             }
10442             return token = 78 /* Identifier */;
10443         }
10444         function scanBinaryOrOctalDigits(base) {
10445             var value = "";
10446             // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
10447             // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
10448             var separatorAllowed = false;
10449             var isPreviousTokenSeparator = false;
10450             while (true) {
10451                 var ch = text.charCodeAt(pos);
10452                 // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
10453                 if (ch === 95 /* _ */) {
10454                     tokenFlags |= 512 /* ContainsSeparator */;
10455                     if (separatorAllowed) {
10456                         separatorAllowed = false;
10457                         isPreviousTokenSeparator = true;
10458                     }
10459                     else if (isPreviousTokenSeparator) {
10460                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
10461                     }
10462                     else {
10463                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
10464                     }
10465                     pos++;
10466                     continue;
10467                 }
10468                 separatorAllowed = true;
10469                 if (!isDigit(ch) || ch - 48 /* _0 */ >= base) {
10470                     break;
10471                 }
10472                 value += text[pos];
10473                 pos++;
10474                 isPreviousTokenSeparator = false;
10475             }
10476             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
10477                 // Literal ends with underscore - not allowed
10478                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
10479             }
10480             return value;
10481         }
10482         function checkBigIntSuffix() {
10483             if (text.charCodeAt(pos) === 110 /* n */) {
10484                 tokenValue += "n";
10485                 // Use base 10 instead of base 2 or base 8 for shorter literals
10486                 if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) {
10487                     tokenValue = ts.parsePseudoBigInt(tokenValue) + "n";
10488                 }
10489                 pos++;
10490                 return 9 /* BigIntLiteral */;
10491             }
10492             else { // not a bigint, so can convert to number in simplified form
10493                 // Number() may not support 0b or 0o, so use parseInt() instead
10494                 var numericValue = tokenFlags & 128 /* BinarySpecifier */
10495                     ? parseInt(tokenValue.slice(2), 2) // skip "0b"
10496                     : tokenFlags & 256 /* OctalSpecifier */
10497                         ? parseInt(tokenValue.slice(2), 8) // skip "0o"
10498                         : +tokenValue;
10499                 tokenValue = "" + numericValue;
10500                 return 8 /* NumericLiteral */;
10501             }
10502         }
10503         function scan() {
10504             var _a;
10505             startPos = pos;
10506             tokenFlags = 0 /* None */;
10507             var asteriskSeen = false;
10508             while (true) {
10509                 tokenPos = pos;
10510                 if (pos >= end) {
10511                     return token = 1 /* EndOfFileToken */;
10512                 }
10513                 var ch = codePointAt(text, pos);
10514                 // Special handling for shebang
10515                 if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
10516                     pos = scanShebangTrivia(text, pos);
10517                     if (skipTrivia) {
10518                         continue;
10519                     }
10520                     else {
10521                         return token = 6 /* ShebangTrivia */;
10522                     }
10523                 }
10524                 switch (ch) {
10525                     case 10 /* lineFeed */:
10526                     case 13 /* carriageReturn */:
10527                         tokenFlags |= 1 /* PrecedingLineBreak */;
10528                         if (skipTrivia) {
10529                             pos++;
10530                             continue;
10531                         }
10532                         else {
10533                             if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
10534                                 // consume both CR and LF
10535                                 pos += 2;
10536                             }
10537                             else {
10538                                 pos++;
10539                             }
10540                             return token = 4 /* NewLineTrivia */;
10541                         }
10542                     case 9 /* tab */:
10543                     case 11 /* verticalTab */:
10544                     case 12 /* formFeed */:
10545                     case 32 /* space */:
10546                     case 160 /* nonBreakingSpace */:
10547                     case 5760 /* ogham */:
10548                     case 8192 /* enQuad */:
10549                     case 8193 /* emQuad */:
10550                     case 8194 /* enSpace */:
10551                     case 8195 /* emSpace */:
10552                     case 8196 /* threePerEmSpace */:
10553                     case 8197 /* fourPerEmSpace */:
10554                     case 8198 /* sixPerEmSpace */:
10555                     case 8199 /* figureSpace */:
10556                     case 8200 /* punctuationSpace */:
10557                     case 8201 /* thinSpace */:
10558                     case 8202 /* hairSpace */:
10559                     case 8203 /* zeroWidthSpace */:
10560                     case 8239 /* narrowNoBreakSpace */:
10561                     case 8287 /* mathematicalSpace */:
10562                     case 12288 /* ideographicSpace */:
10563                     case 65279 /* byteOrderMark */:
10564                         if (skipTrivia) {
10565                             pos++;
10566                             continue;
10567                         }
10568                         else {
10569                             while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
10570                                 pos++;
10571                             }
10572                             return token = 5 /* WhitespaceTrivia */;
10573                         }
10574                     case 33 /* exclamation */:
10575                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10576                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10577                                 return pos += 3, token = 37 /* ExclamationEqualsEqualsToken */;
10578                             }
10579                             return pos += 2, token = 35 /* ExclamationEqualsToken */;
10580                         }
10581                         pos++;
10582                         return token = 53 /* ExclamationToken */;
10583                     case 34 /* doubleQuote */:
10584                     case 39 /* singleQuote */:
10585                         tokenValue = scanString();
10586                         return token = 10 /* StringLiteral */;
10587                     case 96 /* backtick */:
10588                         return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false);
10589                     case 37 /* percent */:
10590                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10591                             return pos += 2, token = 68 /* PercentEqualsToken */;
10592                         }
10593                         pos++;
10594                         return token = 44 /* PercentToken */;
10595                     case 38 /* ampersand */:
10596                         if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
10597                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10598                                 return pos += 3, token = 75 /* AmpersandAmpersandEqualsToken */;
10599                             }
10600                             return pos += 2, token = 55 /* AmpersandAmpersandToken */;
10601                         }
10602                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10603                             return pos += 2, token = 72 /* AmpersandEqualsToken */;
10604                         }
10605                         pos++;
10606                         return token = 50 /* AmpersandToken */;
10607                     case 40 /* openParen */:
10608                         pos++;
10609                         return token = 20 /* OpenParenToken */;
10610                     case 41 /* closeParen */:
10611                         pos++;
10612                         return token = 21 /* CloseParenToken */;
10613                     case 42 /* asterisk */:
10614                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10615                             return pos += 2, token = 65 /* AsteriskEqualsToken */;
10616                         }
10617                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
10618                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10619                                 return pos += 3, token = 66 /* AsteriskAsteriskEqualsToken */;
10620                             }
10621                             return pos += 2, token = 42 /* AsteriskAsteriskToken */;
10622                         }
10623                         pos++;
10624                         if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
10625                             // decoration at the start of a JSDoc comment line
10626                             asteriskSeen = true;
10627                             continue;
10628                         }
10629                         return token = 41 /* AsteriskToken */;
10630                     case 43 /* plus */:
10631                         if (text.charCodeAt(pos + 1) === 43 /* plus */) {
10632                             return pos += 2, token = 45 /* PlusPlusToken */;
10633                         }
10634                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10635                             return pos += 2, token = 63 /* PlusEqualsToken */;
10636                         }
10637                         pos++;
10638                         return token = 39 /* PlusToken */;
10639                     case 44 /* comma */:
10640                         pos++;
10641                         return token = 27 /* CommaToken */;
10642                     case 45 /* minus */:
10643                         if (text.charCodeAt(pos + 1) === 45 /* minus */) {
10644                             return pos += 2, token = 46 /* MinusMinusToken */;
10645                         }
10646                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10647                             return pos += 2, token = 64 /* MinusEqualsToken */;
10648                         }
10649                         pos++;
10650                         return token = 40 /* MinusToken */;
10651                     case 46 /* dot */:
10652                         if (isDigit(text.charCodeAt(pos + 1))) {
10653                             tokenValue = scanNumber().value;
10654                             return token = 8 /* NumericLiteral */;
10655                         }
10656                         if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
10657                             return pos += 3, token = 25 /* DotDotDotToken */;
10658                         }
10659                         pos++;
10660                         return token = 24 /* DotToken */;
10661                     case 47 /* slash */:
10662                         // Single-line comment
10663                         if (text.charCodeAt(pos + 1) === 47 /* slash */) {
10664                             pos += 2;
10665                             while (pos < end) {
10666                                 if (isLineBreak(text.charCodeAt(pos))) {
10667                                     break;
10668                                 }
10669                                 pos++;
10670                             }
10671                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos);
10672                             if (skipTrivia) {
10673                                 continue;
10674                             }
10675                             else {
10676                                 return token = 2 /* SingleLineCommentTrivia */;
10677                             }
10678                         }
10679                         // Multi-line comment
10680                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
10681                             pos += 2;
10682                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
10683                                 tokenFlags |= 2 /* PrecedingJSDocComment */;
10684                             }
10685                             var commentClosed = false;
10686                             var lastLineStart = tokenPos;
10687                             while (pos < end) {
10688                                 var ch_1 = text.charCodeAt(pos);
10689                                 if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
10690                                     pos += 2;
10691                                     commentClosed = true;
10692                                     break;
10693                                 }
10694                                 pos++;
10695                                 if (isLineBreak(ch_1)) {
10696                                     lastLineStart = pos;
10697                                     tokenFlags |= 1 /* PrecedingLineBreak */;
10698                                 }
10699                             }
10700                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart);
10701                             if (!commentClosed) {
10702                                 error(ts.Diagnostics.Asterisk_Slash_expected);
10703                             }
10704                             if (skipTrivia) {
10705                                 continue;
10706                             }
10707                             else {
10708                                 if (!commentClosed) {
10709                                     tokenFlags |= 4 /* Unterminated */;
10710                                 }
10711                                 return token = 3 /* MultiLineCommentTrivia */;
10712                             }
10713                         }
10714                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10715                             return pos += 2, token = 67 /* SlashEqualsToken */;
10716                         }
10717                         pos++;
10718                         return token = 43 /* SlashToken */;
10719                     case 48 /* _0 */:
10720                         if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
10721                             pos += 2;
10722                             tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
10723                             if (!tokenValue) {
10724                                 error(ts.Diagnostics.Hexadecimal_digit_expected);
10725                                 tokenValue = "0";
10726                             }
10727                             tokenValue = "0x" + tokenValue;
10728                             tokenFlags |= 64 /* HexSpecifier */;
10729                             return token = checkBigIntSuffix();
10730                         }
10731                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
10732                             pos += 2;
10733                             tokenValue = scanBinaryOrOctalDigits(/* base */ 2);
10734                             if (!tokenValue) {
10735                                 error(ts.Diagnostics.Binary_digit_expected);
10736                                 tokenValue = "0";
10737                             }
10738                             tokenValue = "0b" + tokenValue;
10739                             tokenFlags |= 128 /* BinarySpecifier */;
10740                             return token = checkBigIntSuffix();
10741                         }
10742                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
10743                             pos += 2;
10744                             tokenValue = scanBinaryOrOctalDigits(/* base */ 8);
10745                             if (!tokenValue) {
10746                                 error(ts.Diagnostics.Octal_digit_expected);
10747                                 tokenValue = "0";
10748                             }
10749                             tokenValue = "0o" + tokenValue;
10750                             tokenFlags |= 256 /* OctalSpecifier */;
10751                             return token = checkBigIntSuffix();
10752                         }
10753                         // Try to parse as an octal
10754                         if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
10755                             tokenValue = "" + scanOctalDigits();
10756                             tokenFlags |= 32 /* Octal */;
10757                             return token = 8 /* NumericLiteral */;
10758                         }
10759                     // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
10760                     // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
10761                     // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
10762                     // falls through
10763                     case 49 /* _1 */:
10764                     case 50 /* _2 */:
10765                     case 51 /* _3 */:
10766                     case 52 /* _4 */:
10767                     case 53 /* _5 */:
10768                     case 54 /* _6 */:
10769                     case 55 /* _7 */:
10770                     case 56 /* _8 */:
10771                     case 57 /* _9 */:
10772                         (_a = scanNumber(), token = _a.type, tokenValue = _a.value);
10773                         return token;
10774                     case 58 /* colon */:
10775                         pos++;
10776                         return token = 58 /* ColonToken */;
10777                     case 59 /* semicolon */:
10778                         pos++;
10779                         return token = 26 /* SemicolonToken */;
10780                     case 60 /* lessThan */:
10781                         if (isConflictMarkerTrivia(text, pos)) {
10782                             pos = scanConflictMarkerTrivia(text, pos, error);
10783                             if (skipTrivia) {
10784                                 continue;
10785                             }
10786                             else {
10787                                 return token = 7 /* ConflictMarkerTrivia */;
10788                             }
10789                         }
10790                         if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
10791                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10792                                 return pos += 3, token = 69 /* LessThanLessThanEqualsToken */;
10793                             }
10794                             return pos += 2, token = 47 /* LessThanLessThanToken */;
10795                         }
10796                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10797                             return pos += 2, token = 32 /* LessThanEqualsToken */;
10798                         }
10799                         if (languageVariant === 1 /* JSX */ &&
10800                             text.charCodeAt(pos + 1) === 47 /* slash */ &&
10801                             text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
10802                             return pos += 2, token = 30 /* LessThanSlashToken */;
10803                         }
10804                         pos++;
10805                         return token = 29 /* LessThanToken */;
10806                     case 61 /* equals */:
10807                         if (isConflictMarkerTrivia(text, pos)) {
10808                             pos = scanConflictMarkerTrivia(text, pos, error);
10809                             if (skipTrivia) {
10810                                 continue;
10811                             }
10812                             else {
10813                                 return token = 7 /* ConflictMarkerTrivia */;
10814                             }
10815                         }
10816                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10817                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10818                                 return pos += 3, token = 36 /* EqualsEqualsEqualsToken */;
10819                             }
10820                             return pos += 2, token = 34 /* EqualsEqualsToken */;
10821                         }
10822                         if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
10823                             return pos += 2, token = 38 /* EqualsGreaterThanToken */;
10824                         }
10825                         pos++;
10826                         return token = 62 /* EqualsToken */;
10827                     case 62 /* greaterThan */:
10828                         if (isConflictMarkerTrivia(text, pos)) {
10829                             pos = scanConflictMarkerTrivia(text, pos, error);
10830                             if (skipTrivia) {
10831                                 continue;
10832                             }
10833                             else {
10834                                 return token = 7 /* ConflictMarkerTrivia */;
10835                             }
10836                         }
10837                         pos++;
10838                         return token = 31 /* GreaterThanToken */;
10839                     case 63 /* question */:
10840                         if (text.charCodeAt(pos + 1) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 2))) {
10841                             return pos += 2, token = 28 /* QuestionDotToken */;
10842                         }
10843                         if (text.charCodeAt(pos + 1) === 63 /* question */) {
10844                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10845                                 return pos += 3, token = 76 /* QuestionQuestionEqualsToken */;
10846                             }
10847                             return pos += 2, token = 60 /* QuestionQuestionToken */;
10848                         }
10849                         pos++;
10850                         return token = 57 /* QuestionToken */;
10851                     case 91 /* openBracket */:
10852                         pos++;
10853                         return token = 22 /* OpenBracketToken */;
10854                     case 93 /* closeBracket */:
10855                         pos++;
10856                         return token = 23 /* CloseBracketToken */;
10857                     case 94 /* caret */:
10858                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10859                             return pos += 2, token = 77 /* CaretEqualsToken */;
10860                         }
10861                         pos++;
10862                         return token = 52 /* CaretToken */;
10863                     case 123 /* openBrace */:
10864                         pos++;
10865                         return token = 18 /* OpenBraceToken */;
10866                     case 124 /* bar */:
10867                         if (isConflictMarkerTrivia(text, pos)) {
10868                             pos = scanConflictMarkerTrivia(text, pos, error);
10869                             if (skipTrivia) {
10870                                 continue;
10871                             }
10872                             else {
10873                                 return token = 7 /* ConflictMarkerTrivia */;
10874                             }
10875                         }
10876                         if (text.charCodeAt(pos + 1) === 124 /* bar */) {
10877                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10878                                 return pos += 3, token = 74 /* BarBarEqualsToken */;
10879                             }
10880                             return pos += 2, token = 56 /* BarBarToken */;
10881                         }
10882                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10883                             return pos += 2, token = 73 /* BarEqualsToken */;
10884                         }
10885                         pos++;
10886                         return token = 51 /* BarToken */;
10887                     case 125 /* closeBrace */:
10888                         pos++;
10889                         return token = 19 /* CloseBraceToken */;
10890                     case 126 /* tilde */:
10891                         pos++;
10892                         return token = 54 /* TildeToken */;
10893                     case 64 /* at */:
10894                         pos++;
10895                         return token = 59 /* AtToken */;
10896                     case 92 /* backslash */:
10897                         var extendedCookedChar = peekExtendedUnicodeEscape();
10898                         if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
10899                             pos += 3;
10900                             tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10901                             tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
10902                             return token = getIdentifierToken();
10903                         }
10904                         var cookedChar = peekUnicodeEscape();
10905                         if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
10906                             pos += 6;
10907                             tokenFlags |= 1024 /* UnicodeEscape */;
10908                             tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
10909                             return token = getIdentifierToken();
10910                         }
10911                         error(ts.Diagnostics.Invalid_character);
10912                         pos++;
10913                         return token = 0 /* Unknown */;
10914                     case 35 /* hash */:
10915                         if (pos !== 0 && text[pos + 1] === "!") {
10916                             error(ts.Diagnostics.can_only_be_used_at_the_start_of_a_file);
10917                             pos++;
10918                             return token = 0 /* Unknown */;
10919                         }
10920                         pos++;
10921                         if (isIdentifierStart(ch = text.charCodeAt(pos), languageVersion)) {
10922                             pos++;
10923                             while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion))
10924                                 pos++;
10925                             tokenValue = text.substring(tokenPos, pos);
10926                             if (ch === 92 /* backslash */) {
10927                                 tokenValue += scanIdentifierParts();
10928                             }
10929                         }
10930                         else {
10931                             tokenValue = "#";
10932                             error(ts.Diagnostics.Invalid_character);
10933                         }
10934                         return token = 79 /* PrivateIdentifier */;
10935                     default:
10936                         var identifierKind = scanIdentifier(ch, languageVersion);
10937                         if (identifierKind) {
10938                             return token = identifierKind;
10939                         }
10940                         else if (isWhiteSpaceSingleLine(ch)) {
10941                             pos += charSize(ch);
10942                             continue;
10943                         }
10944                         else if (isLineBreak(ch)) {
10945                             tokenFlags |= 1 /* PrecedingLineBreak */;
10946                             pos += charSize(ch);
10947                             continue;
10948                         }
10949                         error(ts.Diagnostics.Invalid_character);
10950                         pos += charSize(ch);
10951                         return token = 0 /* Unknown */;
10952                 }
10953             }
10954         }
10955         function reScanInvalidIdentifier() {
10956             ts.Debug.assert(token === 0 /* Unknown */, "'reScanInvalidIdentifier' should only be called when the current token is 'SyntaxKind.Unknown'.");
10957             pos = tokenPos = startPos;
10958             tokenFlags = 0;
10959             var ch = codePointAt(text, pos);
10960             var identifierKind = scanIdentifier(ch, 99 /* ESNext */);
10961             if (identifierKind) {
10962                 return token = identifierKind;
10963             }
10964             pos += charSize(ch);
10965             return token; // Still `SyntaKind.Unknown`
10966         }
10967         function scanIdentifier(startCharacter, languageVersion) {
10968             var ch = startCharacter;
10969             if (isIdentifierStart(ch, languageVersion)) {
10970                 pos += charSize(ch);
10971                 while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
10972                     pos += charSize(ch);
10973                 tokenValue = text.substring(tokenPos, pos);
10974                 if (ch === 92 /* backslash */) {
10975                     tokenValue += scanIdentifierParts();
10976                 }
10977                 return getIdentifierToken();
10978             }
10979         }
10980         function reScanGreaterToken() {
10981             if (token === 31 /* GreaterThanToken */) {
10982                 if (text.charCodeAt(pos) === 62 /* greaterThan */) {
10983                     if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
10984                         if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10985                             return pos += 3, token = 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
10986                         }
10987                         return pos += 2, token = 49 /* GreaterThanGreaterThanGreaterThanToken */;
10988                     }
10989                     if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10990                         return pos += 2, token = 70 /* GreaterThanGreaterThanEqualsToken */;
10991                     }
10992                     pos++;
10993                     return token = 48 /* GreaterThanGreaterThanToken */;
10994                 }
10995                 if (text.charCodeAt(pos) === 61 /* equals */) {
10996                     pos++;
10997                     return token = 33 /* GreaterThanEqualsToken */;
10998                 }
10999             }
11000             return token;
11001         }
11002         function reScanAsteriskEqualsToken() {
11003             ts.Debug.assert(token === 65 /* AsteriskEqualsToken */, "'reScanAsteriskEqualsToken' should only be called on a '*='");
11004             pos = tokenPos + 1;
11005             return token = 62 /* EqualsToken */;
11006         }
11007         function reScanSlashToken() {
11008             if (token === 43 /* SlashToken */ || token === 67 /* SlashEqualsToken */) {
11009                 var p = tokenPos + 1;
11010                 var inEscape = false;
11011                 var inCharacterClass = false;
11012                 while (true) {
11013                     // If we reach the end of a file, or hit a newline, then this is an unterminated
11014                     // regex.  Report error and return what we have so far.
11015                     if (p >= end) {
11016                         tokenFlags |= 4 /* Unterminated */;
11017                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
11018                         break;
11019                     }
11020                     var ch = text.charCodeAt(p);
11021                     if (isLineBreak(ch)) {
11022                         tokenFlags |= 4 /* Unterminated */;
11023                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
11024                         break;
11025                     }
11026                     if (inEscape) {
11027                         // Parsing an escape character;
11028                         // reset the flag and just advance to the next char.
11029                         inEscape = false;
11030                     }
11031                     else if (ch === 47 /* slash */ && !inCharacterClass) {
11032                         // A slash within a character class is permissible,
11033                         // but in general it signals the end of the regexp literal.
11034                         p++;
11035                         break;
11036                     }
11037                     else if (ch === 91 /* openBracket */) {
11038                         inCharacterClass = true;
11039                     }
11040                     else if (ch === 92 /* backslash */) {
11041                         inEscape = true;
11042                     }
11043                     else if (ch === 93 /* closeBracket */) {
11044                         inCharacterClass = false;
11045                     }
11046                     p++;
11047                 }
11048                 while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
11049                     p++;
11050                 }
11051                 pos = p;
11052                 tokenValue = text.substring(tokenPos, pos);
11053                 token = 13 /* RegularExpressionLiteral */;
11054             }
11055             return token;
11056         }
11057         function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) {
11058             var type = getDirectiveFromComment(text, commentDirectiveRegEx);
11059             if (type === undefined) {
11060                 return commentDirectives;
11061             }
11062             return ts.append(commentDirectives, {
11063                 range: { pos: lineStart, end: pos },
11064                 type: type,
11065             });
11066         }
11067         function getDirectiveFromComment(text, commentDirectiveRegEx) {
11068             var match = commentDirectiveRegEx.exec(text);
11069             if (!match) {
11070                 return undefined;
11071             }
11072             switch (match[1]) {
11073                 case "ts-expect-error":
11074                     return 0 /* ExpectError */;
11075                 case "ts-ignore":
11076                     return 1 /* Ignore */;
11077             }
11078             return undefined;
11079         }
11080         /**
11081          * Unconditionally back up and scan a template expression portion.
11082          */
11083         function reScanTemplateToken(isTaggedTemplate) {
11084             ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
11085             pos = tokenPos;
11086             return token = scanTemplateAndSetTokenValue(isTaggedTemplate);
11087         }
11088         function reScanTemplateHeadOrNoSubstitutionTemplate() {
11089             pos = tokenPos;
11090             return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true);
11091         }
11092         function reScanJsxToken() {
11093             pos = tokenPos = startPos;
11094             return token = scanJsxToken();
11095         }
11096         function reScanLessThanToken() {
11097             if (token === 47 /* LessThanLessThanToken */) {
11098                 pos = tokenPos + 1;
11099                 return token = 29 /* LessThanToken */;
11100             }
11101             return token;
11102         }
11103         function reScanQuestionToken() {
11104             ts.Debug.assert(token === 60 /* QuestionQuestionToken */, "'reScanQuestionToken' should only be called on a '??'");
11105             pos = tokenPos + 1;
11106             return token = 57 /* QuestionToken */;
11107         }
11108         function scanJsxToken() {
11109             startPos = tokenPos = pos;
11110             if (pos >= end) {
11111                 return token = 1 /* EndOfFileToken */;
11112             }
11113             var char = text.charCodeAt(pos);
11114             if (char === 60 /* lessThan */) {
11115                 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
11116                     pos += 2;
11117                     return token = 30 /* LessThanSlashToken */;
11118                 }
11119                 pos++;
11120                 return token = 29 /* LessThanToken */;
11121             }
11122             if (char === 123 /* openBrace */) {
11123                 pos++;
11124                 return token = 18 /* OpenBraceToken */;
11125             }
11126             // First non-whitespace character on this line.
11127             var firstNonWhitespace = 0;
11128             var lastNonWhitespace = -1;
11129             // These initial values are special because the first line is:
11130             // firstNonWhitespace = 0 to indicate that we want leading whitespace,
11131             while (pos < end) {
11132                 // We want to keep track of the last non-whitespace (but including
11133                 // newlines character for hitting the end of the JSX Text region)
11134                 if (!isWhiteSpaceSingleLine(char)) {
11135                     lastNonWhitespace = pos;
11136                 }
11137                 char = text.charCodeAt(pos);
11138                 if (char === 123 /* openBrace */) {
11139                     break;
11140                 }
11141                 if (char === 60 /* lessThan */) {
11142                     if (isConflictMarkerTrivia(text, pos)) {
11143                         pos = scanConflictMarkerTrivia(text, pos, error);
11144                         return token = 7 /* ConflictMarkerTrivia */;
11145                     }
11146                     break;
11147                 }
11148                 if (char === 62 /* greaterThan */) {
11149                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1);
11150                 }
11151                 if (char === 125 /* closeBrace */) {
11152                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1);
11153                 }
11154                 if (lastNonWhitespace > 0)
11155                     lastNonWhitespace++;
11156                 // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
11157                 // i.e (- : whitespace)
11158                 //      <div>----
11159                 //      </div> becomes <div></div>
11160                 //
11161                 //      <div>----</div> becomes <div>----</div>
11162                 if (isLineBreak(char) && firstNonWhitespace === 0) {
11163                     firstNonWhitespace = -1;
11164                 }
11165                 else if (!isWhiteSpaceLike(char)) {
11166                     firstNonWhitespace = pos;
11167                 }
11168                 pos++;
11169             }
11170             var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace;
11171             tokenValue = text.substring(startPos, endPosition);
11172             return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
11173         }
11174         // Scans a JSX identifier; these differ from normal identifiers in that
11175         // they allow dashes
11176         function scanJsxIdentifier() {
11177             if (tokenIsIdentifierOrKeyword(token)) {
11178                 // An identifier or keyword has already been parsed - check for a `-` or a single instance of `:` and then append it and
11179                 // everything after it to the token
11180                 // Do note that this means that `scanJsxIdentifier` effectively _mutates_ the visible token without advancing to a new token
11181                 // Any caller should be expecting this behavior and should only read the pos or token value after calling it.
11182                 var namespaceSeparator = false;
11183                 while (pos < end) {
11184                     var ch = text.charCodeAt(pos);
11185                     if (ch === 45 /* minus */) {
11186                         tokenValue += "-";
11187                         pos++;
11188                         continue;
11189                     }
11190                     else if (ch === 58 /* colon */ && !namespaceSeparator) {
11191                         tokenValue += ":";
11192                         pos++;
11193                         namespaceSeparator = true;
11194                         continue;
11195                     }
11196                     var oldPos = pos;
11197                     tokenValue += scanIdentifierParts(); // reuse `scanIdentifierParts` so unicode escapes are handled
11198                     if (pos === oldPos) {
11199                         break;
11200                     }
11201                 }
11202                 // Do not include a trailing namespace separator in the token, since this is against the spec.
11203                 if (tokenValue.slice(-1) === ":") {
11204                     tokenValue = tokenValue.slice(0, -1);
11205                     pos--;
11206                 }
11207             }
11208             return token;
11209         }
11210         function scanJsxAttributeValue() {
11211             startPos = pos;
11212             switch (text.charCodeAt(pos)) {
11213                 case 34 /* doubleQuote */:
11214                 case 39 /* singleQuote */:
11215                     tokenValue = scanString(/*jsxAttributeString*/ true);
11216                     return token = 10 /* StringLiteral */;
11217                 default:
11218                     // If this scans anything other than `{`, it's a parse error.
11219                     return scan();
11220             }
11221         }
11222         function reScanJsxAttributeValue() {
11223             pos = tokenPos = startPos;
11224             return scanJsxAttributeValue();
11225         }
11226         function scanJsDocToken() {
11227             startPos = tokenPos = pos;
11228             tokenFlags = 0 /* None */;
11229             if (pos >= end) {
11230                 return token = 1 /* EndOfFileToken */;
11231             }
11232             var ch = codePointAt(text, pos);
11233             pos += charSize(ch);
11234             switch (ch) {
11235                 case 9 /* tab */:
11236                 case 11 /* verticalTab */:
11237                 case 12 /* formFeed */:
11238                 case 32 /* space */:
11239                     while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
11240                         pos++;
11241                     }
11242                     return token = 5 /* WhitespaceTrivia */;
11243                 case 64 /* at */:
11244                     return token = 59 /* AtToken */;
11245                 case 13 /* carriageReturn */:
11246                     if (text.charCodeAt(pos) === 10 /* lineFeed */) {
11247                         pos++;
11248                     }
11249                 // falls through
11250                 case 10 /* lineFeed */:
11251                     tokenFlags |= 1 /* PrecedingLineBreak */;
11252                     return token = 4 /* NewLineTrivia */;
11253                 case 42 /* asterisk */:
11254                     return token = 41 /* AsteriskToken */;
11255                 case 123 /* openBrace */:
11256                     return token = 18 /* OpenBraceToken */;
11257                 case 125 /* closeBrace */:
11258                     return token = 19 /* CloseBraceToken */;
11259                 case 91 /* openBracket */:
11260                     return token = 22 /* OpenBracketToken */;
11261                 case 93 /* closeBracket */:
11262                     return token = 23 /* CloseBracketToken */;
11263                 case 60 /* lessThan */:
11264                     return token = 29 /* LessThanToken */;
11265                 case 62 /* greaterThan */:
11266                     return token = 31 /* GreaterThanToken */;
11267                 case 61 /* equals */:
11268                     return token = 62 /* EqualsToken */;
11269                 case 44 /* comma */:
11270                     return token = 27 /* CommaToken */;
11271                 case 46 /* dot */:
11272                     return token = 24 /* DotToken */;
11273                 case 96 /* backtick */:
11274                     return token = 61 /* BacktickToken */;
11275                 case 92 /* backslash */:
11276                     pos--;
11277                     var extendedCookedChar = peekExtendedUnicodeEscape();
11278                     if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
11279                         pos += 3;
11280                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
11281                         tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
11282                         return token = getIdentifierToken();
11283                     }
11284                     var cookedChar = peekUnicodeEscape();
11285                     if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
11286                         pos += 6;
11287                         tokenFlags |= 1024 /* UnicodeEscape */;
11288                         tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
11289                         return token = getIdentifierToken();
11290                     }
11291                     pos++;
11292                     return token = 0 /* Unknown */;
11293             }
11294             if (isIdentifierStart(ch, languageVersion)) {
11295                 var char = ch;
11296                 while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */)
11297                     pos += charSize(char);
11298                 tokenValue = text.substring(tokenPos, pos);
11299                 if (char === 92 /* backslash */) {
11300                     tokenValue += scanIdentifierParts();
11301                 }
11302                 return token = getIdentifierToken();
11303             }
11304             else {
11305                 return token = 0 /* Unknown */;
11306             }
11307         }
11308         function speculationHelper(callback, isLookahead) {
11309             var savePos = pos;
11310             var saveStartPos = startPos;
11311             var saveTokenPos = tokenPos;
11312             var saveToken = token;
11313             var saveTokenValue = tokenValue;
11314             var saveTokenFlags = tokenFlags;
11315             var result = callback();
11316             // If our callback returned something 'falsy' or we're just looking ahead,
11317             // then unconditionally restore us to where we were.
11318             if (!result || isLookahead) {
11319                 pos = savePos;
11320                 startPos = saveStartPos;
11321                 tokenPos = saveTokenPos;
11322                 token = saveToken;
11323                 tokenValue = saveTokenValue;
11324                 tokenFlags = saveTokenFlags;
11325             }
11326             return result;
11327         }
11328         function scanRange(start, length, callback) {
11329             var saveEnd = end;
11330             var savePos = pos;
11331             var saveStartPos = startPos;
11332             var saveTokenPos = tokenPos;
11333             var saveToken = token;
11334             var saveTokenValue = tokenValue;
11335             var saveTokenFlags = tokenFlags;
11336             var saveErrorExpectations = commentDirectives;
11337             setText(text, start, length);
11338             var result = callback();
11339             end = saveEnd;
11340             pos = savePos;
11341             startPos = saveStartPos;
11342             tokenPos = saveTokenPos;
11343             token = saveToken;
11344             tokenValue = saveTokenValue;
11345             tokenFlags = saveTokenFlags;
11346             commentDirectives = saveErrorExpectations;
11347             return result;
11348         }
11349         function lookAhead(callback) {
11350             return speculationHelper(callback, /*isLookahead*/ true);
11351         }
11352         function tryScan(callback) {
11353             return speculationHelper(callback, /*isLookahead*/ false);
11354         }
11355         function getText() {
11356             return text;
11357         }
11358         function clearCommentDirectives() {
11359             commentDirectives = undefined;
11360         }
11361         function setText(newText, start, length) {
11362             text = newText || "";
11363             end = length === undefined ? text.length : start + length;
11364             setTextPos(start || 0);
11365         }
11366         function setOnError(errorCallback) {
11367             onError = errorCallback;
11368         }
11369         function setScriptTarget(scriptTarget) {
11370             languageVersion = scriptTarget;
11371         }
11372         function setLanguageVariant(variant) {
11373             languageVariant = variant;
11374         }
11375         function setTextPos(textPos) {
11376             ts.Debug.assert(textPos >= 0);
11377             pos = textPos;
11378             startPos = textPos;
11379             tokenPos = textPos;
11380             token = 0 /* Unknown */;
11381             tokenValue = undefined;
11382             tokenFlags = 0 /* None */;
11383         }
11384         function setInJSDocType(inType) {
11385             inJSDocType += inType ? 1 : -1;
11386         }
11387     }
11388     ts.createScanner = createScanner;
11389     /* @internal */
11390     var codePointAt = String.prototype.codePointAt ? function (s, i) { return s.codePointAt(i); } : function codePointAt(str, i) {
11391         // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
11392         var size = str.length;
11393         // Account for out-of-bounds indices:
11394         if (i < 0 || i >= size) {
11395             return undefined; // String.codePointAt returns `undefined` for OOB indexes
11396         }
11397         // Get the first code unit
11398         var first = str.charCodeAt(i);
11399         // check if it’s the start of a surrogate pair
11400         if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { // high surrogate and there is a next code unit
11401             var second = str.charCodeAt(i + 1);
11402             if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
11403                 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
11404                 return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
11405             }
11406         }
11407         return first;
11408     };
11409     /* @internal */
11410     function charSize(ch) {
11411         if (ch >= 0x10000) {
11412             return 2;
11413         }
11414         return 1;
11415     }
11416     // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
11417     function utf16EncodeAsStringFallback(codePoint) {
11418         ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
11419         if (codePoint <= 65535) {
11420             return String.fromCharCode(codePoint);
11421         }
11422         var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
11423         var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
11424         return String.fromCharCode(codeUnit1, codeUnit2);
11425     }
11426     var utf16EncodeAsStringWorker = String.fromCodePoint ? function (codePoint) { return String.fromCodePoint(codePoint); } : utf16EncodeAsStringFallback;
11427     /* @internal */
11428     function utf16EncodeAsString(codePoint) {
11429         return utf16EncodeAsStringWorker(codePoint);
11430     }
11431     ts.utf16EncodeAsString = utf16EncodeAsString;
11432 })(ts || (ts = {}));
11433 var ts;
11434 (function (ts) {
11435     function isExternalModuleNameRelative(moduleName) {
11436         // TypeScript 1.0 spec (April 2014): 11.2.1
11437         // An external module name is "relative" if the first term is "." or "..".
11438         // 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.
11439         return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName);
11440     }
11441     ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
11442     function sortAndDeduplicateDiagnostics(diagnostics) {
11443         return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
11444     }
11445     ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
11446     function getDefaultLibFileName(options) {
11447         switch (options.target) {
11448             case 99 /* ESNext */:
11449                 return "lib.esnext.full.d.ts";
11450             case 7 /* ES2020 */:
11451                 return "lib.es2020.full.d.ts";
11452             case 6 /* ES2019 */:
11453                 return "lib.es2019.full.d.ts";
11454             case 5 /* ES2018 */:
11455                 return "lib.es2018.full.d.ts";
11456             case 4 /* ES2017 */:
11457                 return "lib.es2017.full.d.ts";
11458             case 3 /* ES2016 */:
11459                 return "lib.es2016.full.d.ts";
11460             case 2 /* ES2015 */:
11461                 return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
11462             default:
11463                 return "lib.d.ts";
11464         }
11465     }
11466     ts.getDefaultLibFileName = getDefaultLibFileName;
11467     function textSpanEnd(span) {
11468         return span.start + span.length;
11469     }
11470     ts.textSpanEnd = textSpanEnd;
11471     function textSpanIsEmpty(span) {
11472         return span.length === 0;
11473     }
11474     ts.textSpanIsEmpty = textSpanIsEmpty;
11475     function textSpanContainsPosition(span, position) {
11476         return position >= span.start && position < textSpanEnd(span);
11477     }
11478     ts.textSpanContainsPosition = textSpanContainsPosition;
11479     /* @internal */
11480     function textRangeContainsPositionInclusive(span, position) {
11481         return position >= span.pos && position <= span.end;
11482     }
11483     ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
11484     // Returns true if 'span' contains 'other'.
11485     function textSpanContainsTextSpan(span, other) {
11486         return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
11487     }
11488     ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
11489     function textSpanOverlapsWith(span, other) {
11490         return textSpanOverlap(span, other) !== undefined;
11491     }
11492     ts.textSpanOverlapsWith = textSpanOverlapsWith;
11493     function textSpanOverlap(span1, span2) {
11494         var overlap = textSpanIntersection(span1, span2);
11495         return overlap && overlap.length === 0 ? undefined : overlap;
11496     }
11497     ts.textSpanOverlap = textSpanOverlap;
11498     function textSpanIntersectsWithTextSpan(span, other) {
11499         return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
11500     }
11501     ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
11502     function textSpanIntersectsWith(span, start, length) {
11503         return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
11504     }
11505     ts.textSpanIntersectsWith = textSpanIntersectsWith;
11506     function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
11507         var end1 = start1 + length1;
11508         var end2 = start2 + length2;
11509         return start2 <= end1 && end2 >= start1;
11510     }
11511     ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
11512     function textSpanIntersectsWithPosition(span, position) {
11513         return position <= textSpanEnd(span) && position >= span.start;
11514     }
11515     ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
11516     function textSpanIntersection(span1, span2) {
11517         var start = Math.max(span1.start, span2.start);
11518         var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
11519         return start <= end ? createTextSpanFromBounds(start, end) : undefined;
11520     }
11521     ts.textSpanIntersection = textSpanIntersection;
11522     function createTextSpan(start, length) {
11523         if (start < 0) {
11524             throw new Error("start < 0");
11525         }
11526         if (length < 0) {
11527             throw new Error("length < 0");
11528         }
11529         return { start: start, length: length };
11530     }
11531     ts.createTextSpan = createTextSpan;
11532     function createTextSpanFromBounds(start, end) {
11533         return createTextSpan(start, end - start);
11534     }
11535     ts.createTextSpanFromBounds = createTextSpanFromBounds;
11536     function textChangeRangeNewSpan(range) {
11537         return createTextSpan(range.span.start, range.newLength);
11538     }
11539     ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
11540     function textChangeRangeIsUnchanged(range) {
11541         return textSpanIsEmpty(range.span) && range.newLength === 0;
11542     }
11543     ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
11544     function createTextChangeRange(span, newLength) {
11545         if (newLength < 0) {
11546             throw new Error("newLength < 0");
11547         }
11548         return { span: span, newLength: newLength };
11549     }
11550     ts.createTextChangeRange = createTextChangeRange;
11551     ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const
11552     /**
11553      * Called to merge all the changes that occurred across several versions of a script snapshot
11554      * into a single change.  i.e. if a user keeps making successive edits to a script we will
11555      * have a text change from V1 to V2, V2 to V3, ..., Vn.
11556      *
11557      * This function will then merge those changes into a single change range valid between V1 and
11558      * Vn.
11559      */
11560     function collapseTextChangeRangesAcrossMultipleVersions(changes) {
11561         if (changes.length === 0) {
11562             return ts.unchangedTextChangeRange;
11563         }
11564         if (changes.length === 1) {
11565             return changes[0];
11566         }
11567         // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
11568         // as it makes things much easier to reason about.
11569         var change0 = changes[0];
11570         var oldStartN = change0.span.start;
11571         var oldEndN = textSpanEnd(change0.span);
11572         var newEndN = oldStartN + change0.newLength;
11573         for (var i = 1; i < changes.length; i++) {
11574             var nextChange = changes[i];
11575             // Consider the following case:
11576             // i.e. two edits.  The first represents the text change range { { 10, 50 }, 30 }.  i.e. The span starting
11577             // at 10, with length 50 is reduced to length 30.  The second represents the text change range { { 30, 30 }, 40 }.
11578             // i.e. the span starting at 30 with length 30 is increased to length 40.
11579             //
11580             //      0         10        20        30        40        50        60        70        80        90        100
11581             //      -------------------------------------------------------------------------------------------------------
11582             //                |                                                 /
11583             //                |                                            /----
11584             //  T1            |                                       /----
11585             //                |                                  /----
11586             //                |                             /----
11587             //      -------------------------------------------------------------------------------------------------------
11588             //                                     |                            \
11589             //                                     |                               \
11590             //   T2                                |                                 \
11591             //                                     |                                   \
11592             //                                     |                                      \
11593             //      -------------------------------------------------------------------------------------------------------
11594             //
11595             // Merging these turns out to not be too difficult.  First, determining the new start of the change is trivial
11596             // it's just the min of the old and new starts.  i.e.:
11597             //
11598             //      0         10        20        30        40        50        60        70        80        90        100
11599             //      ------------------------------------------------------------*------------------------------------------
11600             //                |                                                 /
11601             //                |                                            /----
11602             //  T1            |                                       /----
11603             //                |                                  /----
11604             //                |                             /----
11605             //      ----------------------------------------$-------------------$------------------------------------------
11606             //                .                    |                            \
11607             //                .                    |                               \
11608             //   T2           .                    |                                 \
11609             //                .                    |                                   \
11610             //                .                    |                                      \
11611             //      ----------------------------------------------------------------------*--------------------------------
11612             //
11613             // (Note the dots represent the newly inferred start.
11614             // Determining the new and old end is also pretty simple.  Basically it boils down to paying attention to the
11615             // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
11616             // which if the two $'s precedes the other, and we move that one forward until they line up.  in this case that
11617             // means:
11618             //
11619             //      0         10        20        30        40        50        60        70        80        90        100
11620             //      --------------------------------------------------------------------------------*----------------------
11621             //                |                                                                     /
11622             //                |                                                                /----
11623             //  T1            |                                                           /----
11624             //                |                                                      /----
11625             //                |                                                 /----
11626             //      ------------------------------------------------------------$------------------------------------------
11627             //                .                    |                            \
11628             //                .                    |                               \
11629             //   T2           .                    |                                 \
11630             //                .                    |                                   \
11631             //                .                    |                                      \
11632             //      ----------------------------------------------------------------------*--------------------------------
11633             //
11634             // In other words (in this case), we're recognizing that the second edit happened after where the first edit
11635             // ended with a delta of 20 characters (60 - 40).  Thus, if we go back in time to where the first edit started
11636             // that's the same as if we started at char 80 instead of 60.
11637             //
11638             // As it so happens, the same logic applies if the second edit precedes the first edit.  In that case rather
11639             // than pushing the first edit forward to match the second, we'll push the second edit forward to match the
11640             // first.
11641             //
11642             // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
11643             // semantics: { { start: 10, length: 70 }, newLength: 60 }
11644             //
11645             // The math then works out as follows.
11646             // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
11647             // final result like so:
11648             //
11649             // {
11650             //      oldStart3: Min(oldStart1, oldStart2),
11651             //      oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
11652             //      newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
11653             // }
11654             var oldStart1 = oldStartN;
11655             var oldEnd1 = oldEndN;
11656             var newEnd1 = newEndN;
11657             var oldStart2 = nextChange.span.start;
11658             var oldEnd2 = textSpanEnd(nextChange.span);
11659             var newEnd2 = oldStart2 + nextChange.newLength;
11660             oldStartN = Math.min(oldStart1, oldStart2);
11661             oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
11662             newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
11663         }
11664         return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
11665     }
11666     ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
11667     function getTypeParameterOwner(d) {
11668         if (d && d.kind === 159 /* TypeParameter */) {
11669             for (var current = d; current; current = current.parent) {
11670                 if (isFunctionLike(current) || isClassLike(current) || current.kind === 253 /* InterfaceDeclaration */) {
11671                     return current;
11672                 }
11673             }
11674         }
11675     }
11676     ts.getTypeParameterOwner = getTypeParameterOwner;
11677     function isParameterPropertyDeclaration(node, parent) {
11678         return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 166 /* Constructor */;
11679     }
11680     ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
11681     function isEmptyBindingPattern(node) {
11682         if (isBindingPattern(node)) {
11683             return ts.every(node.elements, isEmptyBindingElement);
11684         }
11685         return false;
11686     }
11687     ts.isEmptyBindingPattern = isEmptyBindingPattern;
11688     function isEmptyBindingElement(node) {
11689         if (ts.isOmittedExpression(node)) {
11690             return true;
11691         }
11692         return isEmptyBindingPattern(node.name);
11693     }
11694     ts.isEmptyBindingElement = isEmptyBindingElement;
11695     function walkUpBindingElementsAndPatterns(binding) {
11696         var node = binding.parent;
11697         while (ts.isBindingElement(node.parent)) {
11698             node = node.parent.parent;
11699         }
11700         return node.parent;
11701     }
11702     ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
11703     function getCombinedFlags(node, getFlags) {
11704         if (ts.isBindingElement(node)) {
11705             node = walkUpBindingElementsAndPatterns(node);
11706         }
11707         var flags = getFlags(node);
11708         if (node.kind === 249 /* VariableDeclaration */) {
11709             node = node.parent;
11710         }
11711         if (node && node.kind === 250 /* VariableDeclarationList */) {
11712             flags |= getFlags(node);
11713             node = node.parent;
11714         }
11715         if (node && node.kind === 232 /* VariableStatement */) {
11716             flags |= getFlags(node);
11717         }
11718         return flags;
11719     }
11720     function getCombinedModifierFlags(node) {
11721         return getCombinedFlags(node, ts.getEffectiveModifierFlags);
11722     }
11723     ts.getCombinedModifierFlags = getCombinedModifierFlags;
11724     /* @internal */
11725     function getCombinedNodeFlagsAlwaysIncludeJSDoc(node) {
11726         return getCombinedFlags(node, ts.getEffectiveModifierFlagsAlwaysIncludeJSDoc);
11727     }
11728     ts.getCombinedNodeFlagsAlwaysIncludeJSDoc = getCombinedNodeFlagsAlwaysIncludeJSDoc;
11729     // Returns the node flags for this node and all relevant parent nodes.  This is done so that
11730     // nodes like variable declarations and binding elements can returned a view of their flags
11731     // that includes the modifiers from their container.  i.e. flags like export/declare aren't
11732     // stored on the variable declaration directly, but on the containing variable statement
11733     // (if it has one).  Similarly, flags for let/const are stored on the variable declaration
11734     // list.  By calling this function, all those flags are combined so that the client can treat
11735     // the node as if it actually had those flags.
11736     function getCombinedNodeFlags(node) {
11737         return getCombinedFlags(node, function (n) { return n.flags; });
11738     }
11739     ts.getCombinedNodeFlags = getCombinedNodeFlags;
11740     /* @internal */
11741     ts.supportedLocaleDirectories = ["cs", "de", "es", "fr", "it", "ja", "ko", "pl", "pt-br", "ru", "tr", "zh-cn", "zh-tw"];
11742     /**
11743      * Checks to see if the locale is in the appropriate format,
11744      * and if it is, attempts to set the appropriate language.
11745      */
11746     function validateLocaleAndSetLanguage(locale, sys, errors) {
11747         var lowerCaseLocale = locale.toLowerCase();
11748         var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(lowerCaseLocale);
11749         if (!matchResult) {
11750             if (errors) {
11751                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
11752             }
11753             return;
11754         }
11755         var language = matchResult[1];
11756         var territory = matchResult[3];
11757         // First try the entire locale, then fall back to just language if that's all we have.
11758         // Either ways do not fail, and fallback to the English diagnostic strings.
11759         if (ts.contains(ts.supportedLocaleDirectories, lowerCaseLocale) && !trySetLanguageAndTerritory(language, territory, errors)) {
11760             trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
11761         }
11762         // Set the UI locale for string collation
11763         ts.setUILocale(locale);
11764         function trySetLanguageAndTerritory(language, territory, errors) {
11765             var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
11766             var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
11767             var filePath = ts.combinePaths(containingDirectoryPath, language);
11768             if (territory) {
11769                 filePath = filePath + "-" + territory;
11770             }
11771             filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
11772             if (!sys.fileExists(filePath)) {
11773                 return false;
11774             }
11775             // TODO: Add codePage support for readFile?
11776             var fileContents = "";
11777             try {
11778                 fileContents = sys.readFile(filePath);
11779             }
11780             catch (e) {
11781                 if (errors) {
11782                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
11783                 }
11784                 return false;
11785             }
11786             try {
11787                 // this is a global mutation (or live binding update)!
11788                 ts.setLocalizedDiagnosticMessages(JSON.parse(fileContents));
11789             }
11790             catch (_a) {
11791                 if (errors) {
11792                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
11793                 }
11794                 return false;
11795             }
11796             return true;
11797         }
11798     }
11799     ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
11800     function getOriginalNode(node, nodeTest) {
11801         if (node) {
11802             while (node.original !== undefined) {
11803                 node = node.original;
11804             }
11805         }
11806         return !nodeTest || nodeTest(node) ? node : undefined;
11807     }
11808     ts.getOriginalNode = getOriginalNode;
11809     function findAncestor(node, callback) {
11810         while (node) {
11811             var result = callback(node);
11812             if (result === "quit") {
11813                 return undefined;
11814             }
11815             else if (result) {
11816                 return node;
11817             }
11818             node = node.parent;
11819         }
11820         return undefined;
11821     }
11822     ts.findAncestor = findAncestor;
11823     /**
11824      * Gets a value indicating whether a node originated in the parse tree.
11825      *
11826      * @param node The node to test.
11827      */
11828     function isParseTreeNode(node) {
11829         return (node.flags & 8 /* Synthesized */) === 0;
11830     }
11831     ts.isParseTreeNode = isParseTreeNode;
11832     function getParseTreeNode(node, nodeTest) {
11833         if (node === undefined || isParseTreeNode(node)) {
11834             return node;
11835         }
11836         node = node.original;
11837         while (node) {
11838             if (isParseTreeNode(node)) {
11839                 return !nodeTest || nodeTest(node) ? node : undefined;
11840             }
11841             node = node.original;
11842         }
11843     }
11844     ts.getParseTreeNode = getParseTreeNode;
11845     /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */
11846     function escapeLeadingUnderscores(identifier) {
11847         return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier);
11848     }
11849     ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
11850     /**
11851      * Remove extra underscore from escaped identifier text content.
11852      *
11853      * @param identifier The escaped identifier text.
11854      * @returns The unescaped identifier text.
11855      */
11856     function unescapeLeadingUnderscores(identifier) {
11857         var id = identifier;
11858         return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id;
11859     }
11860     ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
11861     function idText(identifierOrPrivateName) {
11862         return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
11863     }
11864     ts.idText = idText;
11865     function symbolName(symbol) {
11866         if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) {
11867             return idText(symbol.valueDeclaration.name);
11868         }
11869         return unescapeLeadingUnderscores(symbol.escapedName);
11870     }
11871     ts.symbolName = symbolName;
11872     /**
11873      * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
11874      * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
11875      * will be merged with)
11876      */
11877     function nameForNamelessJSDocTypedef(declaration) {
11878         var hostNode = declaration.parent.parent;
11879         if (!hostNode) {
11880             return undefined;
11881         }
11882         // Covers classes, functions - any named declaration host node
11883         if (isDeclaration(hostNode)) {
11884             return getDeclarationIdentifier(hostNode);
11885         }
11886         // Covers remaining cases (returning undefined if none match).
11887         switch (hostNode.kind) {
11888             case 232 /* VariableStatement */:
11889                 if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
11890                     return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
11891                 }
11892                 break;
11893             case 233 /* ExpressionStatement */:
11894                 var expr = hostNode.expression;
11895                 if (expr.kind === 216 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) {
11896                     expr = expr.left;
11897                 }
11898                 switch (expr.kind) {
11899                     case 201 /* PropertyAccessExpression */:
11900                         return expr.name;
11901                     case 202 /* ElementAccessExpression */:
11902                         var arg = expr.argumentExpression;
11903                         if (ts.isIdentifier(arg)) {
11904                             return arg;
11905                         }
11906                 }
11907                 break;
11908             case 207 /* ParenthesizedExpression */: {
11909                 return getDeclarationIdentifier(hostNode.expression);
11910             }
11911             case 245 /* LabeledStatement */: {
11912                 if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
11913                     return getDeclarationIdentifier(hostNode.statement);
11914                 }
11915                 break;
11916             }
11917         }
11918     }
11919     function getDeclarationIdentifier(node) {
11920         var name = getNameOfDeclaration(node);
11921         return name && ts.isIdentifier(name) ? name : undefined;
11922     }
11923     /** @internal */
11924     function nodeHasName(statement, name) {
11925         if (isNamedDeclaration(statement) && ts.isIdentifier(statement.name) && idText(statement.name) === idText(name)) {
11926             return true;
11927         }
11928         if (ts.isVariableStatement(statement) && ts.some(statement.declarationList.declarations, function (d) { return nodeHasName(d, name); })) {
11929             return true;
11930         }
11931         return false;
11932     }
11933     ts.nodeHasName = nodeHasName;
11934     function getNameOfJSDocTypedef(declaration) {
11935         return declaration.name || nameForNamelessJSDocTypedef(declaration);
11936     }
11937     ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
11938     /** @internal */
11939     function isNamedDeclaration(node) {
11940         return !!node.name; // A 'name' property should always be a DeclarationName.
11941     }
11942     ts.isNamedDeclaration = isNamedDeclaration;
11943     /** @internal */
11944     function getNonAssignedNameOfDeclaration(declaration) {
11945         switch (declaration.kind) {
11946             case 78 /* Identifier */:
11947                 return declaration;
11948             case 333 /* JSDocPropertyTag */:
11949             case 326 /* JSDocParameterTag */: {
11950                 var name = declaration.name;
11951                 if (name.kind === 157 /* QualifiedName */) {
11952                     return name.right;
11953                 }
11954                 break;
11955             }
11956             case 203 /* CallExpression */:
11957             case 216 /* BinaryExpression */: {
11958                 var expr_1 = declaration;
11959                 switch (ts.getAssignmentDeclarationKind(expr_1)) {
11960                     case 1 /* ExportsProperty */:
11961                     case 4 /* ThisProperty */:
11962                     case 5 /* Property */:
11963                     case 3 /* PrototypeProperty */:
11964                         return ts.getElementOrPropertyAccessArgumentExpressionOrName(expr_1.left);
11965                     case 7 /* ObjectDefinePropertyValue */:
11966                     case 8 /* ObjectDefinePropertyExports */:
11967                     case 9 /* ObjectDefinePrototypeProperty */:
11968                         return expr_1.arguments[1];
11969                     default:
11970                         return undefined;
11971                 }
11972             }
11973             case 331 /* JSDocTypedefTag */:
11974                 return getNameOfJSDocTypedef(declaration);
11975             case 325 /* JSDocEnumTag */:
11976                 return nameForNamelessJSDocTypedef(declaration);
11977             case 266 /* ExportAssignment */: {
11978                 var expression = declaration.expression;
11979                 return ts.isIdentifier(expression) ? expression : undefined;
11980             }
11981             case 202 /* ElementAccessExpression */:
11982                 var expr = declaration;
11983                 if (ts.isBindableStaticElementAccessExpression(expr)) {
11984                     return expr.argumentExpression;
11985                 }
11986         }
11987         return declaration.name;
11988     }
11989     ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
11990     function getNameOfDeclaration(declaration) {
11991         if (declaration === undefined)
11992             return undefined;
11993         return getNonAssignedNameOfDeclaration(declaration) ||
11994             (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
11995     }
11996     ts.getNameOfDeclaration = getNameOfDeclaration;
11997     /*@internal*/
11998     function getAssignedName(node) {
11999         if (!node.parent) {
12000             return undefined;
12001         }
12002         else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) {
12003             return node.parent.name;
12004         }
12005         else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) {
12006             if (ts.isIdentifier(node.parent.left)) {
12007                 return node.parent.left;
12008             }
12009             else if (ts.isAccessExpression(node.parent.left)) {
12010                 return ts.getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
12011             }
12012         }
12013         else if (ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) {
12014             return node.parent.name;
12015         }
12016     }
12017     ts.getAssignedName = getAssignedName;
12018     function getJSDocParameterTagsWorker(param, noCache) {
12019         if (param.name) {
12020             if (ts.isIdentifier(param.name)) {
12021                 var name_1 = param.name.escapedText;
12022                 return getJSDocTagsWorker(param.parent, noCache).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; });
12023             }
12024             else {
12025                 var i = param.parent.parameters.indexOf(param);
12026                 ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
12027                 var paramTags = getJSDocTagsWorker(param.parent, noCache).filter(ts.isJSDocParameterTag);
12028                 if (i < paramTags.length) {
12029                     return [paramTags[i]];
12030                 }
12031             }
12032         }
12033         // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
12034         return ts.emptyArray;
12035     }
12036     /**
12037      * Gets the JSDoc parameter tags for the node if present.
12038      *
12039      * @remarks Returns any JSDoc param tag whose name matches the provided
12040      * parameter, whether a param tag on a containing function
12041      * expression, or a param tag on a variable declaration whose
12042      * initializer is the containing function. The tags closest to the
12043      * node are returned first, so in the previous example, the param
12044      * tag on the containing function expression would be first.
12045      *
12046      * For binding patterns, parameter tags are matched by position.
12047      */
12048     function getJSDocParameterTags(param) {
12049         return getJSDocParameterTagsWorker(param, /*noCache*/ false);
12050     }
12051     ts.getJSDocParameterTags = getJSDocParameterTags;
12052     /* @internal */
12053     function getJSDocParameterTagsNoCache(param) {
12054         return getJSDocParameterTagsWorker(param, /*noCache*/ true);
12055     }
12056     ts.getJSDocParameterTagsNoCache = getJSDocParameterTagsNoCache;
12057     function getJSDocTypeParameterTagsWorker(param, noCache) {
12058         var name = param.name.escapedText;
12059         return getJSDocTagsWorker(param.parent, noCache).filter(function (tag) {
12060             return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
12061         });
12062     }
12063     /**
12064      * Gets the JSDoc type parameter tags for the node if present.
12065      *
12066      * @remarks Returns any JSDoc template tag whose names match the provided
12067      * parameter, whether a template tag on a containing function
12068      * expression, or a template tag on a variable declaration whose
12069      * initializer is the containing function. The tags closest to the
12070      * node are returned first, so in the previous example, the template
12071      * tag on the containing function expression would be first.
12072      */
12073     function getJSDocTypeParameterTags(param) {
12074         return getJSDocTypeParameterTagsWorker(param, /*noCache*/ false);
12075     }
12076     ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
12077     /* @internal */
12078     function getJSDocTypeParameterTagsNoCache(param) {
12079         return getJSDocTypeParameterTagsWorker(param, /*noCache*/ true);
12080     }
12081     ts.getJSDocTypeParameterTagsNoCache = getJSDocTypeParameterTagsNoCache;
12082     /**
12083      * Return true if the node has JSDoc parameter tags.
12084      *
12085      * @remarks Includes parameter tags that are not directly on the node,
12086      * for example on a variable declaration whose initializer is a function expression.
12087      */
12088     function hasJSDocParameterTags(node) {
12089         return !!getFirstJSDocTag(node, ts.isJSDocParameterTag);
12090     }
12091     ts.hasJSDocParameterTags = hasJSDocParameterTags;
12092     /** Gets the JSDoc augments tag for the node if present */
12093     function getJSDocAugmentsTag(node) {
12094         return getFirstJSDocTag(node, ts.isJSDocAugmentsTag);
12095     }
12096     ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
12097     /** Gets the JSDoc implements tags for the node if present */
12098     function getJSDocImplementsTags(node) {
12099         return getAllJSDocTags(node, ts.isJSDocImplementsTag);
12100     }
12101     ts.getJSDocImplementsTags = getJSDocImplementsTags;
12102     /** Gets the JSDoc class tag for the node if present */
12103     function getJSDocClassTag(node) {
12104         return getFirstJSDocTag(node, ts.isJSDocClassTag);
12105     }
12106     ts.getJSDocClassTag = getJSDocClassTag;
12107     /** Gets the JSDoc public tag for the node if present */
12108     function getJSDocPublicTag(node) {
12109         return getFirstJSDocTag(node, ts.isJSDocPublicTag);
12110     }
12111     ts.getJSDocPublicTag = getJSDocPublicTag;
12112     /*@internal*/
12113     function getJSDocPublicTagNoCache(node) {
12114         return getFirstJSDocTag(node, ts.isJSDocPublicTag, /*noCache*/ true);
12115     }
12116     ts.getJSDocPublicTagNoCache = getJSDocPublicTagNoCache;
12117     /** Gets the JSDoc private tag for the node if present */
12118     function getJSDocPrivateTag(node) {
12119         return getFirstJSDocTag(node, ts.isJSDocPrivateTag);
12120     }
12121     ts.getJSDocPrivateTag = getJSDocPrivateTag;
12122     /*@internal*/
12123     function getJSDocPrivateTagNoCache(node) {
12124         return getFirstJSDocTag(node, ts.isJSDocPrivateTag, /*noCache*/ true);
12125     }
12126     ts.getJSDocPrivateTagNoCache = getJSDocPrivateTagNoCache;
12127     /** Gets the JSDoc protected tag for the node if present */
12128     function getJSDocProtectedTag(node) {
12129         return getFirstJSDocTag(node, ts.isJSDocProtectedTag);
12130     }
12131     ts.getJSDocProtectedTag = getJSDocProtectedTag;
12132     /*@internal*/
12133     function getJSDocProtectedTagNoCache(node) {
12134         return getFirstJSDocTag(node, ts.isJSDocProtectedTag, /*noCache*/ true);
12135     }
12136     ts.getJSDocProtectedTagNoCache = getJSDocProtectedTagNoCache;
12137     /** Gets the JSDoc protected tag for the node if present */
12138     function getJSDocReadonlyTag(node) {
12139         return getFirstJSDocTag(node, ts.isJSDocReadonlyTag);
12140     }
12141     ts.getJSDocReadonlyTag = getJSDocReadonlyTag;
12142     /*@internal*/
12143     function getJSDocReadonlyTagNoCache(node) {
12144         return getFirstJSDocTag(node, ts.isJSDocReadonlyTag, /*noCache*/ true);
12145     }
12146     ts.getJSDocReadonlyTagNoCache = getJSDocReadonlyTagNoCache;
12147     /** Gets the JSDoc deprecated tag for the node if present */
12148     function getJSDocDeprecatedTag(node) {
12149         return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag);
12150     }
12151     ts.getJSDocDeprecatedTag = getJSDocDeprecatedTag;
12152     /*@internal */
12153     function getJSDocDeprecatedTagNoCache(node) {
12154         return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag, /*noCache*/ true);
12155     }
12156     ts.getJSDocDeprecatedTagNoCache = getJSDocDeprecatedTagNoCache;
12157     /** Gets the JSDoc enum tag for the node if present */
12158     function getJSDocEnumTag(node) {
12159         return getFirstJSDocTag(node, ts.isJSDocEnumTag);
12160     }
12161     ts.getJSDocEnumTag = getJSDocEnumTag;
12162     /** Gets the JSDoc this tag for the node if present */
12163     function getJSDocThisTag(node) {
12164         return getFirstJSDocTag(node, ts.isJSDocThisTag);
12165     }
12166     ts.getJSDocThisTag = getJSDocThisTag;
12167     /** Gets the JSDoc return tag for the node if present */
12168     function getJSDocReturnTag(node) {
12169         return getFirstJSDocTag(node, ts.isJSDocReturnTag);
12170     }
12171     ts.getJSDocReturnTag = getJSDocReturnTag;
12172     /** Gets the JSDoc template tag for the node if present */
12173     function getJSDocTemplateTag(node) {
12174         return getFirstJSDocTag(node, ts.isJSDocTemplateTag);
12175     }
12176     ts.getJSDocTemplateTag = getJSDocTemplateTag;
12177     /** Gets the JSDoc type tag for the node if present and valid */
12178     function getJSDocTypeTag(node) {
12179         // We should have already issued an error if there were multiple type jsdocs, so just use the first one.
12180         var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
12181         if (tag && tag.typeExpression && tag.typeExpression.type) {
12182             return tag;
12183         }
12184         return undefined;
12185     }
12186     ts.getJSDocTypeTag = getJSDocTypeTag;
12187     /**
12188      * Gets the type node for the node if provided via JSDoc.
12189      *
12190      * @remarks The search includes any JSDoc param tag that relates
12191      * to the provided parameter, for example a type tag on the
12192      * parameter itself, or a param tag on a containing function
12193      * expression, or a param tag on a variable declaration whose
12194      * initializer is the containing function. The tags closest to the
12195      * node are examined first, so in the previous example, the type
12196      * tag directly on the node would be returned.
12197      */
12198     function getJSDocType(node) {
12199         var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
12200         if (!tag && ts.isParameter(node)) {
12201             tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
12202         }
12203         return tag && tag.typeExpression && tag.typeExpression.type;
12204     }
12205     ts.getJSDocType = getJSDocType;
12206     /**
12207      * Gets the return type node for the node if provided via JSDoc return tag or type tag.
12208      *
12209      * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
12210      * gets the type from inside the braces, after the fat arrow, etc.
12211      */
12212     function getJSDocReturnType(node) {
12213         var returnTag = getJSDocReturnTag(node);
12214         if (returnTag && returnTag.typeExpression) {
12215             return returnTag.typeExpression.type;
12216         }
12217         var typeTag = getJSDocTypeTag(node);
12218         if (typeTag && typeTag.typeExpression) {
12219             var type = typeTag.typeExpression.type;
12220             if (ts.isTypeLiteralNode(type)) {
12221                 var sig = ts.find(type.members, ts.isCallSignatureDeclaration);
12222                 return sig && sig.type;
12223             }
12224             if (ts.isFunctionTypeNode(type) || ts.isJSDocFunctionType(type)) {
12225                 return type.type;
12226             }
12227         }
12228     }
12229     ts.getJSDocReturnType = getJSDocReturnType;
12230     function getJSDocTagsWorker(node, noCache) {
12231         var tags = node.jsDocCache;
12232         // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
12233         if (tags === undefined || noCache) {
12234             var comments = ts.getJSDocCommentsAndTags(node, noCache);
12235             ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
12236             tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; });
12237             if (!noCache) {
12238                 node.jsDocCache = tags;
12239             }
12240         }
12241         return tags;
12242     }
12243     /** Get all JSDoc tags related to a node, including those on parent nodes. */
12244     function getJSDocTags(node) {
12245         return getJSDocTagsWorker(node, /*noCache*/ false);
12246     }
12247     ts.getJSDocTags = getJSDocTags;
12248     /* @internal */
12249     function getJSDocTagsNoCache(node) {
12250         return getJSDocTagsWorker(node, /*noCache*/ true);
12251     }
12252     ts.getJSDocTagsNoCache = getJSDocTagsNoCache;
12253     /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
12254     function getFirstJSDocTag(node, predicate, noCache) {
12255         return ts.find(getJSDocTagsWorker(node, noCache), predicate);
12256     }
12257     /** Gets all JSDoc tags that match a specified predicate */
12258     function getAllJSDocTags(node, predicate) {
12259         return getJSDocTags(node).filter(predicate);
12260     }
12261     ts.getAllJSDocTags = getAllJSDocTags;
12262     /** Gets all JSDoc tags of a specified kind */
12263     function getAllJSDocTagsOfKind(node, kind) {
12264         return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
12265     }
12266     ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
12267     /**
12268      * Gets the effective type parameters. If the node was parsed in a
12269      * JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
12270      */
12271     function getEffectiveTypeParameterDeclarations(node) {
12272         if (ts.isJSDocSignature(node)) {
12273             return ts.emptyArray;
12274         }
12275         if (ts.isJSDocTypeAlias(node)) {
12276             ts.Debug.assert(node.parent.kind === 311 /* JSDocComment */);
12277             return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
12278         }
12279         if (node.typeParameters) {
12280             return node.typeParameters;
12281         }
12282         if (ts.isInJSFile(node)) {
12283             var decls = ts.getJSDocTypeParameterDeclarations(node);
12284             if (decls.length) {
12285                 return decls;
12286             }
12287             var typeTag = getJSDocType(node);
12288             if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
12289                 return typeTag.typeParameters;
12290             }
12291         }
12292         return ts.emptyArray;
12293     }
12294     ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
12295     function getEffectiveConstraintOfTypeParameter(node) {
12296         return node.constraint ? node.constraint :
12297             ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint :
12298                 undefined;
12299     }
12300     ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
12301     // #region
12302     function isIdentifierOrPrivateIdentifier(node) {
12303         return node.kind === 78 /* Identifier */ || node.kind === 79 /* PrivateIdentifier */;
12304     }
12305     ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier;
12306     /* @internal */
12307     function isGetOrSetAccessorDeclaration(node) {
12308         return node.kind === 168 /* SetAccessor */ || node.kind === 167 /* GetAccessor */;
12309     }
12310     ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
12311     function isPropertyAccessChain(node) {
12312         return ts.isPropertyAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12313     }
12314     ts.isPropertyAccessChain = isPropertyAccessChain;
12315     function isElementAccessChain(node) {
12316         return ts.isElementAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12317     }
12318     ts.isElementAccessChain = isElementAccessChain;
12319     function isCallChain(node) {
12320         return ts.isCallExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12321     }
12322     ts.isCallChain = isCallChain;
12323     function isOptionalChain(node) {
12324         var kind = node.kind;
12325         return !!(node.flags & 32 /* OptionalChain */) &&
12326             (kind === 201 /* PropertyAccessExpression */
12327                 || kind === 202 /* ElementAccessExpression */
12328                 || kind === 203 /* CallExpression */
12329                 || kind === 225 /* NonNullExpression */);
12330     }
12331     ts.isOptionalChain = isOptionalChain;
12332     /* @internal */
12333     function isOptionalChainRoot(node) {
12334         return isOptionalChain(node) && !ts.isNonNullExpression(node) && !!node.questionDotToken;
12335     }
12336     ts.isOptionalChainRoot = isOptionalChainRoot;
12337     /**
12338      * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
12339      */
12340     /* @internal */
12341     function isExpressionOfOptionalChainRoot(node) {
12342         return isOptionalChainRoot(node.parent) && node.parent.expression === node;
12343     }
12344     ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot;
12345     /**
12346      * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`:
12347      *
12348      * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`)
12349      * 2. For `a?.b!`, the outermost chain is `a?.b` (`b` is the end of the chain starting at `a?.`)
12350      * 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)
12351      * 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
12352      *   the end of the chain starting at `c?.`)
12353      * 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
12354      *   the end of the chain starting at `a?.`)
12355      */
12356     /* @internal */
12357     function isOutermostOptionalChain(node) {
12358         return !isOptionalChain(node.parent) // cases 1, 2, and 3
12359             || isOptionalChainRoot(node.parent) // case 4
12360             || node !== node.parent.expression; // case 5
12361     }
12362     ts.isOutermostOptionalChain = isOutermostOptionalChain;
12363     function isNullishCoalesce(node) {
12364         return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */;
12365     }
12366     ts.isNullishCoalesce = isNullishCoalesce;
12367     function isConstTypeReference(node) {
12368         return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) &&
12369             node.typeName.escapedText === "const" && !node.typeArguments;
12370     }
12371     ts.isConstTypeReference = isConstTypeReference;
12372     function skipPartiallyEmittedExpressions(node) {
12373         return ts.skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */);
12374     }
12375     ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
12376     function isNonNullChain(node) {
12377         return ts.isNonNullExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12378     }
12379     ts.isNonNullChain = isNonNullChain;
12380     function isBreakOrContinueStatement(node) {
12381         return node.kind === 241 /* BreakStatement */ || node.kind === 240 /* ContinueStatement */;
12382     }
12383     ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
12384     function isNamedExportBindings(node) {
12385         return node.kind === 269 /* NamespaceExport */ || node.kind === 268 /* NamedExports */;
12386     }
12387     ts.isNamedExportBindings = isNamedExportBindings;
12388     function isUnparsedTextLike(node) {
12389         switch (node.kind) {
12390             case 294 /* UnparsedText */:
12391             case 295 /* UnparsedInternalText */:
12392                 return true;
12393             default:
12394                 return false;
12395         }
12396     }
12397     ts.isUnparsedTextLike = isUnparsedTextLike;
12398     function isUnparsedNode(node) {
12399         return isUnparsedTextLike(node) ||
12400             node.kind === 292 /* UnparsedPrologue */ ||
12401             node.kind === 296 /* UnparsedSyntheticReference */;
12402     }
12403     ts.isUnparsedNode = isUnparsedNode;
12404     function isJSDocPropertyLikeTag(node) {
12405         return node.kind === 333 /* JSDocPropertyTag */ || node.kind === 326 /* JSDocParameterTag */;
12406     }
12407     ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
12408     // #endregion
12409     // #region
12410     // Node tests
12411     //
12412     // All node tests in the following list should *not* reference parent pointers so that
12413     // they may be used with transformations.
12414     /* @internal */
12415     function isNode(node) {
12416         return isNodeKind(node.kind);
12417     }
12418     ts.isNode = isNode;
12419     /* @internal */
12420     function isNodeKind(kind) {
12421         return kind >= 157 /* FirstNode */;
12422     }
12423     ts.isNodeKind = isNodeKind;
12424     /**
12425      * True if node is of some token syntax kind.
12426      * For example, this is true for an IfKeyword but not for an IfStatement.
12427      * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
12428      */
12429     function isToken(n) {
12430         return n.kind >= 0 /* FirstToken */ && n.kind <= 156 /* LastToken */;
12431     }
12432     ts.isToken = isToken;
12433     // Node Arrays
12434     /* @internal */
12435     function isNodeArray(array) {
12436         return array.hasOwnProperty("pos") && array.hasOwnProperty("end");
12437     }
12438     ts.isNodeArray = isNodeArray;
12439     // Literals
12440     /* @internal */
12441     function isLiteralKind(kind) {
12442         return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */;
12443     }
12444     ts.isLiteralKind = isLiteralKind;
12445     function isLiteralExpression(node) {
12446         return isLiteralKind(node.kind);
12447     }
12448     ts.isLiteralExpression = isLiteralExpression;
12449     // Pseudo-literals
12450     /* @internal */
12451     function isTemplateLiteralKind(kind) {
12452         return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */;
12453     }
12454     ts.isTemplateLiteralKind = isTemplateLiteralKind;
12455     function isTemplateLiteralToken(node) {
12456         return isTemplateLiteralKind(node.kind);
12457     }
12458     ts.isTemplateLiteralToken = isTemplateLiteralToken;
12459     function isTemplateMiddleOrTemplateTail(node) {
12460         var kind = node.kind;
12461         return kind === 16 /* TemplateMiddle */
12462             || kind === 17 /* TemplateTail */;
12463     }
12464     ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
12465     function isImportOrExportSpecifier(node) {
12466         return ts.isImportSpecifier(node) || ts.isExportSpecifier(node);
12467     }
12468     ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
12469     function isTypeOnlyImportOrExportDeclaration(node) {
12470         switch (node.kind) {
12471             case 265 /* ImportSpecifier */:
12472             case 270 /* ExportSpecifier */:
12473                 return node.parent.parent.isTypeOnly;
12474             case 263 /* NamespaceImport */:
12475                 return node.parent.isTypeOnly;
12476             case 262 /* ImportClause */:
12477             case 260 /* ImportEqualsDeclaration */:
12478                 return node.isTypeOnly;
12479             default:
12480                 return false;
12481         }
12482     }
12483     ts.isTypeOnlyImportOrExportDeclaration = isTypeOnlyImportOrExportDeclaration;
12484     function isStringTextContainingNode(node) {
12485         return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
12486     }
12487     ts.isStringTextContainingNode = isStringTextContainingNode;
12488     // Identifiers
12489     /* @internal */
12490     function isGeneratedIdentifier(node) {
12491         return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
12492     }
12493     ts.isGeneratedIdentifier = isGeneratedIdentifier;
12494     // Private Identifiers
12495     /*@internal*/
12496     function isPrivateIdentifierPropertyDeclaration(node) {
12497         return ts.isPropertyDeclaration(node) && ts.isPrivateIdentifier(node.name);
12498     }
12499     ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration;
12500     /*@internal*/
12501     function isPrivateIdentifierPropertyAccessExpression(node) {
12502         return ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name);
12503     }
12504     ts.isPrivateIdentifierPropertyAccessExpression = isPrivateIdentifierPropertyAccessExpression;
12505     // Keywords
12506     /* @internal */
12507     function isModifierKind(token) {
12508         switch (token) {
12509             case 125 /* AbstractKeyword */:
12510             case 129 /* AsyncKeyword */:
12511             case 84 /* ConstKeyword */:
12512             case 133 /* DeclareKeyword */:
12513             case 87 /* DefaultKeyword */:
12514             case 92 /* ExportKeyword */:
12515             case 122 /* PublicKeyword */:
12516             case 120 /* PrivateKeyword */:
12517             case 121 /* ProtectedKeyword */:
12518             case 142 /* ReadonlyKeyword */:
12519             case 123 /* StaticKeyword */:
12520                 return true;
12521         }
12522         return false;
12523     }
12524     ts.isModifierKind = isModifierKind;
12525     /* @internal */
12526     function isParameterPropertyModifier(kind) {
12527         return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */);
12528     }
12529     ts.isParameterPropertyModifier = isParameterPropertyModifier;
12530     /* @internal */
12531     function isClassMemberModifier(idToken) {
12532         return isParameterPropertyModifier(idToken) || idToken === 123 /* StaticKeyword */;
12533     }
12534     ts.isClassMemberModifier = isClassMemberModifier;
12535     function isModifier(node) {
12536         return isModifierKind(node.kind);
12537     }
12538     ts.isModifier = isModifier;
12539     function isEntityName(node) {
12540         var kind = node.kind;
12541         return kind === 157 /* QualifiedName */
12542             || kind === 78 /* Identifier */;
12543     }
12544     ts.isEntityName = isEntityName;
12545     function isPropertyName(node) {
12546         var kind = node.kind;
12547         return kind === 78 /* Identifier */
12548             || kind === 79 /* PrivateIdentifier */
12549             || kind === 10 /* StringLiteral */
12550             || kind === 8 /* NumericLiteral */
12551             || kind === 158 /* ComputedPropertyName */;
12552     }
12553     ts.isPropertyName = isPropertyName;
12554     function isBindingName(node) {
12555         var kind = node.kind;
12556         return kind === 78 /* Identifier */
12557             || kind === 196 /* ObjectBindingPattern */
12558             || kind === 197 /* ArrayBindingPattern */;
12559     }
12560     ts.isBindingName = isBindingName;
12561     // Functions
12562     function isFunctionLike(node) {
12563         return node && isFunctionLikeKind(node.kind);
12564     }
12565     ts.isFunctionLike = isFunctionLike;
12566     /* @internal */
12567     function isFunctionLikeDeclaration(node) {
12568         return node && isFunctionLikeDeclarationKind(node.kind);
12569     }
12570     ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
12571     function isFunctionLikeDeclarationKind(kind) {
12572         switch (kind) {
12573             case 251 /* FunctionDeclaration */:
12574             case 165 /* MethodDeclaration */:
12575             case 166 /* Constructor */:
12576             case 167 /* GetAccessor */:
12577             case 168 /* SetAccessor */:
12578             case 208 /* FunctionExpression */:
12579             case 209 /* ArrowFunction */:
12580                 return true;
12581             default:
12582                 return false;
12583         }
12584     }
12585     /* @internal */
12586     function isFunctionLikeKind(kind) {
12587         switch (kind) {
12588             case 164 /* MethodSignature */:
12589             case 169 /* CallSignature */:
12590             case 313 /* JSDocSignature */:
12591             case 170 /* ConstructSignature */:
12592             case 171 /* IndexSignature */:
12593             case 174 /* FunctionType */:
12594             case 308 /* JSDocFunctionType */:
12595             case 175 /* ConstructorType */:
12596                 return true;
12597             default:
12598                 return isFunctionLikeDeclarationKind(kind);
12599         }
12600     }
12601     ts.isFunctionLikeKind = isFunctionLikeKind;
12602     /* @internal */
12603     function isFunctionOrModuleBlock(node) {
12604         return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent);
12605     }
12606     ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
12607     // Classes
12608     function isClassElement(node) {
12609         var kind = node.kind;
12610         return kind === 166 /* Constructor */
12611             || kind === 163 /* PropertyDeclaration */
12612             || kind === 165 /* MethodDeclaration */
12613             || kind === 167 /* GetAccessor */
12614             || kind === 168 /* SetAccessor */
12615             || kind === 171 /* IndexSignature */
12616             || kind === 229 /* SemicolonClassElement */;
12617     }
12618     ts.isClassElement = isClassElement;
12619     function isClassLike(node) {
12620         return node && (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */);
12621     }
12622     ts.isClassLike = isClassLike;
12623     function isAccessor(node) {
12624         return node && (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */);
12625     }
12626     ts.isAccessor = isAccessor;
12627     /* @internal */
12628     function isMethodOrAccessor(node) {
12629         switch (node.kind) {
12630             case 165 /* MethodDeclaration */:
12631             case 167 /* GetAccessor */:
12632             case 168 /* SetAccessor */:
12633                 return true;
12634             default:
12635                 return false;
12636         }
12637     }
12638     ts.isMethodOrAccessor = isMethodOrAccessor;
12639     // Type members
12640     function isTypeElement(node) {
12641         var kind = node.kind;
12642         return kind === 170 /* ConstructSignature */
12643             || kind === 169 /* CallSignature */
12644             || kind === 162 /* PropertySignature */
12645             || kind === 164 /* MethodSignature */
12646             || kind === 171 /* IndexSignature */;
12647     }
12648     ts.isTypeElement = isTypeElement;
12649     function isClassOrTypeElement(node) {
12650         return isTypeElement(node) || isClassElement(node);
12651     }
12652     ts.isClassOrTypeElement = isClassOrTypeElement;
12653     function isObjectLiteralElementLike(node) {
12654         var kind = node.kind;
12655         return kind === 288 /* PropertyAssignment */
12656             || kind === 289 /* ShorthandPropertyAssignment */
12657             || kind === 290 /* SpreadAssignment */
12658             || kind === 165 /* MethodDeclaration */
12659             || kind === 167 /* GetAccessor */
12660             || kind === 168 /* SetAccessor */;
12661     }
12662     ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
12663     // Type
12664     /**
12665      * Node test that determines whether a node is a valid type node.
12666      * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
12667      * of a TypeNode.
12668      */
12669     function isTypeNode(node) {
12670         return ts.isTypeNodeKind(node.kind);
12671     }
12672     ts.isTypeNode = isTypeNode;
12673     function isFunctionOrConstructorTypeNode(node) {
12674         switch (node.kind) {
12675             case 174 /* FunctionType */:
12676             case 175 /* ConstructorType */:
12677                 return true;
12678         }
12679         return false;
12680     }
12681     ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
12682     // Binding patterns
12683     /* @internal */
12684     function isBindingPattern(node) {
12685         if (node) {
12686             var kind = node.kind;
12687             return kind === 197 /* ArrayBindingPattern */
12688                 || kind === 196 /* ObjectBindingPattern */;
12689         }
12690         return false;
12691     }
12692     ts.isBindingPattern = isBindingPattern;
12693     /* @internal */
12694     function isAssignmentPattern(node) {
12695         var kind = node.kind;
12696         return kind === 199 /* ArrayLiteralExpression */
12697             || kind === 200 /* ObjectLiteralExpression */;
12698     }
12699     ts.isAssignmentPattern = isAssignmentPattern;
12700     /* @internal */
12701     function isArrayBindingElement(node) {
12702         var kind = node.kind;
12703         return kind === 198 /* BindingElement */
12704             || kind === 222 /* OmittedExpression */;
12705     }
12706     ts.isArrayBindingElement = isArrayBindingElement;
12707     /**
12708      * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
12709      */
12710     /* @internal */
12711     function isDeclarationBindingElement(bindingElement) {
12712         switch (bindingElement.kind) {
12713             case 249 /* VariableDeclaration */:
12714             case 160 /* Parameter */:
12715             case 198 /* BindingElement */:
12716                 return true;
12717         }
12718         return false;
12719     }
12720     ts.isDeclarationBindingElement = isDeclarationBindingElement;
12721     /**
12722      * Determines whether a node is a BindingOrAssignmentPattern
12723      */
12724     /* @internal */
12725     function isBindingOrAssignmentPattern(node) {
12726         return isObjectBindingOrAssignmentPattern(node)
12727             || isArrayBindingOrAssignmentPattern(node);
12728     }
12729     ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern;
12730     /**
12731      * Determines whether a node is an ObjectBindingOrAssignmentPattern
12732      */
12733     /* @internal */
12734     function isObjectBindingOrAssignmentPattern(node) {
12735         switch (node.kind) {
12736             case 196 /* ObjectBindingPattern */:
12737             case 200 /* ObjectLiteralExpression */:
12738                 return true;
12739         }
12740         return false;
12741     }
12742     ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
12743     /**
12744      * Determines whether a node is an ArrayBindingOrAssignmentPattern
12745      */
12746     /* @internal */
12747     function isArrayBindingOrAssignmentPattern(node) {
12748         switch (node.kind) {
12749             case 197 /* ArrayBindingPattern */:
12750             case 199 /* ArrayLiteralExpression */:
12751                 return true;
12752         }
12753         return false;
12754     }
12755     ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
12756     /* @internal */
12757     function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
12758         var kind = node.kind;
12759         return kind === 201 /* PropertyAccessExpression */
12760             || kind === 157 /* QualifiedName */
12761             || kind === 195 /* ImportType */;
12762     }
12763     ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
12764     // Expression
12765     function isPropertyAccessOrQualifiedName(node) {
12766         var kind = node.kind;
12767         return kind === 201 /* PropertyAccessExpression */
12768             || kind === 157 /* QualifiedName */;
12769     }
12770     ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
12771     function isCallLikeExpression(node) {
12772         switch (node.kind) {
12773             case 275 /* JsxOpeningElement */:
12774             case 274 /* JsxSelfClosingElement */:
12775             case 203 /* CallExpression */:
12776             case 204 /* NewExpression */:
12777             case 205 /* TaggedTemplateExpression */:
12778             case 161 /* Decorator */:
12779                 return true;
12780             default:
12781                 return false;
12782         }
12783     }
12784     ts.isCallLikeExpression = isCallLikeExpression;
12785     function isCallOrNewExpression(node) {
12786         return node.kind === 203 /* CallExpression */ || node.kind === 204 /* NewExpression */;
12787     }
12788     ts.isCallOrNewExpression = isCallOrNewExpression;
12789     function isTemplateLiteral(node) {
12790         var kind = node.kind;
12791         return kind === 218 /* TemplateExpression */
12792             || kind === 14 /* NoSubstitutionTemplateLiteral */;
12793     }
12794     ts.isTemplateLiteral = isTemplateLiteral;
12795     /* @internal */
12796     function isLeftHandSideExpression(node) {
12797         return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12798     }
12799     ts.isLeftHandSideExpression = isLeftHandSideExpression;
12800     function isLeftHandSideExpressionKind(kind) {
12801         switch (kind) {
12802             case 201 /* PropertyAccessExpression */:
12803             case 202 /* ElementAccessExpression */:
12804             case 204 /* NewExpression */:
12805             case 203 /* CallExpression */:
12806             case 273 /* JsxElement */:
12807             case 274 /* JsxSelfClosingElement */:
12808             case 277 /* JsxFragment */:
12809             case 205 /* TaggedTemplateExpression */:
12810             case 199 /* ArrayLiteralExpression */:
12811             case 207 /* ParenthesizedExpression */:
12812             case 200 /* ObjectLiteralExpression */:
12813             case 221 /* ClassExpression */:
12814             case 208 /* FunctionExpression */:
12815             case 78 /* Identifier */:
12816             case 13 /* RegularExpressionLiteral */:
12817             case 8 /* NumericLiteral */:
12818             case 9 /* BigIntLiteral */:
12819             case 10 /* StringLiteral */:
12820             case 14 /* NoSubstitutionTemplateLiteral */:
12821             case 218 /* TemplateExpression */:
12822             case 94 /* FalseKeyword */:
12823             case 103 /* NullKeyword */:
12824             case 107 /* ThisKeyword */:
12825             case 109 /* TrueKeyword */:
12826             case 105 /* SuperKeyword */:
12827             case 225 /* NonNullExpression */:
12828             case 226 /* MetaProperty */:
12829             case 99 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
12830                 return true;
12831             default:
12832                 return false;
12833         }
12834     }
12835     /* @internal */
12836     function isUnaryExpression(node) {
12837         return isUnaryExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12838     }
12839     ts.isUnaryExpression = isUnaryExpression;
12840     function isUnaryExpressionKind(kind) {
12841         switch (kind) {
12842             case 214 /* PrefixUnaryExpression */:
12843             case 215 /* PostfixUnaryExpression */:
12844             case 210 /* DeleteExpression */:
12845             case 211 /* TypeOfExpression */:
12846             case 212 /* VoidExpression */:
12847             case 213 /* AwaitExpression */:
12848             case 206 /* TypeAssertionExpression */:
12849                 return true;
12850             default:
12851                 return isLeftHandSideExpressionKind(kind);
12852         }
12853     }
12854     /* @internal */
12855     function isUnaryExpressionWithWrite(expr) {
12856         switch (expr.kind) {
12857             case 215 /* PostfixUnaryExpression */:
12858                 return true;
12859             case 214 /* PrefixUnaryExpression */:
12860                 return expr.operator === 45 /* PlusPlusToken */ ||
12861                     expr.operator === 46 /* MinusMinusToken */;
12862             default:
12863                 return false;
12864         }
12865     }
12866     ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite;
12867     /* @internal */
12868     /**
12869      * Determines whether a node is an expression based only on its kind.
12870      * Use `isExpressionNode` if not in transforms.
12871      */
12872     function isExpression(node) {
12873         return isExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12874     }
12875     ts.isExpression = isExpression;
12876     function isExpressionKind(kind) {
12877         switch (kind) {
12878             case 217 /* ConditionalExpression */:
12879             case 219 /* YieldExpression */:
12880             case 209 /* ArrowFunction */:
12881             case 216 /* BinaryExpression */:
12882             case 220 /* SpreadElement */:
12883             case 224 /* AsExpression */:
12884             case 222 /* OmittedExpression */:
12885             case 337 /* CommaListExpression */:
12886             case 336 /* PartiallyEmittedExpression */:
12887                 return true;
12888             default:
12889                 return isUnaryExpressionKind(kind);
12890         }
12891     }
12892     function isAssertionExpression(node) {
12893         var kind = node.kind;
12894         return kind === 206 /* TypeAssertionExpression */
12895             || kind === 224 /* AsExpression */;
12896     }
12897     ts.isAssertionExpression = isAssertionExpression;
12898     /* @internal */
12899     function isNotEmittedOrPartiallyEmittedNode(node) {
12900         return ts.isNotEmittedStatement(node)
12901             || ts.isPartiallyEmittedExpression(node);
12902     }
12903     ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
12904     function isIterationStatement(node, lookInLabeledStatements) {
12905         switch (node.kind) {
12906             case 237 /* ForStatement */:
12907             case 238 /* ForInStatement */:
12908             case 239 /* ForOfStatement */:
12909             case 235 /* DoStatement */:
12910             case 236 /* WhileStatement */:
12911                 return true;
12912             case 245 /* LabeledStatement */:
12913                 return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
12914         }
12915         return false;
12916     }
12917     ts.isIterationStatement = isIterationStatement;
12918     /* @internal */
12919     function isScopeMarker(node) {
12920         return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
12921     }
12922     ts.isScopeMarker = isScopeMarker;
12923     /* @internal */
12924     function hasScopeMarker(statements) {
12925         return ts.some(statements, isScopeMarker);
12926     }
12927     ts.hasScopeMarker = hasScopeMarker;
12928     /* @internal */
12929     function needsScopeMarker(result) {
12930         return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasSyntacticModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
12931     }
12932     ts.needsScopeMarker = needsScopeMarker;
12933     /* @internal */
12934     function isExternalModuleIndicator(result) {
12935         // Exported top-level member indicates moduleness
12936         return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasSyntacticModifier(result, 1 /* Export */);
12937     }
12938     ts.isExternalModuleIndicator = isExternalModuleIndicator;
12939     /* @internal */
12940     function isForInOrOfStatement(node) {
12941         return node.kind === 238 /* ForInStatement */ || node.kind === 239 /* ForOfStatement */;
12942     }
12943     ts.isForInOrOfStatement = isForInOrOfStatement;
12944     // Element
12945     /* @internal */
12946     function isConciseBody(node) {
12947         return ts.isBlock(node)
12948             || isExpression(node);
12949     }
12950     ts.isConciseBody = isConciseBody;
12951     /* @internal */
12952     function isFunctionBody(node) {
12953         return ts.isBlock(node);
12954     }
12955     ts.isFunctionBody = isFunctionBody;
12956     /* @internal */
12957     function isForInitializer(node) {
12958         return ts.isVariableDeclarationList(node)
12959             || isExpression(node);
12960     }
12961     ts.isForInitializer = isForInitializer;
12962     /* @internal */
12963     function isModuleBody(node) {
12964         var kind = node.kind;
12965         return kind === 257 /* ModuleBlock */
12966             || kind === 256 /* ModuleDeclaration */
12967             || kind === 78 /* Identifier */;
12968     }
12969     ts.isModuleBody = isModuleBody;
12970     /* @internal */
12971     function isNamespaceBody(node) {
12972         var kind = node.kind;
12973         return kind === 257 /* ModuleBlock */
12974             || kind === 256 /* ModuleDeclaration */;
12975     }
12976     ts.isNamespaceBody = isNamespaceBody;
12977     /* @internal */
12978     function isJSDocNamespaceBody(node) {
12979         var kind = node.kind;
12980         return kind === 78 /* Identifier */
12981             || kind === 256 /* ModuleDeclaration */;
12982     }
12983     ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
12984     /* @internal */
12985     function isNamedImportBindings(node) {
12986         var kind = node.kind;
12987         return kind === 264 /* NamedImports */
12988             || kind === 263 /* NamespaceImport */;
12989     }
12990     ts.isNamedImportBindings = isNamedImportBindings;
12991     /* @internal */
12992     function isModuleOrEnumDeclaration(node) {
12993         return node.kind === 256 /* ModuleDeclaration */ || node.kind === 255 /* EnumDeclaration */;
12994     }
12995     ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
12996     function isDeclarationKind(kind) {
12997         return kind === 209 /* ArrowFunction */
12998             || kind === 198 /* BindingElement */
12999             || kind === 252 /* ClassDeclaration */
13000             || kind === 221 /* ClassExpression */
13001             || kind === 166 /* Constructor */
13002             || kind === 255 /* EnumDeclaration */
13003             || kind === 291 /* EnumMember */
13004             || kind === 270 /* ExportSpecifier */
13005             || kind === 251 /* FunctionDeclaration */
13006             || kind === 208 /* FunctionExpression */
13007             || kind === 167 /* GetAccessor */
13008             || kind === 262 /* ImportClause */
13009             || kind === 260 /* ImportEqualsDeclaration */
13010             || kind === 265 /* ImportSpecifier */
13011             || kind === 253 /* InterfaceDeclaration */
13012             || kind === 280 /* JsxAttribute */
13013             || kind === 165 /* MethodDeclaration */
13014             || kind === 164 /* MethodSignature */
13015             || kind === 256 /* ModuleDeclaration */
13016             || kind === 259 /* NamespaceExportDeclaration */
13017             || kind === 263 /* NamespaceImport */
13018             || kind === 269 /* NamespaceExport */
13019             || kind === 160 /* Parameter */
13020             || kind === 288 /* PropertyAssignment */
13021             || kind === 163 /* PropertyDeclaration */
13022             || kind === 162 /* PropertySignature */
13023             || kind === 168 /* SetAccessor */
13024             || kind === 289 /* ShorthandPropertyAssignment */
13025             || kind === 254 /* TypeAliasDeclaration */
13026             || kind === 159 /* TypeParameter */
13027             || kind === 249 /* VariableDeclaration */
13028             || kind === 331 /* JSDocTypedefTag */
13029             || kind === 324 /* JSDocCallbackTag */
13030             || kind === 333 /* JSDocPropertyTag */;
13031     }
13032     function isDeclarationStatementKind(kind) {
13033         return kind === 251 /* FunctionDeclaration */
13034             || kind === 271 /* MissingDeclaration */
13035             || kind === 252 /* ClassDeclaration */
13036             || kind === 253 /* InterfaceDeclaration */
13037             || kind === 254 /* TypeAliasDeclaration */
13038             || kind === 255 /* EnumDeclaration */
13039             || kind === 256 /* ModuleDeclaration */
13040             || kind === 261 /* ImportDeclaration */
13041             || kind === 260 /* ImportEqualsDeclaration */
13042             || kind === 267 /* ExportDeclaration */
13043             || kind === 266 /* ExportAssignment */
13044             || kind === 259 /* NamespaceExportDeclaration */;
13045     }
13046     function isStatementKindButNotDeclarationKind(kind) {
13047         return kind === 241 /* BreakStatement */
13048             || kind === 240 /* ContinueStatement */
13049             || kind === 248 /* DebuggerStatement */
13050             || kind === 235 /* DoStatement */
13051             || kind === 233 /* ExpressionStatement */
13052             || kind === 231 /* EmptyStatement */
13053             || kind === 238 /* ForInStatement */
13054             || kind === 239 /* ForOfStatement */
13055             || kind === 237 /* ForStatement */
13056             || kind === 234 /* IfStatement */
13057             || kind === 245 /* LabeledStatement */
13058             || kind === 242 /* ReturnStatement */
13059             || kind === 244 /* SwitchStatement */
13060             || kind === 246 /* ThrowStatement */
13061             || kind === 247 /* TryStatement */
13062             || kind === 232 /* VariableStatement */
13063             || kind === 236 /* WhileStatement */
13064             || kind === 243 /* WithStatement */
13065             || kind === 335 /* NotEmittedStatement */
13066             || kind === 339 /* EndOfDeclarationMarker */
13067             || kind === 338 /* MergeDeclarationMarker */;
13068     }
13069     /* @internal */
13070     function isDeclaration(node) {
13071         if (node.kind === 159 /* TypeParameter */) {
13072             return (node.parent && node.parent.kind !== 330 /* JSDocTemplateTag */) || ts.isInJSFile(node);
13073         }
13074         return isDeclarationKind(node.kind);
13075     }
13076     ts.isDeclaration = isDeclaration;
13077     /* @internal */
13078     function isDeclarationStatement(node) {
13079         return isDeclarationStatementKind(node.kind);
13080     }
13081     ts.isDeclarationStatement = isDeclarationStatement;
13082     /**
13083      * Determines whether the node is a statement that is not also a declaration
13084      */
13085     /* @internal */
13086     function isStatementButNotDeclaration(node) {
13087         return isStatementKindButNotDeclarationKind(node.kind);
13088     }
13089     ts.isStatementButNotDeclaration = isStatementButNotDeclaration;
13090     /* @internal */
13091     function isStatement(node) {
13092         var kind = node.kind;
13093         return isStatementKindButNotDeclarationKind(kind)
13094             || isDeclarationStatementKind(kind)
13095             || isBlockStatement(node);
13096     }
13097     ts.isStatement = isStatement;
13098     function isBlockStatement(node) {
13099         if (node.kind !== 230 /* Block */)
13100             return false;
13101         if (node.parent !== undefined) {
13102             if (node.parent.kind === 247 /* TryStatement */ || node.parent.kind === 287 /* CatchClause */) {
13103                 return false;
13104             }
13105         }
13106         return !ts.isFunctionBlock(node);
13107     }
13108     /**
13109      * NOTE: This is similar to `isStatement` but does not access parent pointers.
13110      */
13111     /* @internal */
13112     function isStatementOrBlock(node) {
13113         var kind = node.kind;
13114         return isStatementKindButNotDeclarationKind(kind)
13115             || isDeclarationStatementKind(kind)
13116             || kind === 230 /* Block */;
13117     }
13118     ts.isStatementOrBlock = isStatementOrBlock;
13119     // Module references
13120     /* @internal */
13121     function isModuleReference(node) {
13122         var kind = node.kind;
13123         return kind === 272 /* ExternalModuleReference */
13124             || kind === 157 /* QualifiedName */
13125             || kind === 78 /* Identifier */;
13126     }
13127     ts.isModuleReference = isModuleReference;
13128     // JSX
13129     /* @internal */
13130     function isJsxTagNameExpression(node) {
13131         var kind = node.kind;
13132         return kind === 107 /* ThisKeyword */
13133             || kind === 78 /* Identifier */
13134             || kind === 201 /* PropertyAccessExpression */;
13135     }
13136     ts.isJsxTagNameExpression = isJsxTagNameExpression;
13137     /* @internal */
13138     function isJsxChild(node) {
13139         var kind = node.kind;
13140         return kind === 273 /* JsxElement */
13141             || kind === 283 /* JsxExpression */
13142             || kind === 274 /* JsxSelfClosingElement */
13143             || kind === 11 /* JsxText */
13144             || kind === 277 /* JsxFragment */;
13145     }
13146     ts.isJsxChild = isJsxChild;
13147     /* @internal */
13148     function isJsxAttributeLike(node) {
13149         var kind = node.kind;
13150         return kind === 280 /* JsxAttribute */
13151             || kind === 282 /* JsxSpreadAttribute */;
13152     }
13153     ts.isJsxAttributeLike = isJsxAttributeLike;
13154     /* @internal */
13155     function isStringLiteralOrJsxExpression(node) {
13156         var kind = node.kind;
13157         return kind === 10 /* StringLiteral */
13158             || kind === 283 /* JsxExpression */;
13159     }
13160     ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
13161     function isJsxOpeningLikeElement(node) {
13162         var kind = node.kind;
13163         return kind === 275 /* JsxOpeningElement */
13164             || kind === 274 /* JsxSelfClosingElement */;
13165     }
13166     ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
13167     // Clauses
13168     function isCaseOrDefaultClause(node) {
13169         var kind = node.kind;
13170         return kind === 284 /* CaseClause */
13171             || kind === 285 /* DefaultClause */;
13172     }
13173     ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
13174     // JSDoc
13175     /** True if node is of some JSDoc syntax kind. */
13176     /* @internal */
13177     function isJSDocNode(node) {
13178         return node.kind >= 301 /* FirstJSDocNode */ && node.kind <= 333 /* LastJSDocNode */;
13179     }
13180     ts.isJSDocNode = isJSDocNode;
13181     /** True if node is of a kind that may contain comment text. */
13182     function isJSDocCommentContainingNode(node) {
13183         return node.kind === 311 /* JSDocComment */ || node.kind === 310 /* JSDocNamepathType */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
13184     }
13185     ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
13186     // TODO: determine what this does before making it public.
13187     /* @internal */
13188     function isJSDocTag(node) {
13189         return node.kind >= 314 /* FirstJSDocTagNode */ && node.kind <= 333 /* LastJSDocTagNode */;
13190     }
13191     ts.isJSDocTag = isJSDocTag;
13192     function isSetAccessor(node) {
13193         return node.kind === 168 /* SetAccessor */;
13194     }
13195     ts.isSetAccessor = isSetAccessor;
13196     function isGetAccessor(node) {
13197         return node.kind === 167 /* GetAccessor */;
13198     }
13199     ts.isGetAccessor = isGetAccessor;
13200     /** True if has jsdoc nodes attached to it. */
13201     /* @internal */
13202     // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times
13203     function hasJSDocNodes(node) {
13204         var jsDoc = node.jsDoc;
13205         return !!jsDoc && jsDoc.length > 0;
13206     }
13207     ts.hasJSDocNodes = hasJSDocNodes;
13208     /** True if has type node attached to it. */
13209     /* @internal */
13210     function hasType(node) {
13211         return !!node.type;
13212     }
13213     ts.hasType = hasType;
13214     /** True if has initializer node attached to it. */
13215     /* @internal */
13216     function hasInitializer(node) {
13217         return !!node.initializer;
13218     }
13219     ts.hasInitializer = hasInitializer;
13220     /** True if has initializer node attached to it. */
13221     function hasOnlyExpressionInitializer(node) {
13222         switch (node.kind) {
13223             case 249 /* VariableDeclaration */:
13224             case 160 /* Parameter */:
13225             case 198 /* BindingElement */:
13226             case 162 /* PropertySignature */:
13227             case 163 /* PropertyDeclaration */:
13228             case 288 /* PropertyAssignment */:
13229             case 291 /* EnumMember */:
13230                 return true;
13231             default:
13232                 return false;
13233         }
13234     }
13235     ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
13236     function isObjectLiteralElement(node) {
13237         return node.kind === 280 /* JsxAttribute */ || node.kind === 282 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
13238     }
13239     ts.isObjectLiteralElement = isObjectLiteralElement;
13240     /* @internal */
13241     function isTypeReferenceType(node) {
13242         return node.kind === 173 /* TypeReference */ || node.kind === 223 /* ExpressionWithTypeArguments */;
13243     }
13244     ts.isTypeReferenceType = isTypeReferenceType;
13245     var MAX_SMI_X86 = 1073741823;
13246     /* @internal */
13247     function guessIndentation(lines) {
13248         var indentation = MAX_SMI_X86;
13249         for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
13250             var line = lines_1[_i];
13251             if (!line.length) {
13252                 continue;
13253             }
13254             var i = 0;
13255             for (; i < line.length && i < indentation; i++) {
13256                 if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
13257                     break;
13258                 }
13259             }
13260             if (i < indentation) {
13261                 indentation = i;
13262             }
13263             if (indentation === 0) {
13264                 return 0;
13265             }
13266         }
13267         return indentation === MAX_SMI_X86 ? undefined : indentation;
13268     }
13269     ts.guessIndentation = guessIndentation;
13270     function isStringLiteralLike(node) {
13271         return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */;
13272     }
13273     ts.isStringLiteralLike = isStringLiteralLike;
13274     // #endregion
13275 })(ts || (ts = {}));
13276 /* @internal */
13277 var ts;
13278 (function (ts) {
13279     ts.resolvingEmptyArray = [];
13280     ts.externalHelpersModuleNameText = "tslib";
13281     ts.defaultMaximumTruncationLength = 160;
13282     ts.noTruncationMaximumTruncationLength = 1000000;
13283     function getDeclarationOfKind(symbol, kind) {
13284         var declarations = symbol.declarations;
13285         if (declarations) {
13286             for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
13287                 var declaration = declarations_1[_i];
13288                 if (declaration.kind === kind) {
13289                     return declaration;
13290                 }
13291             }
13292         }
13293         return undefined;
13294     }
13295     ts.getDeclarationOfKind = getDeclarationOfKind;
13296     /**
13297      * Create a new escaped identifier map.
13298      * @deprecated Use `new Map<__String, T>()` instead.
13299      */
13300     function createUnderscoreEscapedMap() {
13301         return new ts.Map();
13302     }
13303     ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
13304     /**
13305      * @deprecated Use `!!map?.size` instead
13306      */
13307     function hasEntries(map) {
13308         return !!map && !!map.size;
13309     }
13310     ts.hasEntries = hasEntries;
13311     function createSymbolTable(symbols) {
13312         var result = new ts.Map();
13313         if (symbols) {
13314             for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
13315                 var symbol = symbols_1[_i];
13316                 result.set(symbol.escapedName, symbol);
13317             }
13318         }
13319         return result;
13320     }
13321     ts.createSymbolTable = createSymbolTable;
13322     function isTransientSymbol(symbol) {
13323         return (symbol.flags & 33554432 /* Transient */) !== 0;
13324     }
13325     ts.isTransientSymbol = isTransientSymbol;
13326     var stringWriter = createSingleLineStringWriter();
13327     function createSingleLineStringWriter() {
13328         var str = "";
13329         var writeText = function (text) { return str += text; };
13330         return {
13331             getText: function () { return str; },
13332             write: writeText,
13333             rawWrite: writeText,
13334             writeKeyword: writeText,
13335             writeOperator: writeText,
13336             writePunctuation: writeText,
13337             writeSpace: writeText,
13338             writeStringLiteral: writeText,
13339             writeLiteral: writeText,
13340             writeParameter: writeText,
13341             writeProperty: writeText,
13342             writeSymbol: function (s, _) { return writeText(s); },
13343             writeTrailingSemicolon: writeText,
13344             writeComment: writeText,
13345             getTextPos: function () { return str.length; },
13346             getLine: function () { return 0; },
13347             getColumn: function () { return 0; },
13348             getIndent: function () { return 0; },
13349             isAtStartOfLine: function () { return false; },
13350             hasTrailingComment: function () { return false; },
13351             hasTrailingWhitespace: function () { return !!str.length && ts.isWhiteSpaceLike(str.charCodeAt(str.length - 1)); },
13352             // Completely ignore indentation for string writers.  And map newlines to
13353             // a single space.
13354             writeLine: function () { return str += " "; },
13355             increaseIndent: ts.noop,
13356             decreaseIndent: ts.noop,
13357             clear: function () { return str = ""; },
13358             trackSymbol: ts.noop,
13359             reportInaccessibleThisError: ts.noop,
13360             reportInaccessibleUniqueSymbolError: ts.noop,
13361             reportPrivateInBaseOfClassExpression: ts.noop,
13362         };
13363     }
13364     function changesAffectModuleResolution(oldOptions, newOptions) {
13365         return oldOptions.configFilePath !== newOptions.configFilePath ||
13366             optionsHaveModuleResolutionChanges(oldOptions, newOptions);
13367     }
13368     ts.changesAffectModuleResolution = changesAffectModuleResolution;
13369     function optionsHaveModuleResolutionChanges(oldOptions, newOptions) {
13370         return ts.moduleResolutionOptionDeclarations.some(function (o) {
13371             return !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o));
13372         });
13373     }
13374     ts.optionsHaveModuleResolutionChanges = optionsHaveModuleResolutionChanges;
13375     function forEachAncestor(node, callback) {
13376         while (true) {
13377             var res = callback(node);
13378             if (res === "quit")
13379                 return undefined;
13380             if (res !== undefined)
13381                 return res;
13382             if (ts.isSourceFile(node))
13383                 return undefined;
13384             node = node.parent;
13385         }
13386     }
13387     ts.forEachAncestor = forEachAncestor;
13388     /**
13389      * Calls `callback` for each entry in the map, returning the first truthy result.
13390      * Use `map.forEach` instead for normal iteration.
13391      */
13392     function forEachEntry(map, callback) {
13393         var iterator = map.entries();
13394         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
13395             var _a = iterResult.value, key = _a[0], value = _a[1];
13396             var result = callback(value, key);
13397             if (result) {
13398                 return result;
13399             }
13400         }
13401         return undefined;
13402     }
13403     ts.forEachEntry = forEachEntry;
13404     /** `forEachEntry` for just keys. */
13405     function forEachKey(map, callback) {
13406         var iterator = map.keys();
13407         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
13408             var result = callback(iterResult.value);
13409             if (result) {
13410                 return result;
13411             }
13412         }
13413         return undefined;
13414     }
13415     ts.forEachKey = forEachKey;
13416     /** Copy entries from `source` to `target`. */
13417     function copyEntries(source, target) {
13418         source.forEach(function (value, key) {
13419             target.set(key, value);
13420         });
13421     }
13422     ts.copyEntries = copyEntries;
13423     function usingSingleLineStringWriter(action) {
13424         var oldString = stringWriter.getText();
13425         try {
13426             action(stringWriter);
13427             return stringWriter.getText();
13428         }
13429         finally {
13430             stringWriter.clear();
13431             stringWriter.writeKeyword(oldString);
13432         }
13433     }
13434     ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
13435     function getFullWidth(node) {
13436         return node.end - node.pos;
13437     }
13438     ts.getFullWidth = getFullWidth;
13439     function getResolvedModule(sourceFile, moduleNameText) {
13440         return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText);
13441     }
13442     ts.getResolvedModule = getResolvedModule;
13443     function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
13444         if (!sourceFile.resolvedModules) {
13445             sourceFile.resolvedModules = new ts.Map();
13446         }
13447         sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
13448     }
13449     ts.setResolvedModule = setResolvedModule;
13450     function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
13451         if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
13452             sourceFile.resolvedTypeReferenceDirectiveNames = new ts.Map();
13453         }
13454         sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
13455     }
13456     ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
13457     function projectReferenceIsEqualTo(oldRef, newRef) {
13458         return oldRef.path === newRef.path &&
13459             !oldRef.prepend === !newRef.prepend &&
13460             !oldRef.circular === !newRef.circular;
13461     }
13462     ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
13463     function moduleResolutionIsEqualTo(oldResolution, newResolution) {
13464         return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
13465             oldResolution.extension === newResolution.extension &&
13466             oldResolution.resolvedFileName === newResolution.resolvedFileName &&
13467             oldResolution.originalPath === newResolution.originalPath &&
13468             packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
13469     }
13470     ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
13471     function packageIdIsEqual(a, b) {
13472         return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
13473     }
13474     function packageIdToString(_a) {
13475         var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
13476         var fullName = subModuleName ? name + "/" + subModuleName : name;
13477         return fullName + "@" + version;
13478     }
13479     ts.packageIdToString = packageIdToString;
13480     function typeDirectiveIsEqualTo(oldResolution, newResolution) {
13481         return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
13482     }
13483     ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
13484     function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) {
13485         ts.Debug.assert(names.length === newResolutions.length);
13486         for (var i = 0; i < names.length; i++) {
13487             var newResolution = newResolutions[i];
13488             var oldResolution = oldResolutions && oldResolutions.get(names[i]);
13489             var changed = oldResolution
13490                 ? !newResolution || !comparer(oldResolution, newResolution)
13491                 : newResolution;
13492             if (changed) {
13493                 return true;
13494             }
13495         }
13496         return false;
13497     }
13498     ts.hasChangesInResolutions = hasChangesInResolutions;
13499     // Returns true if this node contains a parse error anywhere underneath it.
13500     function containsParseError(node) {
13501         aggregateChildData(node);
13502         return (node.flags & 262144 /* ThisNodeOrAnySubNodesHasError */) !== 0;
13503     }
13504     ts.containsParseError = containsParseError;
13505     function aggregateChildData(node) {
13506         if (!(node.flags & 524288 /* HasAggregatedChildData */)) {
13507             // A node is considered to contain a parse error if:
13508             //  a) the parser explicitly marked that it had an error
13509             //  b) any of it's children reported that it had an error.
13510             var thisNodeOrAnySubNodesHasError = ((node.flags & 65536 /* ThisNodeHasError */) !== 0) ||
13511                 ts.forEachChild(node, containsParseError);
13512             // If so, mark ourselves accordingly.
13513             if (thisNodeOrAnySubNodesHasError) {
13514                 node.flags |= 262144 /* ThisNodeOrAnySubNodesHasError */;
13515             }
13516             // Also mark that we've propagated the child information to this node.  This way we can
13517             // always consult the bit directly on this node without needing to check its children
13518             // again.
13519             node.flags |= 524288 /* HasAggregatedChildData */;
13520         }
13521     }
13522     function getSourceFileOfNode(node) {
13523         while (node && node.kind !== 297 /* SourceFile */) {
13524             node = node.parent;
13525         }
13526         return node;
13527     }
13528     ts.getSourceFileOfNode = getSourceFileOfNode;
13529     function isStatementWithLocals(node) {
13530         switch (node.kind) {
13531             case 230 /* Block */:
13532             case 258 /* CaseBlock */:
13533             case 237 /* ForStatement */:
13534             case 238 /* ForInStatement */:
13535             case 239 /* ForOfStatement */:
13536                 return true;
13537         }
13538         return false;
13539     }
13540     ts.isStatementWithLocals = isStatementWithLocals;
13541     function getStartPositionOfLine(line, sourceFile) {
13542         ts.Debug.assert(line >= 0);
13543         return ts.getLineStarts(sourceFile)[line];
13544     }
13545     ts.getStartPositionOfLine = getStartPositionOfLine;
13546     // This is a useful function for debugging purposes.
13547     function nodePosToString(node) {
13548         var file = getSourceFileOfNode(node);
13549         var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
13550         return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
13551     }
13552     ts.nodePosToString = nodePosToString;
13553     function getEndLinePosition(line, sourceFile) {
13554         ts.Debug.assert(line >= 0);
13555         var lineStarts = ts.getLineStarts(sourceFile);
13556         var lineIndex = line;
13557         var sourceText = sourceFile.text;
13558         if (lineIndex + 1 === lineStarts.length) {
13559             // last line - return EOF
13560             return sourceText.length - 1;
13561         }
13562         else {
13563             // current line start
13564             var start = lineStarts[lineIndex];
13565             // take the start position of the next line - 1 = it should be some line break
13566             var pos = lineStarts[lineIndex + 1] - 1;
13567             ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
13568             // walk backwards skipping line breaks, stop the the beginning of current line.
13569             // i.e:
13570             // <some text>
13571             // $ <- end of line for this position should match the start position
13572             while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
13573                 pos--;
13574             }
13575             return pos;
13576         }
13577     }
13578     ts.getEndLinePosition = getEndLinePosition;
13579     /**
13580      * Returns a value indicating whether a name is unique globally or within the current file.
13581      * 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`.
13582      */
13583     function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
13584         return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
13585     }
13586     ts.isFileLevelUniqueName = isFileLevelUniqueName;
13587     // Returns true if this node is missing from the actual source code. A 'missing' node is different
13588     // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
13589     // in the tree), it is definitely missing. However, a node may be defined, but still be
13590     // missing.  This happens whenever the parser knows it needs to parse something, but can't
13591     // get anything in the source code that it expects at that location. For example:
13592     //
13593     //          let a: ;
13594     //
13595     // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
13596     // code). So the parser will attempt to parse out a type, and will create an actual node.
13597     // However, this node will be 'missing' in the sense that no actual source-code/tokens are
13598     // contained within it.
13599     function nodeIsMissing(node) {
13600         if (node === undefined) {
13601             return true;
13602         }
13603         return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
13604     }
13605     ts.nodeIsMissing = nodeIsMissing;
13606     function nodeIsPresent(node) {
13607         return !nodeIsMissing(node);
13608     }
13609     ts.nodeIsPresent = nodeIsPresent;
13610     function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
13611         if (from === undefined || from.length === 0)
13612             return to;
13613         var statementIndex = 0;
13614         // skip all prologue directives to insert at the correct position
13615         for (; statementIndex < to.length; ++statementIndex) {
13616             if (!isPrologueDirective(to[statementIndex])) {
13617                 break;
13618             }
13619         }
13620         to.splice.apply(to, __spreadArray([statementIndex, 0], from));
13621         return to;
13622     }
13623     function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
13624         if (statement === undefined)
13625             return to;
13626         var statementIndex = 0;
13627         // skip all prologue directives to insert at the correct position
13628         for (; statementIndex < to.length; ++statementIndex) {
13629             if (!isPrologueDirective(to[statementIndex])) {
13630                 break;
13631             }
13632         }
13633         to.splice(statementIndex, 0, statement);
13634         return to;
13635     }
13636     function isAnyPrologueDirective(node) {
13637         return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13638     }
13639     /**
13640      * Prepends statements to an array while taking care of prologue directives.
13641      */
13642     function insertStatementsAfterStandardPrologue(to, from) {
13643         return insertStatementsAfterPrologue(to, from, isPrologueDirective);
13644     }
13645     ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
13646     function insertStatementsAfterCustomPrologue(to, from) {
13647         return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
13648     }
13649     ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
13650     /**
13651      * Prepends statements to an array while taking care of prologue directives.
13652      */
13653     function insertStatementAfterStandardPrologue(to, statement) {
13654         return insertStatementAfterPrologue(to, statement, isPrologueDirective);
13655     }
13656     ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
13657     function insertStatementAfterCustomPrologue(to, statement) {
13658         return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
13659     }
13660     ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
13661     /**
13662      * Determine if the given comment is a triple-slash
13663      *
13664      * @return true if the comment is a triple-slash comment else false
13665      */
13666     function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
13667         // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
13668         // so that we don't end up computing comment string and doing match for all // comments
13669         if (text.charCodeAt(commentPos + 1) === 47 /* slash */ &&
13670             commentPos + 2 < commentEnd &&
13671             text.charCodeAt(commentPos + 2) === 47 /* slash */) {
13672             var textSubStr = text.substring(commentPos, commentEnd);
13673             return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
13674                 textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ||
13675                 textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) ||
13676                 textSubStr.match(defaultLibReferenceRegEx) ?
13677                 true : false;
13678         }
13679         return false;
13680     }
13681     ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
13682     function isPinnedComment(text, start) {
13683         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
13684             text.charCodeAt(start + 2) === 33 /* exclamation */;
13685     }
13686     ts.isPinnedComment = isPinnedComment;
13687     function createCommentDirectivesMap(sourceFile, commentDirectives) {
13688         var directivesByLine = new ts.Map(commentDirectives.map(function (commentDirective) { return ([
13689             "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line,
13690             commentDirective,
13691         ]); }));
13692         var usedLines = new ts.Map();
13693         return { getUnusedExpectations: getUnusedExpectations, markUsed: markUsed };
13694         function getUnusedExpectations() {
13695             return ts.arrayFrom(directivesByLine.entries())
13696                 .filter(function (_a) {
13697                 var line = _a[0], directive = _a[1];
13698                 return directive.type === 0 /* ExpectError */ && !usedLines.get(line);
13699             })
13700                 .map(function (_a) {
13701                 var _ = _a[0], directive = _a[1];
13702                 return directive;
13703             });
13704         }
13705         function markUsed(line) {
13706             if (!directivesByLine.has("" + line)) {
13707                 return false;
13708             }
13709             usedLines.set("" + line, true);
13710             return true;
13711         }
13712     }
13713     ts.createCommentDirectivesMap = createCommentDirectivesMap;
13714     function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
13715         // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
13716         // want to skip trivia because this will launch us forward to the next token.
13717         if (nodeIsMissing(node)) {
13718             return node.pos;
13719         }
13720         if (ts.isJSDocNode(node) || node.kind === 11 /* JsxText */) {
13721             // JsxText cannot actually contain comments, even though the scanner will think it sees comments
13722             return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
13723         }
13724         if (includeJsDoc && ts.hasJSDocNodes(node)) {
13725             return getTokenPosOfNode(node.jsDoc[0], sourceFile);
13726         }
13727         // For a syntax list, it is possible that one of its children has JSDocComment nodes, while
13728         // the syntax list itself considers them as normal trivia. Therefore if we simply skip
13729         // trivia for the list, we may have skipped the JSDocComment as well. So we should process its
13730         // first child to determine the actual position of its first token.
13731         if (node.kind === 334 /* SyntaxList */ && node._children.length > 0) {
13732             return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
13733         }
13734         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
13735     }
13736     ts.getTokenPosOfNode = getTokenPosOfNode;
13737     function getNonDecoratorTokenPosOfNode(node, sourceFile) {
13738         if (nodeIsMissing(node) || !node.decorators) {
13739             return getTokenPosOfNode(node, sourceFile);
13740         }
13741         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
13742     }
13743     ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
13744     function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
13745         if (includeTrivia === void 0) { includeTrivia = false; }
13746         return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
13747     }
13748     ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
13749     function isJSDocTypeExpressionOrChild(node) {
13750         return !!ts.findAncestor(node, ts.isJSDocTypeExpression);
13751     }
13752     function isExportNamespaceAsDefaultDeclaration(node) {
13753         return !!(ts.isExportDeclaration(node) && node.exportClause && ts.isNamespaceExport(node.exportClause) && node.exportClause.name.escapedText === "default");
13754     }
13755     ts.isExportNamespaceAsDefaultDeclaration = isExportNamespaceAsDefaultDeclaration;
13756     function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
13757         if (includeTrivia === void 0) { includeTrivia = false; }
13758         if (nodeIsMissing(node)) {
13759             return "";
13760         }
13761         var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
13762         if (isJSDocTypeExpressionOrChild(node)) {
13763             // strip space + asterisk at line start
13764             text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1");
13765         }
13766         return text;
13767     }
13768     ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
13769     function getTextOfNode(node, includeTrivia) {
13770         if (includeTrivia === void 0) { includeTrivia = false; }
13771         return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
13772     }
13773     ts.getTextOfNode = getTextOfNode;
13774     function getPos(range) {
13775         return range.pos;
13776     }
13777     /**
13778      * Note: it is expected that the `nodeArray` and the `node` are within the same file.
13779      * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work.
13780      */
13781     function indexOfNode(nodeArray, node) {
13782         return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
13783     }
13784     ts.indexOfNode = indexOfNode;
13785     /**
13786      * Gets flags that control emit behavior of a node.
13787      */
13788     function getEmitFlags(node) {
13789         var emitNode = node.emitNode;
13790         return emitNode && emitNode.flags || 0;
13791     }
13792     ts.getEmitFlags = getEmitFlags;
13793     ;
13794     function getScriptTargetFeatures() {
13795         return {
13796             es2015: {
13797                 Array: ["find", "findIndex", "fill", "copyWithin", "entries", "keys", "values"],
13798                 RegExp: ["flags", "sticky", "unicode"],
13799                 Reflect: ["apply", "construct", "defineProperty", "deleteProperty", "get", " getOwnPropertyDescriptor", "getPrototypeOf", "has", "isExtensible", "ownKeys", "preventExtensions", "set", "setPrototypeOf"],
13800                 ArrayConstructor: ["from", "of"],
13801                 ObjectConstructor: ["assign", "getOwnPropertySymbols", "keys", "is", "setPrototypeOf"],
13802                 NumberConstructor: ["isFinite", "isInteger", "isNaN", "isSafeInteger", "parseFloat", "parseInt"],
13803                 Math: ["clz32", "imul", "sign", "log10", "log2", "log1p", "expm1", "cosh", "sinh", "tanh", "acosh", "asinh", "atanh", "hypot", "trunc", "fround", "cbrt"],
13804                 Map: ["entries", "keys", "values"],
13805                 Set: ["entries", "keys", "values"],
13806                 Promise: ts.emptyArray,
13807                 PromiseConstructor: ["all", "race", "reject", "resolve"],
13808                 Symbol: ["for", "keyFor"],
13809                 WeakMap: ["entries", "keys", "values"],
13810                 WeakSet: ["entries", "keys", "values"],
13811                 Iterator: ts.emptyArray,
13812                 AsyncIterator: ts.emptyArray,
13813                 String: ["codePointAt", "includes", "endsWith", "normalize", "repeat", "startsWith", "anchor", "big", "blink", "bold", "fixed", "fontcolor", "fontsize", "italics", "link", "small", "strike", "sub", "sup"],
13814                 StringConstructor: ["fromCodePoint", "raw"]
13815             },
13816             es2016: {
13817                 Array: ["includes"]
13818             },
13819             es2017: {
13820                 Atomics: ts.emptyArray,
13821                 SharedArrayBuffer: ts.emptyArray,
13822                 String: ["padStart", "padEnd"],
13823                 ObjectConstructor: ["values", "entries", "getOwnPropertyDescriptors"],
13824                 DateTimeFormat: ["formatToParts"]
13825             },
13826             es2018: {
13827                 Promise: ["finally"],
13828                 RegExpMatchArray: ["groups"],
13829                 RegExpExecArray: ["groups"],
13830                 RegExp: ["dotAll"],
13831                 Intl: ["PluralRules"],
13832                 AsyncIterable: ts.emptyArray,
13833                 AsyncIterableIterator: ts.emptyArray,
13834                 AsyncGenerator: ts.emptyArray,
13835                 AsyncGeneratorFunction: ts.emptyArray,
13836             },
13837             es2019: {
13838                 Array: ["flat", "flatMap"],
13839                 ObjectConstructor: ["fromEntries"],
13840                 String: ["trimStart", "trimEnd", "trimLeft", "trimRight"],
13841                 Symbol: ["description"]
13842             },
13843             es2020: {
13844                 BigInt: ts.emptyArray,
13845                 BigInt64Array: ts.emptyArray,
13846                 BigUint64Array: ts.emptyArray,
13847                 PromiseConstructor: ["allSettled"],
13848                 SymbolConstructor: ["matchAll"],
13849                 String: ["matchAll"],
13850                 DataView: ["setBigInt64", "setBigUint64", "getBigInt64", "getBigUint64"],
13851                 RelativeTimeFormat: ["format", "formatToParts", "resolvedOptions"]
13852             },
13853             esnext: {
13854                 PromiseConstructor: ["any"],
13855                 String: ["replaceAll"],
13856                 NumberFormat: ["formatToParts"]
13857             }
13858         };
13859     }
13860     ts.getScriptTargetFeatures = getScriptTargetFeatures;
13861     var GetLiteralTextFlags;
13862     (function (GetLiteralTextFlags) {
13863         GetLiteralTextFlags[GetLiteralTextFlags["None"] = 0] = "None";
13864         GetLiteralTextFlags[GetLiteralTextFlags["NeverAsciiEscape"] = 1] = "NeverAsciiEscape";
13865         GetLiteralTextFlags[GetLiteralTextFlags["JsxAttributeEscape"] = 2] = "JsxAttributeEscape";
13866         GetLiteralTextFlags[GetLiteralTextFlags["TerminateUnterminatedLiterals"] = 4] = "TerminateUnterminatedLiterals";
13867         GetLiteralTextFlags[GetLiteralTextFlags["AllowNumericSeparator"] = 8] = "AllowNumericSeparator";
13868     })(GetLiteralTextFlags = ts.GetLiteralTextFlags || (ts.GetLiteralTextFlags = {}));
13869     function getLiteralText(node, sourceFile, flags) {
13870         // If we don't need to downlevel and we can reach the original source text using
13871         // the node's parent reference, then simply get the text as it was originally written.
13872         if (canUseOriginalText(node, flags)) {
13873             return getSourceTextOfNodeFromSourceFile(sourceFile, node);
13874         }
13875         // If we can't reach the original source text, use the canonical form if it's a number,
13876         // or a (possibly escaped) quoted form of the original text if it's string-like.
13877         switch (node.kind) {
13878             case 10 /* StringLiteral */: {
13879                 var escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString :
13880                     flags & 1 /* NeverAsciiEscape */ || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13881                         escapeNonAsciiString;
13882                 if (node.singleQuote) {
13883                     return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
13884                 }
13885                 else {
13886                     return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
13887                 }
13888             }
13889             case 14 /* NoSubstitutionTemplateLiteral */:
13890             case 15 /* TemplateHead */:
13891             case 16 /* TemplateMiddle */:
13892             case 17 /* TemplateTail */: {
13893                 // If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
13894                 // had to include a backslash: `not \${a} substitution`.
13895                 var escapeText = flags & 1 /* NeverAsciiEscape */ || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13896                     escapeNonAsciiString;
13897                 var rawText = node.rawText || escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */));
13898                 switch (node.kind) {
13899                     case 14 /* NoSubstitutionTemplateLiteral */:
13900                         return "`" + rawText + "`";
13901                     case 15 /* TemplateHead */:
13902                         return "`" + rawText + "${";
13903                     case 16 /* TemplateMiddle */:
13904                         return "}" + rawText + "${";
13905                     case 17 /* TemplateTail */:
13906                         return "}" + rawText + "`";
13907                 }
13908                 break;
13909             }
13910             case 8 /* NumericLiteral */:
13911             case 9 /* BigIntLiteral */:
13912                 return node.text;
13913             case 13 /* RegularExpressionLiteral */:
13914                 if (flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated) {
13915                     return node.text + (node.text.charCodeAt(node.text.length - 1) === 92 /* backslash */ ? " /" : "/");
13916                 }
13917                 return node.text;
13918         }
13919         return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
13920     }
13921     ts.getLiteralText = getLiteralText;
13922     function canUseOriginalText(node, flags) {
13923         if (nodeIsSynthesized(node) || !node.parent || (flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated)) {
13924             return false;
13925         }
13926         if (ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) {
13927             return !!(flags & 8 /* AllowNumericSeparator */);
13928         }
13929         return !ts.isBigIntLiteral(node);
13930     }
13931     function getTextOfConstantValue(value) {
13932         return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
13933     }
13934     ts.getTextOfConstantValue = getTextOfConstantValue;
13935     // Make an identifier from an external module name by extracting the string after the last "/" and replacing
13936     // all non-alphanumeric characters with underscores
13937     function makeIdentifierFromModuleName(moduleName) {
13938         return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
13939     }
13940     ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName;
13941     function isBlockOrCatchScoped(declaration) {
13942         return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
13943             isCatchClauseVariableDeclarationOrBindingElement(declaration);
13944     }
13945     ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
13946     function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
13947         var node = getRootDeclaration(declaration);
13948         return node.kind === 249 /* VariableDeclaration */ && node.parent.kind === 287 /* CatchClause */;
13949     }
13950     ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
13951     function isAmbientModule(node) {
13952         return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node));
13953     }
13954     ts.isAmbientModule = isAmbientModule;
13955     function isModuleWithStringLiteralName(node) {
13956         return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */;
13957     }
13958     ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName;
13959     function isNonGlobalAmbientModule(node) {
13960         return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
13961     }
13962     ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule;
13963     /**
13964      * An effective module (namespace) declaration is either
13965      * 1. An actual declaration: namespace X { ... }
13966      * 2. A Javascript declaration, which is:
13967      *    An identifier in a nested property access expression: Y in `X.Y.Z = { ... }`
13968      */
13969     function isEffectiveModuleDeclaration(node) {
13970         return ts.isModuleDeclaration(node) || ts.isIdentifier(node);
13971     }
13972     ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration;
13973     /** Given a symbol for a module, checks that it is a shorthand ambient module. */
13974     function isShorthandAmbientModuleSymbol(moduleSymbol) {
13975         return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
13976     }
13977     ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
13978     function isShorthandAmbientModule(node) {
13979         // The only kind of module that can be missing a body is a shorthand ambient module.
13980         return node && node.kind === 256 /* ModuleDeclaration */ && (!node.body);
13981     }
13982     function isBlockScopedContainerTopLevel(node) {
13983         return node.kind === 297 /* SourceFile */ ||
13984             node.kind === 256 /* ModuleDeclaration */ ||
13985             ts.isFunctionLike(node);
13986     }
13987     ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
13988     function isGlobalScopeAugmentation(module) {
13989         return !!(module.flags & 1024 /* GlobalAugmentation */);
13990     }
13991     ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
13992     function isExternalModuleAugmentation(node) {
13993         return isAmbientModule(node) && isModuleAugmentationExternal(node);
13994     }
13995     ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
13996     function isModuleAugmentationExternal(node) {
13997         // external module augmentation is a ambient module declaration that is either:
13998         // - defined in the top level scope and source file is an external module
13999         // - defined inside ambient module declaration located in the top level scope and source file not an external module
14000         switch (node.parent.kind) {
14001             case 297 /* SourceFile */:
14002                 return ts.isExternalModule(node.parent);
14003             case 257 /* ModuleBlock */:
14004                 return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
14005         }
14006         return false;
14007     }
14008     ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
14009     function getNonAugmentationDeclaration(symbol) {
14010         return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
14011     }
14012     ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
14013     function isEffectiveExternalModule(node, compilerOptions) {
14014         return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
14015     }
14016     ts.isEffectiveExternalModule = isEffectiveExternalModule;
14017     /**
14018      * Returns whether the source file will be treated as if it were in strict mode at runtime.
14019      */
14020     function isEffectiveStrictModeSourceFile(node, compilerOptions) {
14021         // We can only verify strict mode for JS/TS files
14022         switch (node.scriptKind) {
14023             case 1 /* JS */:
14024             case 3 /* TS */:
14025             case 2 /* JSX */:
14026             case 4 /* TSX */:
14027                 break;
14028             default:
14029                 return false;
14030         }
14031         // Strict mode does not matter for declaration files.
14032         if (node.isDeclarationFile) {
14033             return false;
14034         }
14035         // If `alwaysStrict` is set, then treat the file as strict.
14036         if (getStrictOptionValue(compilerOptions, "alwaysStrict")) {
14037             return true;
14038         }
14039         // Starting with a "use strict" directive indicates the file is strict.
14040         if (ts.startsWithUseStrict(node.statements)) {
14041             return true;
14042         }
14043         if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
14044             // ECMAScript Modules are always strict.
14045             if (getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
14046                 return true;
14047             }
14048             // Other modules are strict unless otherwise specified.
14049             return !compilerOptions.noImplicitUseStrict;
14050         }
14051         return false;
14052     }
14053     ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile;
14054     function isBlockScope(node, parentNode) {
14055         switch (node.kind) {
14056             case 297 /* SourceFile */:
14057             case 258 /* CaseBlock */:
14058             case 287 /* CatchClause */:
14059             case 256 /* ModuleDeclaration */:
14060             case 237 /* ForStatement */:
14061             case 238 /* ForInStatement */:
14062             case 239 /* ForOfStatement */:
14063             case 166 /* Constructor */:
14064             case 165 /* MethodDeclaration */:
14065             case 167 /* GetAccessor */:
14066             case 168 /* SetAccessor */:
14067             case 251 /* FunctionDeclaration */:
14068             case 208 /* FunctionExpression */:
14069             case 209 /* ArrowFunction */:
14070                 return true;
14071             case 230 /* Block */:
14072                 // function block is not considered block-scope container
14073                 // see comment in binder.ts: bind(...), case for SyntaxKind.Block
14074                 return !ts.isFunctionLike(parentNode);
14075         }
14076         return false;
14077     }
14078     ts.isBlockScope = isBlockScope;
14079     function isDeclarationWithTypeParameters(node) {
14080         switch (node.kind) {
14081             case 324 /* JSDocCallbackTag */:
14082             case 331 /* JSDocTypedefTag */:
14083             case 313 /* JSDocSignature */:
14084                 return true;
14085             default:
14086                 ts.assertType(node);
14087                 return isDeclarationWithTypeParameterChildren(node);
14088         }
14089     }
14090     ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
14091     function isDeclarationWithTypeParameterChildren(node) {
14092         switch (node.kind) {
14093             case 169 /* CallSignature */:
14094             case 170 /* ConstructSignature */:
14095             case 164 /* MethodSignature */:
14096             case 171 /* IndexSignature */:
14097             case 174 /* FunctionType */:
14098             case 175 /* ConstructorType */:
14099             case 308 /* JSDocFunctionType */:
14100             case 252 /* ClassDeclaration */:
14101             case 221 /* ClassExpression */:
14102             case 253 /* InterfaceDeclaration */:
14103             case 254 /* TypeAliasDeclaration */:
14104             case 330 /* JSDocTemplateTag */:
14105             case 251 /* FunctionDeclaration */:
14106             case 165 /* MethodDeclaration */:
14107             case 166 /* Constructor */:
14108             case 167 /* GetAccessor */:
14109             case 168 /* SetAccessor */:
14110             case 208 /* FunctionExpression */:
14111             case 209 /* ArrowFunction */:
14112                 return true;
14113             default:
14114                 ts.assertType(node);
14115                 return false;
14116         }
14117     }
14118     ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
14119     function isAnyImportSyntax(node) {
14120         switch (node.kind) {
14121             case 261 /* ImportDeclaration */:
14122             case 260 /* ImportEqualsDeclaration */:
14123                 return true;
14124             default:
14125                 return false;
14126         }
14127     }
14128     ts.isAnyImportSyntax = isAnyImportSyntax;
14129     function isLateVisibilityPaintedStatement(node) {
14130         switch (node.kind) {
14131             case 261 /* ImportDeclaration */:
14132             case 260 /* ImportEqualsDeclaration */:
14133             case 232 /* VariableStatement */:
14134             case 252 /* ClassDeclaration */:
14135             case 251 /* FunctionDeclaration */:
14136             case 256 /* ModuleDeclaration */:
14137             case 254 /* TypeAliasDeclaration */:
14138             case 253 /* InterfaceDeclaration */:
14139             case 255 /* EnumDeclaration */:
14140                 return true;
14141             default:
14142                 return false;
14143         }
14144     }
14145     ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
14146     function hasPossibleExternalModuleReference(node) {
14147         return isAnyImportOrReExport(node) || ts.isModuleDeclaration(node) || ts.isImportTypeNode(node) || isImportCall(node);
14148     }
14149     ts.hasPossibleExternalModuleReference = hasPossibleExternalModuleReference;
14150     function isAnyImportOrReExport(node) {
14151         return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
14152     }
14153     ts.isAnyImportOrReExport = isAnyImportOrReExport;
14154     // Gets the nearest enclosing block scope container that has the provided node
14155     // as a descendant, that is not the provided node.
14156     function getEnclosingBlockScopeContainer(node) {
14157         return ts.findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
14158     }
14159     ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
14160     // Return display name of an identifier
14161     // Computed property names will just be emitted as "[<expr>]", where <expr> is the source
14162     // text of the expression in the computed property.
14163     function declarationNameToString(name) {
14164         return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
14165     }
14166     ts.declarationNameToString = declarationNameToString;
14167     function getNameFromIndexInfo(info) {
14168         return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
14169     }
14170     ts.getNameFromIndexInfo = getNameFromIndexInfo;
14171     function isComputedNonLiteralName(name) {
14172         return name.kind === 158 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression);
14173     }
14174     ts.isComputedNonLiteralName = isComputedNonLiteralName;
14175     function getTextOfPropertyName(name) {
14176         switch (name.kind) {
14177             case 78 /* Identifier */:
14178             case 79 /* PrivateIdentifier */:
14179                 return name.escapedText;
14180             case 10 /* StringLiteral */:
14181             case 8 /* NumericLiteral */:
14182             case 14 /* NoSubstitutionTemplateLiteral */:
14183                 return ts.escapeLeadingUnderscores(name.text);
14184             case 158 /* ComputedPropertyName */:
14185                 if (isStringOrNumericLiteralLike(name.expression))
14186                     return ts.escapeLeadingUnderscores(name.expression.text);
14187                 return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
14188             default:
14189                 return ts.Debug.assertNever(name);
14190         }
14191     }
14192     ts.getTextOfPropertyName = getTextOfPropertyName;
14193     function entityNameToString(name) {
14194         switch (name.kind) {
14195             case 107 /* ThisKeyword */:
14196                 return "this";
14197             case 79 /* PrivateIdentifier */:
14198             case 78 /* Identifier */:
14199                 return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
14200             case 157 /* QualifiedName */:
14201                 return entityNameToString(name.left) + "." + entityNameToString(name.right);
14202             case 201 /* PropertyAccessExpression */:
14203                 if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) {
14204                     return entityNameToString(name.expression) + "." + entityNameToString(name.name);
14205                 }
14206                 else {
14207                     return ts.Debug.assertNever(name.name);
14208                 }
14209             default:
14210                 return ts.Debug.assertNever(name);
14211         }
14212     }
14213     ts.entityNameToString = entityNameToString;
14214     function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
14215         var sourceFile = getSourceFileOfNode(node);
14216         return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
14217     }
14218     ts.createDiagnosticForNode = createDiagnosticForNode;
14219     function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
14220         var start = ts.skipTrivia(sourceFile.text, nodes.pos);
14221         return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
14222     }
14223     ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
14224     function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
14225         var span = getErrorSpanForNode(sourceFile, node);
14226         return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
14227     }
14228     ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
14229     function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
14230         var sourceFile = getSourceFileOfNode(node);
14231         var span = getErrorSpanForNode(sourceFile, node);
14232         return createFileDiagnosticFromMessageChain(sourceFile, span.start, span.length, messageChain, relatedInformation);
14233     }
14234     ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
14235     function assertDiagnosticLocation(file, start, length) {
14236         ts.Debug.assertGreaterThanOrEqual(start, 0);
14237         ts.Debug.assertGreaterThanOrEqual(length, 0);
14238         if (file) {
14239             ts.Debug.assertLessThanOrEqual(start, file.text.length);
14240             ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
14241         }
14242     }
14243     function createFileDiagnosticFromMessageChain(file, start, length, messageChain, relatedInformation) {
14244         assertDiagnosticLocation(file, start, length);
14245         return {
14246             file: file,
14247             start: start,
14248             length: length,
14249             code: messageChain.code,
14250             category: messageChain.category,
14251             messageText: messageChain.next ? messageChain : messageChain.messageText,
14252             relatedInformation: relatedInformation
14253         };
14254     }
14255     ts.createFileDiagnosticFromMessageChain = createFileDiagnosticFromMessageChain;
14256     function createDiagnosticForFileFromMessageChain(sourceFile, messageChain, relatedInformation) {
14257         return {
14258             file: sourceFile,
14259             start: 0,
14260             length: 0,
14261             code: messageChain.code,
14262             category: messageChain.category,
14263             messageText: messageChain.next ? messageChain : messageChain.messageText,
14264             relatedInformation: relatedInformation
14265         };
14266     }
14267     ts.createDiagnosticForFileFromMessageChain = createDiagnosticForFileFromMessageChain;
14268     function createDiagnosticForRange(sourceFile, range, message) {
14269         return {
14270             file: sourceFile,
14271             start: range.pos,
14272             length: range.end - range.pos,
14273             code: message.code,
14274             category: message.category,
14275             messageText: message.message,
14276         };
14277     }
14278     ts.createDiagnosticForRange = createDiagnosticForRange;
14279     function getSpanOfTokenAtPosition(sourceFile, pos) {
14280         var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
14281         scanner.scan();
14282         var start = scanner.getTokenPos();
14283         return ts.createTextSpanFromBounds(start, scanner.getTextPos());
14284     }
14285     ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
14286     function getErrorSpanForArrowFunction(sourceFile, node) {
14287         var pos = ts.skipTrivia(sourceFile.text, node.pos);
14288         if (node.body && node.body.kind === 230 /* Block */) {
14289             var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
14290             var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
14291             if (startLine < endLine) {
14292                 // The arrow function spans multiple lines,
14293                 // make the error span be the first line, inclusive.
14294                 return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
14295             }
14296         }
14297         return ts.createTextSpanFromBounds(pos, node.end);
14298     }
14299     function getErrorSpanForNode(sourceFile, node) {
14300         var errorNode = node;
14301         switch (node.kind) {
14302             case 297 /* SourceFile */:
14303                 var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
14304                 if (pos_1 === sourceFile.text.length) {
14305                     // file is empty - return span for the beginning of the file
14306                     return ts.createTextSpan(0, 0);
14307                 }
14308                 return getSpanOfTokenAtPosition(sourceFile, pos_1);
14309             // This list is a work in progress. Add missing node kinds to improve their error
14310             // spans.
14311             case 249 /* VariableDeclaration */:
14312             case 198 /* BindingElement */:
14313             case 252 /* ClassDeclaration */:
14314             case 221 /* ClassExpression */:
14315             case 253 /* InterfaceDeclaration */:
14316             case 256 /* ModuleDeclaration */:
14317             case 255 /* EnumDeclaration */:
14318             case 291 /* EnumMember */:
14319             case 251 /* FunctionDeclaration */:
14320             case 208 /* FunctionExpression */:
14321             case 165 /* MethodDeclaration */:
14322             case 167 /* GetAccessor */:
14323             case 168 /* SetAccessor */:
14324             case 254 /* TypeAliasDeclaration */:
14325             case 163 /* PropertyDeclaration */:
14326             case 162 /* PropertySignature */:
14327                 errorNode = node.name;
14328                 break;
14329             case 209 /* ArrowFunction */:
14330                 return getErrorSpanForArrowFunction(sourceFile, node);
14331             case 284 /* CaseClause */:
14332             case 285 /* DefaultClause */:
14333                 var start = ts.skipTrivia(sourceFile.text, node.pos);
14334                 var end = node.statements.length > 0 ? node.statements[0].pos : node.end;
14335                 return ts.createTextSpanFromBounds(start, end);
14336         }
14337         if (errorNode === undefined) {
14338             // If we don't have a better node, then just set the error on the first token of
14339             // construct.
14340             return getSpanOfTokenAtPosition(sourceFile, node.pos);
14341         }
14342         ts.Debug.assert(!ts.isJSDoc(errorNode));
14343         var isMissing = nodeIsMissing(errorNode);
14344         var pos = isMissing || ts.isJsxText(node)
14345             ? errorNode.pos
14346             : ts.skipTrivia(sourceFile.text, errorNode.pos);
14347         // These asserts should all be satisfied for a properly constructed `errorNode`.
14348         if (isMissing) {
14349             ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14350             ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14351         }
14352         else {
14353             ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14354             ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14355         }
14356         return ts.createTextSpanFromBounds(pos, errorNode.end);
14357     }
14358     ts.getErrorSpanForNode = getErrorSpanForNode;
14359     function isExternalOrCommonJsModule(file) {
14360         return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
14361     }
14362     ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
14363     function isJsonSourceFile(file) {
14364         return file.scriptKind === 6 /* JSON */;
14365     }
14366     ts.isJsonSourceFile = isJsonSourceFile;
14367     function isEnumConst(node) {
14368         return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
14369     }
14370     ts.isEnumConst = isEnumConst;
14371     function isDeclarationReadonly(declaration) {
14372         return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration, declaration.parent));
14373     }
14374     ts.isDeclarationReadonly = isDeclarationReadonly;
14375     function isVarConst(node) {
14376         return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
14377     }
14378     ts.isVarConst = isVarConst;
14379     function isLet(node) {
14380         return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
14381     }
14382     ts.isLet = isLet;
14383     function isSuperCall(n) {
14384         return n.kind === 203 /* CallExpression */ && n.expression.kind === 105 /* SuperKeyword */;
14385     }
14386     ts.isSuperCall = isSuperCall;
14387     function isImportCall(n) {
14388         return n.kind === 203 /* CallExpression */ && n.expression.kind === 99 /* ImportKeyword */;
14389     }
14390     ts.isImportCall = isImportCall;
14391     function isImportMeta(n) {
14392         return ts.isMetaProperty(n)
14393             && n.keywordToken === 99 /* ImportKeyword */
14394             && n.name.escapedText === "meta";
14395     }
14396     ts.isImportMeta = isImportMeta;
14397     function isLiteralImportTypeNode(n) {
14398         return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
14399     }
14400     ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
14401     function isPrologueDirective(node) {
14402         return node.kind === 233 /* ExpressionStatement */
14403             && node.expression.kind === 10 /* StringLiteral */;
14404     }
14405     ts.isPrologueDirective = isPrologueDirective;
14406     function isCustomPrologue(node) {
14407         return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
14408     }
14409     ts.isCustomPrologue = isCustomPrologue;
14410     function isHoistedFunction(node) {
14411         return isCustomPrologue(node)
14412             && ts.isFunctionDeclaration(node);
14413     }
14414     ts.isHoistedFunction = isHoistedFunction;
14415     function isHoistedVariable(node) {
14416         return ts.isIdentifier(node.name)
14417             && !node.initializer;
14418     }
14419     function isHoistedVariableStatement(node) {
14420         return isCustomPrologue(node)
14421             && ts.isVariableStatement(node)
14422             && ts.every(node.declarationList.declarations, isHoistedVariable);
14423     }
14424     ts.isHoistedVariableStatement = isHoistedVariableStatement;
14425     function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
14426         return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
14427     }
14428     ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
14429     function getJSDocCommentRanges(node, text) {
14430         var commentRanges = (node.kind === 160 /* Parameter */ ||
14431             node.kind === 159 /* TypeParameter */ ||
14432             node.kind === 208 /* FunctionExpression */ ||
14433             node.kind === 209 /* ArrowFunction */ ||
14434             node.kind === 207 /* ParenthesizedExpression */) ?
14435             ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
14436             ts.getLeadingCommentRanges(text, node.pos);
14437         // True if the comment starts with '/**' but not if it is '/**/'
14438         return ts.filter(commentRanges, function (comment) {
14439             return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
14440                 text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
14441                 text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
14442         });
14443     }
14444     ts.getJSDocCommentRanges = getJSDocCommentRanges;
14445     ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
14446     var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
14447     ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
14448     var defaultLibReferenceRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/;
14449     function isPartOfTypeNode(node) {
14450         if (172 /* FirstTypeNode */ <= node.kind && node.kind <= 195 /* LastTypeNode */) {
14451             return true;
14452         }
14453         switch (node.kind) {
14454             case 128 /* AnyKeyword */:
14455             case 152 /* UnknownKeyword */:
14456             case 144 /* NumberKeyword */:
14457             case 155 /* BigIntKeyword */:
14458             case 147 /* StringKeyword */:
14459             case 131 /* BooleanKeyword */:
14460             case 148 /* SymbolKeyword */:
14461             case 145 /* ObjectKeyword */:
14462             case 150 /* UndefinedKeyword */:
14463             case 141 /* NeverKeyword */:
14464                 return true;
14465             case 113 /* VoidKeyword */:
14466                 return node.parent.kind !== 212 /* VoidExpression */;
14467             case 223 /* ExpressionWithTypeArguments */:
14468                 return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
14469             case 159 /* TypeParameter */:
14470                 return node.parent.kind === 190 /* MappedType */ || node.parent.kind === 185 /* InferType */;
14471             // Identifiers and qualified names may be type nodes, depending on their context. Climb
14472             // above them to find the lowest container
14473             case 78 /* Identifier */:
14474                 // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
14475                 if (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) {
14476                     node = node.parent;
14477                 }
14478                 else if (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node) {
14479                     node = node.parent;
14480                 }
14481                 // At this point, node is either a qualified name or an identifier
14482                 ts.Debug.assert(node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */ || node.kind === 201 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
14483             // falls through
14484             case 157 /* QualifiedName */:
14485             case 201 /* PropertyAccessExpression */:
14486             case 107 /* ThisKeyword */: {
14487                 var parent = node.parent;
14488                 if (parent.kind === 176 /* TypeQuery */) {
14489                     return false;
14490                 }
14491                 if (parent.kind === 195 /* ImportType */) {
14492                     return !parent.isTypeOf;
14493                 }
14494                 // Do not recursively call isPartOfTypeNode on the parent. In the example:
14495                 //
14496                 //     let a: A.B.C;
14497                 //
14498                 // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
14499                 // Only C and A.B.C are type nodes.
14500                 if (172 /* FirstTypeNode */ <= parent.kind && parent.kind <= 195 /* LastTypeNode */) {
14501                     return true;
14502                 }
14503                 switch (parent.kind) {
14504                     case 223 /* ExpressionWithTypeArguments */:
14505                         return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
14506                     case 159 /* TypeParameter */:
14507                         return node === parent.constraint;
14508                     case 330 /* JSDocTemplateTag */:
14509                         return node === parent.constraint;
14510                     case 163 /* PropertyDeclaration */:
14511                     case 162 /* PropertySignature */:
14512                     case 160 /* Parameter */:
14513                     case 249 /* VariableDeclaration */:
14514                         return node === parent.type;
14515                     case 251 /* FunctionDeclaration */:
14516                     case 208 /* FunctionExpression */:
14517                     case 209 /* ArrowFunction */:
14518                     case 166 /* Constructor */:
14519                     case 165 /* MethodDeclaration */:
14520                     case 164 /* MethodSignature */:
14521                     case 167 /* GetAccessor */:
14522                     case 168 /* SetAccessor */:
14523                         return node === parent.type;
14524                     case 169 /* CallSignature */:
14525                     case 170 /* ConstructSignature */:
14526                     case 171 /* IndexSignature */:
14527                         return node === parent.type;
14528                     case 206 /* TypeAssertionExpression */:
14529                         return node === parent.type;
14530                     case 203 /* CallExpression */:
14531                     case 204 /* NewExpression */:
14532                         return ts.contains(parent.typeArguments, node);
14533                     case 205 /* TaggedTemplateExpression */:
14534                         // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
14535                         return false;
14536                 }
14537             }
14538         }
14539         return false;
14540     }
14541     ts.isPartOfTypeNode = isPartOfTypeNode;
14542     function isChildOfNodeWithKind(node, kind) {
14543         while (node) {
14544             if (node.kind === kind) {
14545                 return true;
14546             }
14547             node = node.parent;
14548         }
14549         return false;
14550     }
14551     ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
14552     // Warning: This has the same semantics as the forEach family of functions,
14553     //          in that traversal terminates in the event that 'visitor' supplies a truthy value.
14554     function forEachReturnStatement(body, visitor) {
14555         return traverse(body);
14556         function traverse(node) {
14557             switch (node.kind) {
14558                 case 242 /* ReturnStatement */:
14559                     return visitor(node);
14560                 case 258 /* CaseBlock */:
14561                 case 230 /* Block */:
14562                 case 234 /* IfStatement */:
14563                 case 235 /* DoStatement */:
14564                 case 236 /* WhileStatement */:
14565                 case 237 /* ForStatement */:
14566                 case 238 /* ForInStatement */:
14567                 case 239 /* ForOfStatement */:
14568                 case 243 /* WithStatement */:
14569                 case 244 /* SwitchStatement */:
14570                 case 284 /* CaseClause */:
14571                 case 285 /* DefaultClause */:
14572                 case 245 /* LabeledStatement */:
14573                 case 247 /* TryStatement */:
14574                 case 287 /* CatchClause */:
14575                     return ts.forEachChild(node, traverse);
14576             }
14577         }
14578     }
14579     ts.forEachReturnStatement = forEachReturnStatement;
14580     function forEachYieldExpression(body, visitor) {
14581         return traverse(body);
14582         function traverse(node) {
14583             switch (node.kind) {
14584                 case 219 /* YieldExpression */:
14585                     visitor(node);
14586                     var operand = node.expression;
14587                     if (operand) {
14588                         traverse(operand);
14589                     }
14590                     return;
14591                 case 255 /* EnumDeclaration */:
14592                 case 253 /* InterfaceDeclaration */:
14593                 case 256 /* ModuleDeclaration */:
14594                 case 254 /* TypeAliasDeclaration */:
14595                     // These are not allowed inside a generator now, but eventually they may be allowed
14596                     // as local types. Regardless, skip them to avoid the work.
14597                     return;
14598                 default:
14599                     if (ts.isFunctionLike(node)) {
14600                         if (node.name && node.name.kind === 158 /* ComputedPropertyName */) {
14601                             // Note that we will not include methods/accessors of a class because they would require
14602                             // first descending into the class. This is by design.
14603                             traverse(node.name.expression);
14604                             return;
14605                         }
14606                     }
14607                     else if (!isPartOfTypeNode(node)) {
14608                         // This is the general case, which should include mostly expressions and statements.
14609                         // Also includes NodeArrays.
14610                         ts.forEachChild(node, traverse);
14611                     }
14612             }
14613         }
14614     }
14615     ts.forEachYieldExpression = forEachYieldExpression;
14616     /**
14617      * Gets the most likely element type for a TypeNode. This is not an exhaustive test
14618      * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
14619      *
14620      * @param node The type node.
14621      */
14622     function getRestParameterElementType(node) {
14623         if (node && node.kind === 178 /* ArrayType */) {
14624             return node.elementType;
14625         }
14626         else if (node && node.kind === 173 /* TypeReference */) {
14627             return ts.singleOrUndefined(node.typeArguments);
14628         }
14629         else {
14630             return undefined;
14631         }
14632     }
14633     ts.getRestParameterElementType = getRestParameterElementType;
14634     function getMembersOfDeclaration(node) {
14635         switch (node.kind) {
14636             case 253 /* InterfaceDeclaration */:
14637             case 252 /* ClassDeclaration */:
14638             case 221 /* ClassExpression */:
14639             case 177 /* TypeLiteral */:
14640                 return node.members;
14641             case 200 /* ObjectLiteralExpression */:
14642                 return node.properties;
14643         }
14644     }
14645     ts.getMembersOfDeclaration = getMembersOfDeclaration;
14646     function isVariableLike(node) {
14647         if (node) {
14648             switch (node.kind) {
14649                 case 198 /* BindingElement */:
14650                 case 291 /* EnumMember */:
14651                 case 160 /* Parameter */:
14652                 case 288 /* PropertyAssignment */:
14653                 case 163 /* PropertyDeclaration */:
14654                 case 162 /* PropertySignature */:
14655                 case 289 /* ShorthandPropertyAssignment */:
14656                 case 249 /* VariableDeclaration */:
14657                     return true;
14658             }
14659         }
14660         return false;
14661     }
14662     ts.isVariableLike = isVariableLike;
14663     function isVariableLikeOrAccessor(node) {
14664         return isVariableLike(node) || ts.isAccessor(node);
14665     }
14666     ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
14667     function isVariableDeclarationInVariableStatement(node) {
14668         return node.parent.kind === 250 /* VariableDeclarationList */
14669             && node.parent.parent.kind === 232 /* VariableStatement */;
14670     }
14671     ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
14672     function isValidESSymbolDeclaration(node) {
14673         return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
14674             ts.isPropertyDeclaration(node) ? hasEffectiveReadonlyModifier(node) && hasStaticModifier(node) :
14675                 ts.isPropertySignature(node) && hasEffectiveReadonlyModifier(node);
14676     }
14677     ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
14678     function introducesArgumentsExoticObject(node) {
14679         switch (node.kind) {
14680             case 165 /* MethodDeclaration */:
14681             case 164 /* MethodSignature */:
14682             case 166 /* Constructor */:
14683             case 167 /* GetAccessor */:
14684             case 168 /* SetAccessor */:
14685             case 251 /* FunctionDeclaration */:
14686             case 208 /* FunctionExpression */:
14687                 return true;
14688         }
14689         return false;
14690     }
14691     ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
14692     function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
14693         while (true) {
14694             if (beforeUnwrapLabelCallback) {
14695                 beforeUnwrapLabelCallback(node);
14696             }
14697             if (node.statement.kind !== 245 /* LabeledStatement */) {
14698                 return node.statement;
14699             }
14700             node = node.statement;
14701         }
14702     }
14703     ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
14704     function isFunctionBlock(node) {
14705         return node && node.kind === 230 /* Block */ && ts.isFunctionLike(node.parent);
14706     }
14707     ts.isFunctionBlock = isFunctionBlock;
14708     function isObjectLiteralMethod(node) {
14709         return node && node.kind === 165 /* MethodDeclaration */ && node.parent.kind === 200 /* ObjectLiteralExpression */;
14710     }
14711     ts.isObjectLiteralMethod = isObjectLiteralMethod;
14712     function isObjectLiteralOrClassExpressionMethod(node) {
14713         return node.kind === 165 /* MethodDeclaration */ &&
14714             (node.parent.kind === 200 /* ObjectLiteralExpression */ ||
14715                 node.parent.kind === 221 /* ClassExpression */);
14716     }
14717     ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
14718     function isIdentifierTypePredicate(predicate) {
14719         return predicate && predicate.kind === 1 /* Identifier */;
14720     }
14721     ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
14722     function isThisTypePredicate(predicate) {
14723         return predicate && predicate.kind === 0 /* This */;
14724     }
14725     ts.isThisTypePredicate = isThisTypePredicate;
14726     function getPropertyAssignment(objectLiteral, key, key2) {
14727         return objectLiteral.properties.filter(function (property) {
14728             if (property.kind === 288 /* PropertyAssignment */) {
14729                 var propName = getTextOfPropertyName(property.name);
14730                 return key === propName || (!!key2 && key2 === propName);
14731             }
14732             return false;
14733         });
14734     }
14735     ts.getPropertyAssignment = getPropertyAssignment;
14736     function getPropertyArrayElementValue(objectLiteral, propKey, elementValue) {
14737         return ts.firstDefined(getPropertyAssignment(objectLiteral, propKey), function (property) {
14738             return ts.isArrayLiteralExpression(property.initializer) ?
14739                 ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
14740                 undefined;
14741         });
14742     }
14743     ts.getPropertyArrayElementValue = getPropertyArrayElementValue;
14744     function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
14745         if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
14746             var expression = tsConfigSourceFile.statements[0].expression;
14747             return ts.tryCast(expression, ts.isObjectLiteralExpression);
14748         }
14749     }
14750     ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
14751     function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
14752         return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
14753             return ts.isArrayLiteralExpression(property.initializer) ?
14754                 ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
14755                 undefined;
14756         });
14757     }
14758     ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
14759     function getTsConfigPropArray(tsConfigSourceFile, propKey) {
14760         var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
14761         return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
14762     }
14763     ts.getTsConfigPropArray = getTsConfigPropArray;
14764     function getContainingFunction(node) {
14765         return ts.findAncestor(node.parent, ts.isFunctionLike);
14766     }
14767     ts.getContainingFunction = getContainingFunction;
14768     function getContainingFunctionDeclaration(node) {
14769         return ts.findAncestor(node.parent, ts.isFunctionLikeDeclaration);
14770     }
14771     ts.getContainingFunctionDeclaration = getContainingFunctionDeclaration;
14772     function getContainingClass(node) {
14773         return ts.findAncestor(node.parent, ts.isClassLike);
14774     }
14775     ts.getContainingClass = getContainingClass;
14776     function getThisContainer(node, includeArrowFunctions) {
14777         ts.Debug.assert(node.kind !== 297 /* SourceFile */);
14778         while (true) {
14779             node = node.parent;
14780             if (!node) {
14781                 return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that.
14782             }
14783             switch (node.kind) {
14784                 case 158 /* ComputedPropertyName */:
14785                     // If the grandparent node is an object literal (as opposed to a class),
14786                     // then the computed property is not a 'this' container.
14787                     // A computed property name in a class needs to be a this container
14788                     // so that we can error on it.
14789                     if (ts.isClassLike(node.parent.parent)) {
14790                         return node;
14791                     }
14792                     // If this is a computed property, then the parent should not
14793                     // make it a this container. The parent might be a property
14794                     // in an object literal, like a method or accessor. But in order for
14795                     // such a parent to be a this container, the reference must be in
14796                     // the *body* of the container.
14797                     node = node.parent;
14798                     break;
14799                 case 161 /* Decorator */:
14800                     // Decorators are always applied outside of the body of a class or method.
14801                     if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14802                         // If the decorator's parent is a Parameter, we resolve the this container from
14803                         // the grandparent class declaration.
14804                         node = node.parent.parent;
14805                     }
14806                     else if (ts.isClassElement(node.parent)) {
14807                         // If the decorator's parent is a class element, we resolve the 'this' container
14808                         // from the parent class declaration.
14809                         node = node.parent;
14810                     }
14811                     break;
14812                 case 209 /* ArrowFunction */:
14813                     if (!includeArrowFunctions) {
14814                         continue;
14815                     }
14816                 // falls through
14817                 case 251 /* FunctionDeclaration */:
14818                 case 208 /* FunctionExpression */:
14819                 case 256 /* ModuleDeclaration */:
14820                 case 163 /* PropertyDeclaration */:
14821                 case 162 /* PropertySignature */:
14822                 case 165 /* MethodDeclaration */:
14823                 case 164 /* MethodSignature */:
14824                 case 166 /* Constructor */:
14825                 case 167 /* GetAccessor */:
14826                 case 168 /* SetAccessor */:
14827                 case 169 /* CallSignature */:
14828                 case 170 /* ConstructSignature */:
14829                 case 171 /* IndexSignature */:
14830                 case 255 /* EnumDeclaration */:
14831                 case 297 /* SourceFile */:
14832                     return node;
14833             }
14834         }
14835     }
14836     ts.getThisContainer = getThisContainer;
14837     function isInTopLevelContext(node) {
14838         // The name of a class or function declaration is a BindingIdentifier in its surrounding scope.
14839         if (ts.isIdentifier(node) && (ts.isClassDeclaration(node.parent) || ts.isFunctionDeclaration(node.parent)) && node.parent.name === node) {
14840             node = node.parent;
14841         }
14842         var container = getThisContainer(node, /*includeArrowFunctions*/ true);
14843         return ts.isSourceFile(container);
14844     }
14845     ts.isInTopLevelContext = isInTopLevelContext;
14846     function getNewTargetContainer(node) {
14847         var container = getThisContainer(node, /*includeArrowFunctions*/ false);
14848         if (container) {
14849             switch (container.kind) {
14850                 case 166 /* Constructor */:
14851                 case 251 /* FunctionDeclaration */:
14852                 case 208 /* FunctionExpression */:
14853                     return container;
14854             }
14855         }
14856         return undefined;
14857     }
14858     ts.getNewTargetContainer = getNewTargetContainer;
14859     /**
14860      * Given an super call/property node, returns the closest node where
14861      * - a super call/property access is legal in the node and not legal in the parent node the node.
14862      *   i.e. super call is legal in constructor but not legal in the class body.
14863      * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
14864      * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
14865      *   i.e. super property access is illegal in function declaration but can be legal in the statement list
14866      */
14867     function getSuperContainer(node, stopOnFunctions) {
14868         while (true) {
14869             node = node.parent;
14870             if (!node) {
14871                 return node;
14872             }
14873             switch (node.kind) {
14874                 case 158 /* ComputedPropertyName */:
14875                     node = node.parent;
14876                     break;
14877                 case 251 /* FunctionDeclaration */:
14878                 case 208 /* FunctionExpression */:
14879                 case 209 /* ArrowFunction */:
14880                     if (!stopOnFunctions) {
14881                         continue;
14882                     }
14883                 // falls through
14884                 case 163 /* PropertyDeclaration */:
14885                 case 162 /* PropertySignature */:
14886                 case 165 /* MethodDeclaration */:
14887                 case 164 /* MethodSignature */:
14888                 case 166 /* Constructor */:
14889                 case 167 /* GetAccessor */:
14890                 case 168 /* SetAccessor */:
14891                     return node;
14892                 case 161 /* Decorator */:
14893                     // Decorators are always applied outside of the body of a class or method.
14894                     if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14895                         // If the decorator's parent is a Parameter, we resolve the this container from
14896                         // the grandparent class declaration.
14897                         node = node.parent.parent;
14898                     }
14899                     else if (ts.isClassElement(node.parent)) {
14900                         // If the decorator's parent is a class element, we resolve the 'this' container
14901                         // from the parent class declaration.
14902                         node = node.parent;
14903                     }
14904                     break;
14905             }
14906         }
14907     }
14908     ts.getSuperContainer = getSuperContainer;
14909     function getImmediatelyInvokedFunctionExpression(func) {
14910         if (func.kind === 208 /* FunctionExpression */ || func.kind === 209 /* ArrowFunction */) {
14911             var prev = func;
14912             var parent = func.parent;
14913             while (parent.kind === 207 /* ParenthesizedExpression */) {
14914                 prev = parent;
14915                 parent = parent.parent;
14916             }
14917             if (parent.kind === 203 /* CallExpression */ && parent.expression === prev) {
14918                 return parent;
14919             }
14920         }
14921     }
14922     ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
14923     function isSuperOrSuperProperty(node) {
14924         return node.kind === 105 /* SuperKeyword */
14925             || isSuperProperty(node);
14926     }
14927     ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
14928     /**
14929      * Determines whether a node is a property or element access expression for `super`.
14930      */
14931     function isSuperProperty(node) {
14932         var kind = node.kind;
14933         return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */)
14934             && node.expression.kind === 105 /* SuperKeyword */;
14935     }
14936     ts.isSuperProperty = isSuperProperty;
14937     /**
14938      * Determines whether a node is a property or element access expression for `this`.
14939      */
14940     function isThisProperty(node) {
14941         var kind = node.kind;
14942         return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */)
14943             && node.expression.kind === 107 /* ThisKeyword */;
14944     }
14945     ts.isThisProperty = isThisProperty;
14946     function isThisInitializedDeclaration(node) {
14947         var _a;
14948         return !!node && ts.isVariableDeclaration(node) && ((_a = node.initializer) === null || _a === void 0 ? void 0 : _a.kind) === 107 /* ThisKeyword */;
14949     }
14950     ts.isThisInitializedDeclaration = isThisInitializedDeclaration;
14951     function getEntityNameFromTypeNode(node) {
14952         switch (node.kind) {
14953             case 173 /* TypeReference */:
14954                 return node.typeName;
14955             case 223 /* ExpressionWithTypeArguments */:
14956                 return isEntityNameExpression(node.expression)
14957                     ? node.expression
14958                     : undefined;
14959             // 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.
14960             case 78 /* Identifier */:
14961             case 157 /* QualifiedName */:
14962                 return node;
14963         }
14964         return undefined;
14965     }
14966     ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
14967     function getInvokedExpression(node) {
14968         switch (node.kind) {
14969             case 205 /* TaggedTemplateExpression */:
14970                 return node.tag;
14971             case 275 /* JsxOpeningElement */:
14972             case 274 /* JsxSelfClosingElement */:
14973                 return node.tagName;
14974             default:
14975                 return node.expression;
14976         }
14977     }
14978     ts.getInvokedExpression = getInvokedExpression;
14979     function nodeCanBeDecorated(node, parent, grandparent) {
14980         // private names cannot be used with decorators yet
14981         if (ts.isNamedDeclaration(node) && ts.isPrivateIdentifier(node.name)) {
14982             return false;
14983         }
14984         switch (node.kind) {
14985             case 252 /* ClassDeclaration */:
14986                 // classes are valid targets
14987                 return true;
14988             case 163 /* PropertyDeclaration */:
14989                 // property declarations are valid if their parent is a class declaration.
14990                 return parent.kind === 252 /* ClassDeclaration */;
14991             case 167 /* GetAccessor */:
14992             case 168 /* SetAccessor */:
14993             case 165 /* MethodDeclaration */:
14994                 // if this method has a body and its parent is a class declaration, this is a valid target.
14995                 return node.body !== undefined
14996                     && parent.kind === 252 /* ClassDeclaration */;
14997             case 160 /* Parameter */:
14998                 // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
14999                 return parent.body !== undefined
15000                     && (parent.kind === 166 /* Constructor */
15001                         || parent.kind === 165 /* MethodDeclaration */
15002                         || parent.kind === 168 /* SetAccessor */)
15003                     && grandparent.kind === 252 /* ClassDeclaration */;
15004         }
15005         return false;
15006     }
15007     ts.nodeCanBeDecorated = nodeCanBeDecorated;
15008     function nodeIsDecorated(node, parent, grandparent) {
15009         return node.decorators !== undefined
15010             && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
15011     }
15012     ts.nodeIsDecorated = nodeIsDecorated;
15013     function nodeOrChildIsDecorated(node, parent, grandparent) {
15014         return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
15015     }
15016     ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
15017     function childIsDecorated(node, parent) {
15018         switch (node.kind) {
15019             case 252 /* ClassDeclaration */:
15020                 return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
15021             case 165 /* MethodDeclaration */:
15022             case 168 /* SetAccessor */:
15023                 return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
15024             default:
15025                 return false;
15026         }
15027     }
15028     ts.childIsDecorated = childIsDecorated;
15029     function isJSXTagName(node) {
15030         var parent = node.parent;
15031         if (parent.kind === 275 /* JsxOpeningElement */ ||
15032             parent.kind === 274 /* JsxSelfClosingElement */ ||
15033             parent.kind === 276 /* JsxClosingElement */) {
15034             return parent.tagName === node;
15035         }
15036         return false;
15037     }
15038     ts.isJSXTagName = isJSXTagName;
15039     function isExpressionNode(node) {
15040         switch (node.kind) {
15041             case 105 /* SuperKeyword */:
15042             case 103 /* NullKeyword */:
15043             case 109 /* TrueKeyword */:
15044             case 94 /* FalseKeyword */:
15045             case 13 /* RegularExpressionLiteral */:
15046             case 199 /* ArrayLiteralExpression */:
15047             case 200 /* ObjectLiteralExpression */:
15048             case 201 /* PropertyAccessExpression */:
15049             case 202 /* ElementAccessExpression */:
15050             case 203 /* CallExpression */:
15051             case 204 /* NewExpression */:
15052             case 205 /* TaggedTemplateExpression */:
15053             case 224 /* AsExpression */:
15054             case 206 /* TypeAssertionExpression */:
15055             case 225 /* NonNullExpression */:
15056             case 207 /* ParenthesizedExpression */:
15057             case 208 /* FunctionExpression */:
15058             case 221 /* ClassExpression */:
15059             case 209 /* ArrowFunction */:
15060             case 212 /* VoidExpression */:
15061             case 210 /* DeleteExpression */:
15062             case 211 /* TypeOfExpression */:
15063             case 214 /* PrefixUnaryExpression */:
15064             case 215 /* PostfixUnaryExpression */:
15065             case 216 /* BinaryExpression */:
15066             case 217 /* ConditionalExpression */:
15067             case 220 /* SpreadElement */:
15068             case 218 /* TemplateExpression */:
15069             case 222 /* OmittedExpression */:
15070             case 273 /* JsxElement */:
15071             case 274 /* JsxSelfClosingElement */:
15072             case 277 /* JsxFragment */:
15073             case 219 /* YieldExpression */:
15074             case 213 /* AwaitExpression */:
15075             case 226 /* MetaProperty */:
15076                 return true;
15077             case 157 /* QualifiedName */:
15078                 while (node.parent.kind === 157 /* QualifiedName */) {
15079                     node = node.parent;
15080                 }
15081                 return node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node);
15082             case 78 /* Identifier */:
15083                 if (node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node)) {
15084                     return true;
15085                 }
15086             // falls through
15087             case 8 /* NumericLiteral */:
15088             case 9 /* BigIntLiteral */:
15089             case 10 /* StringLiteral */:
15090             case 14 /* NoSubstitutionTemplateLiteral */:
15091             case 107 /* ThisKeyword */:
15092                 return isInExpressionContext(node);
15093             default:
15094                 return false;
15095         }
15096     }
15097     ts.isExpressionNode = isExpressionNode;
15098     function isInExpressionContext(node) {
15099         var parent = node.parent;
15100         switch (parent.kind) {
15101             case 249 /* VariableDeclaration */:
15102             case 160 /* Parameter */:
15103             case 163 /* PropertyDeclaration */:
15104             case 162 /* PropertySignature */:
15105             case 291 /* EnumMember */:
15106             case 288 /* PropertyAssignment */:
15107             case 198 /* BindingElement */:
15108                 return parent.initializer === node;
15109             case 233 /* ExpressionStatement */:
15110             case 234 /* IfStatement */:
15111             case 235 /* DoStatement */:
15112             case 236 /* WhileStatement */:
15113             case 242 /* ReturnStatement */:
15114             case 243 /* WithStatement */:
15115             case 244 /* SwitchStatement */:
15116             case 284 /* CaseClause */:
15117             case 246 /* ThrowStatement */:
15118                 return parent.expression === node;
15119             case 237 /* ForStatement */:
15120                 var forStatement = parent;
15121                 return (forStatement.initializer === node && forStatement.initializer.kind !== 250 /* VariableDeclarationList */) ||
15122                     forStatement.condition === node ||
15123                     forStatement.incrementor === node;
15124             case 238 /* ForInStatement */:
15125             case 239 /* ForOfStatement */:
15126                 var forInStatement = parent;
15127                 return (forInStatement.initializer === node && forInStatement.initializer.kind !== 250 /* VariableDeclarationList */) ||
15128                     forInStatement.expression === node;
15129             case 206 /* TypeAssertionExpression */:
15130             case 224 /* AsExpression */:
15131                 return node === parent.expression;
15132             case 228 /* TemplateSpan */:
15133                 return node === parent.expression;
15134             case 158 /* ComputedPropertyName */:
15135                 return node === parent.expression;
15136             case 161 /* Decorator */:
15137             case 283 /* JsxExpression */:
15138             case 282 /* JsxSpreadAttribute */:
15139             case 290 /* SpreadAssignment */:
15140                 return true;
15141             case 223 /* ExpressionWithTypeArguments */:
15142                 return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
15143             case 289 /* ShorthandPropertyAssignment */:
15144                 return parent.objectAssignmentInitializer === node;
15145             default:
15146                 return isExpressionNode(parent);
15147         }
15148     }
15149     ts.isInExpressionContext = isInExpressionContext;
15150     function isPartOfTypeQuery(node) {
15151         while (node.kind === 157 /* QualifiedName */ || node.kind === 78 /* Identifier */) {
15152             node = node.parent;
15153         }
15154         return node.kind === 176 /* TypeQuery */;
15155     }
15156     ts.isPartOfTypeQuery = isPartOfTypeQuery;
15157     function isExternalModuleImportEqualsDeclaration(node) {
15158         return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 272 /* ExternalModuleReference */;
15159     }
15160     ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
15161     function getExternalModuleImportEqualsDeclarationExpression(node) {
15162         ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
15163         return node.moduleReference.expression;
15164     }
15165     ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
15166     function getExternalModuleRequireArgument(node) {
15167         return isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true)
15168             && getLeftmostAccessExpression(node.initializer).arguments[0];
15169     }
15170     ts.getExternalModuleRequireArgument = getExternalModuleRequireArgument;
15171     function isInternalModuleImportEqualsDeclaration(node) {
15172         return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 272 /* ExternalModuleReference */;
15173     }
15174     ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
15175     function isSourceFileJS(file) {
15176         return isInJSFile(file);
15177     }
15178     ts.isSourceFileJS = isSourceFileJS;
15179     function isSourceFileNotJS(file) {
15180         return !isInJSFile(file);
15181     }
15182     ts.isSourceFileNotJS = isSourceFileNotJS;
15183     function isInJSFile(node) {
15184         return !!node && !!(node.flags & 131072 /* JavaScriptFile */);
15185     }
15186     ts.isInJSFile = isInJSFile;
15187     function isInJsonFile(node) {
15188         return !!node && !!(node.flags & 33554432 /* JsonFile */);
15189     }
15190     ts.isInJsonFile = isInJsonFile;
15191     function isSourceFileNotJson(file) {
15192         return !isJsonSourceFile(file);
15193     }
15194     ts.isSourceFileNotJson = isSourceFileNotJson;
15195     function isInJSDoc(node) {
15196         return !!node && !!(node.flags & 4194304 /* JSDoc */);
15197     }
15198     ts.isInJSDoc = isInJSDoc;
15199     function isJSDocIndexSignature(node) {
15200         return ts.isTypeReferenceNode(node) &&
15201             ts.isIdentifier(node.typeName) &&
15202             node.typeName.escapedText === "Object" &&
15203             node.typeArguments && node.typeArguments.length === 2 &&
15204             (node.typeArguments[0].kind === 147 /* StringKeyword */ || node.typeArguments[0].kind === 144 /* NumberKeyword */);
15205     }
15206     ts.isJSDocIndexSignature = isJSDocIndexSignature;
15207     function isRequireCall(callExpression, requireStringLiteralLikeArgument) {
15208         if (callExpression.kind !== 203 /* CallExpression */) {
15209             return false;
15210         }
15211         var _a = callExpression, expression = _a.expression, args = _a.arguments;
15212         if (expression.kind !== 78 /* Identifier */ || expression.escapedText !== "require") {
15213             return false;
15214         }
15215         if (args.length !== 1) {
15216             return false;
15217         }
15218         var arg = args[0];
15219         return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg);
15220     }
15221     ts.isRequireCall = isRequireCall;
15222     function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) {
15223         if (node.kind === 198 /* BindingElement */) {
15224             node = node.parent.parent;
15225         }
15226         return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), requireStringLiteralLikeArgument);
15227     }
15228     ts.isRequireVariableDeclaration = isRequireVariableDeclaration;
15229     function isRequireVariableStatement(node, requireStringLiteralLikeArgument) {
15230         if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; }
15231         return ts.isVariableStatement(node)
15232             && node.declarationList.declarations.length > 0
15233             && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); });
15234     }
15235     ts.isRequireVariableStatement = isRequireVariableStatement;
15236     function isSingleOrDoubleQuote(charCode) {
15237         return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
15238     }
15239     ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
15240     function isStringDoubleQuoted(str, sourceFile) {
15241         return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
15242     }
15243     ts.isStringDoubleQuoted = isStringDoubleQuoted;
15244     function isAssignmentDeclaration(decl) {
15245         return ts.isBinaryExpression(decl) || isAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl);
15246     }
15247     ts.isAssignmentDeclaration = isAssignmentDeclaration;
15248     /** Get the initializer, taking into account defaulted Javascript initializers */
15249     function getEffectiveInitializer(node) {
15250         if (isInJSFile(node) && node.initializer &&
15251             ts.isBinaryExpression(node.initializer) &&
15252             (node.initializer.operatorToken.kind === 56 /* BarBarToken */ || node.initializer.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
15253             node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
15254             return node.initializer.right;
15255         }
15256         return node.initializer;
15257     }
15258     ts.getEffectiveInitializer = getEffectiveInitializer;
15259     /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */
15260     function getDeclaredExpandoInitializer(node) {
15261         var init = getEffectiveInitializer(node);
15262         return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
15263     }
15264     ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
15265     function hasExpandoValueProperty(node, isPrototypeAssignment) {
15266         return ts.forEach(node.properties, function (p) {
15267             return ts.isPropertyAssignment(p) &&
15268                 ts.isIdentifier(p.name) &&
15269                 p.name.escapedText === "value" &&
15270                 p.initializer &&
15271                 getExpandoInitializer(p.initializer, isPrototypeAssignment);
15272         });
15273     }
15274     /**
15275      * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
15276      * We treat the right hand side of assignments with container-like initializers as declarations.
15277      */
15278     function getAssignedExpandoInitializer(node) {
15279         if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) {
15280             var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
15281             return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
15282                 getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
15283         }
15284         if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) {
15285             var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype");
15286             if (result) {
15287                 return result;
15288             }
15289         }
15290     }
15291     ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
15292     /**
15293      * Recognized expando initializers are:
15294      * 1. (function() {})() -- IIFEs
15295      * 2. function() { } -- Function expressions
15296      * 3. class { } -- Class expressions
15297      * 4. {} -- Empty object literals
15298      * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }`
15299      *
15300      * This function returns the provided initializer, or undefined if it is not valid.
15301      */
15302     function getExpandoInitializer(initializer, isPrototypeAssignment) {
15303         if (ts.isCallExpression(initializer)) {
15304             var e = skipParentheses(initializer.expression);
15305             return e.kind === 208 /* FunctionExpression */ || e.kind === 209 /* ArrowFunction */ ? initializer : undefined;
15306         }
15307         if (initializer.kind === 208 /* FunctionExpression */ ||
15308             initializer.kind === 221 /* ClassExpression */ ||
15309             initializer.kind === 209 /* ArrowFunction */) {
15310             return initializer;
15311         }
15312         if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
15313             return initializer;
15314         }
15315     }
15316     ts.getExpandoInitializer = getExpandoInitializer;
15317     /**
15318      * A defaulted expando initializer matches the pattern
15319      * `Lhs = Lhs || ExpandoInitializer`
15320      * or `var Lhs = Lhs || ExpandoInitializer`
15321      *
15322      * The second Lhs is required to be the same as the first except that it may be prefixed with
15323      * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
15324      */
15325     function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
15326         var e = ts.isBinaryExpression(initializer)
15327             && (initializer.operatorToken.kind === 56 /* BarBarToken */ || initializer.operatorToken.kind === 60 /* QuestionQuestionToken */)
15328             && getExpandoInitializer(initializer.right, isPrototypeAssignment);
15329         if (e && isSameEntityName(name, initializer.left)) {
15330             return e;
15331         }
15332     }
15333     function isDefaultedExpandoInitializer(node) {
15334         var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
15335             ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ ? node.parent.left :
15336                 undefined;
15337         return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
15338     }
15339     ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
15340     /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
15341     function getNameOfExpando(node) {
15342         if (ts.isBinaryExpression(node.parent)) {
15343             var parent = ((node.parent.operatorToken.kind === 56 /* BarBarToken */ || node.parent.operatorToken.kind === 60 /* QuestionQuestionToken */) && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
15344             if (parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
15345                 return parent.left;
15346             }
15347         }
15348         else if (ts.isVariableDeclaration(node.parent)) {
15349             return node.parent.name;
15350         }
15351     }
15352     ts.getNameOfExpando = getNameOfExpando;
15353     /**
15354      * Is the 'declared' name the same as the one in the initializer?
15355      * @return true for identical entity names, as well as ones where the initializer is prefixed with
15356      * 'window', 'self' or 'global'. For example:
15357      *
15358      * var my = my || {}
15359      * var min = window.min || {}
15360      * my.app = self.my.app || class { }
15361      */
15362     function isSameEntityName(name, initializer) {
15363         if (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) {
15364             return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(initializer);
15365         }
15366         if (ts.isIdentifier(name) && isLiteralLikeAccess(initializer) &&
15367             (initializer.expression.kind === 107 /* ThisKeyword */ ||
15368                 ts.isIdentifier(initializer.expression) &&
15369                     (initializer.expression.escapedText === "window" ||
15370                         initializer.expression.escapedText === "self" ||
15371                         initializer.expression.escapedText === "global"))) {
15372             var nameOrArgument = getNameOrArgument(initializer);
15373             if (ts.isPrivateIdentifier(nameOrArgument)) {
15374                 ts.Debug.fail("Unexpected PrivateIdentifier in name expression with literal-like access.");
15375             }
15376             return isSameEntityName(name, nameOrArgument);
15377         }
15378         if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) {
15379             return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer)
15380                 && isSameEntityName(name.expression, initializer.expression);
15381         }
15382         return false;
15383     }
15384     ts.isSameEntityName = isSameEntityName;
15385     function getRightMostAssignedExpression(node) {
15386         while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
15387             node = node.right;
15388         }
15389         return node;
15390     }
15391     ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
15392     function isExportsIdentifier(node) {
15393         return ts.isIdentifier(node) && node.escapedText === "exports";
15394     }
15395     ts.isExportsIdentifier = isExportsIdentifier;
15396     function isModuleIdentifier(node) {
15397         return ts.isIdentifier(node) && node.escapedText === "module";
15398     }
15399     ts.isModuleIdentifier = isModuleIdentifier;
15400     function isModuleExportsAccessExpression(node) {
15401         return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node))
15402             && isModuleIdentifier(node.expression)
15403             && getElementOrPropertyAccessName(node) === "exports";
15404     }
15405     ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression;
15406     /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
15407     /// assignments we treat as special in the binder
15408     function getAssignmentDeclarationKind(expr) {
15409         var special = getAssignmentDeclarationKindWorker(expr);
15410         return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
15411     }
15412     ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
15413     function isBindableObjectDefinePropertyCall(expr) {
15414         return ts.length(expr.arguments) === 3 &&
15415             ts.isPropertyAccessExpression(expr.expression) &&
15416             ts.isIdentifier(expr.expression.expression) &&
15417             ts.idText(expr.expression.expression) === "Object" &&
15418             ts.idText(expr.expression.name) === "defineProperty" &&
15419             isStringOrNumericLiteralLike(expr.arguments[1]) &&
15420             isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true);
15421     }
15422     ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
15423     /** x.y OR x[0] */
15424     function isLiteralLikeAccess(node) {
15425         return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node);
15426     }
15427     ts.isLiteralLikeAccess = isLiteralLikeAccess;
15428     /** x[0] OR x['a'] OR x[Symbol.y] */
15429     function isLiteralLikeElementAccess(node) {
15430         return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) ||
15431             isWellKnownSymbolSyntactically(node.argumentExpression));
15432     }
15433     ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess;
15434     /** Any series of property and element accesses. */
15435     function isBindableStaticAccessExpression(node, excludeThisKeyword) {
15436         return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 107 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true))
15437             || isBindableStaticElementAccessExpression(node, excludeThisKeyword);
15438     }
15439     ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression;
15440     /** Any series of property and element accesses, ending in a literal element access */
15441     function isBindableStaticElementAccessExpression(node, excludeThisKeyword) {
15442         return isLiteralLikeElementAccess(node)
15443             && ((!excludeThisKeyword && node.expression.kind === 107 /* ThisKeyword */) ||
15444                 isEntityNameExpression(node.expression) ||
15445                 isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true));
15446     }
15447     ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression;
15448     function isBindableStaticNameExpression(node, excludeThisKeyword) {
15449         return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword);
15450     }
15451     ts.isBindableStaticNameExpression = isBindableStaticNameExpression;
15452     function getNameOrArgument(expr) {
15453         if (ts.isPropertyAccessExpression(expr)) {
15454             return expr.name;
15455         }
15456         return expr.argumentExpression;
15457     }
15458     ts.getNameOrArgument = getNameOrArgument;
15459     function getAssignmentDeclarationKindWorker(expr) {
15460         if (ts.isCallExpression(expr)) {
15461             if (!isBindableObjectDefinePropertyCall(expr)) {
15462                 return 0 /* None */;
15463             }
15464             var entityName = expr.arguments[0];
15465             if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) {
15466                 return 8 /* ObjectDefinePropertyExports */;
15467             }
15468             if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") {
15469                 return 9 /* ObjectDefinePrototypeProperty */;
15470             }
15471             return 7 /* ObjectDefinePropertyValue */;
15472         }
15473         if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left) || isVoidZero(getRightMostAssignedExpression(expr))) {
15474             return 0 /* None */;
15475         }
15476         if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
15477             // F.prototype = { ... }
15478             return 6 /* Prototype */;
15479         }
15480         return getAssignmentDeclarationPropertyAccessKind(expr.left);
15481     }
15482     function isVoidZero(node) {
15483         return ts.isVoidExpression(node) && ts.isNumericLiteral(node.expression) && node.expression.text === "0";
15484     }
15485     /**
15486      * Does not handle signed numeric names like `a[+0]` - handling those would require handling prefix unary expressions
15487      * throughout late binding handling as well, which is awkward (but ultimately probably doable if there is demand)
15488      */
15489     /* @internal */
15490     function getElementOrPropertyAccessArgumentExpressionOrName(node) {
15491         if (ts.isPropertyAccessExpression(node)) {
15492             return node.name;
15493         }
15494         var arg = skipParentheses(node.argumentExpression);
15495         if (ts.isNumericLiteral(arg) || ts.isStringLiteralLike(arg)) {
15496             return arg;
15497         }
15498         return node;
15499     }
15500     ts.getElementOrPropertyAccessArgumentExpressionOrName = getElementOrPropertyAccessArgumentExpressionOrName;
15501     function getElementOrPropertyAccessName(node) {
15502         var name = getElementOrPropertyAccessArgumentExpressionOrName(node);
15503         if (name) {
15504             if (ts.isIdentifier(name)) {
15505                 return name.escapedText;
15506             }
15507             if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
15508                 return ts.escapeLeadingUnderscores(name.text);
15509             }
15510         }
15511         if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) {
15512             return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name));
15513         }
15514         return undefined;
15515     }
15516     ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName;
15517     function getAssignmentDeclarationPropertyAccessKind(lhs) {
15518         if (lhs.expression.kind === 107 /* ThisKeyword */) {
15519             return 4 /* ThisProperty */;
15520         }
15521         else if (isModuleExportsAccessExpression(lhs)) {
15522             // module.exports = expr
15523             return 2 /* ModuleExports */;
15524         }
15525         else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ true)) {
15526             if (isPrototypeAccess(lhs.expression)) {
15527                 // F.G....prototype.x = expr
15528                 return 3 /* PrototypeProperty */;
15529             }
15530             var nextToLast = lhs;
15531             while (!ts.isIdentifier(nextToLast.expression)) {
15532                 nextToLast = nextToLast.expression;
15533             }
15534             var id = nextToLast.expression;
15535             if ((id.escapedText === "exports" ||
15536                 id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") &&
15537                 // ExportsProperty does not support binding with computed names
15538                 isBindableStaticAccessExpression(lhs)) {
15539                 // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ...
15540                 return 1 /* ExportsProperty */;
15541             }
15542             if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs))) {
15543                 // F.G...x = expr
15544                 return 5 /* Property */;
15545             }
15546         }
15547         return 0 /* None */;
15548     }
15549     ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
15550     function getInitializerOfBinaryExpression(expr) {
15551         while (ts.isBinaryExpression(expr.right)) {
15552             expr = expr.right;
15553         }
15554         return expr.right;
15555     }
15556     ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
15557     function isPrototypePropertyAssignment(node) {
15558         return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
15559     }
15560     ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
15561     function isSpecialPropertyDeclaration(expr) {
15562         return isInJSFile(expr) &&
15563             expr.parent && expr.parent.kind === 233 /* ExpressionStatement */ &&
15564             (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) &&
15565             !!ts.getJSDocTypeTag(expr.parent);
15566     }
15567     ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
15568     function setValueDeclaration(symbol, node) {
15569         var valueDeclaration = symbol.valueDeclaration;
15570         if (!valueDeclaration ||
15571             !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) &&
15572                 (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) ||
15573             (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) {
15574             // other kinds of value declarations take precedence over modules and assignment declarations
15575             symbol.valueDeclaration = node;
15576         }
15577     }
15578     ts.setValueDeclaration = setValueDeclaration;
15579     function isFunctionSymbol(symbol) {
15580         if (!symbol || !symbol.valueDeclaration) {
15581             return false;
15582         }
15583         var decl = symbol.valueDeclaration;
15584         return decl.kind === 251 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
15585     }
15586     ts.isFunctionSymbol = isFunctionSymbol;
15587     function importFromModuleSpecifier(node) {
15588         return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent);
15589     }
15590     ts.importFromModuleSpecifier = importFromModuleSpecifier;
15591     function tryGetImportFromModuleSpecifier(node) {
15592         switch (node.parent.kind) {
15593             case 261 /* ImportDeclaration */:
15594             case 267 /* ExportDeclaration */:
15595                 return node.parent;
15596             case 272 /* ExternalModuleReference */:
15597                 return node.parent.parent;
15598             case 203 /* CallExpression */:
15599                 return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined;
15600             case 191 /* LiteralType */:
15601                 ts.Debug.assert(ts.isStringLiteral(node));
15602                 return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
15603             default:
15604                 return undefined;
15605         }
15606     }
15607     ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
15608     function getExternalModuleName(node) {
15609         switch (node.kind) {
15610             case 261 /* ImportDeclaration */:
15611             case 267 /* ExportDeclaration */:
15612                 return node.moduleSpecifier;
15613             case 260 /* ImportEqualsDeclaration */:
15614                 return node.moduleReference.kind === 272 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
15615             case 195 /* ImportType */:
15616                 return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
15617             case 203 /* CallExpression */:
15618                 return node.arguments[0];
15619             case 256 /* ModuleDeclaration */:
15620                 return node.name.kind === 10 /* StringLiteral */ ? node.name : undefined;
15621             default:
15622                 return ts.Debug.assertNever(node);
15623         }
15624     }
15625     ts.getExternalModuleName = getExternalModuleName;
15626     function getNamespaceDeclarationNode(node) {
15627         switch (node.kind) {
15628             case 261 /* ImportDeclaration */:
15629                 return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
15630             case 260 /* ImportEqualsDeclaration */:
15631                 return node;
15632             case 267 /* ExportDeclaration */:
15633                 return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport);
15634             default:
15635                 return ts.Debug.assertNever(node);
15636         }
15637     }
15638     ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
15639     function isDefaultImport(node) {
15640         return node.kind === 261 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
15641     }
15642     ts.isDefaultImport = isDefaultImport;
15643     function forEachImportClauseDeclaration(node, action) {
15644         if (node.name) {
15645             var result = action(node);
15646             if (result)
15647                 return result;
15648         }
15649         if (node.namedBindings) {
15650             var result = ts.isNamespaceImport(node.namedBindings)
15651                 ? action(node.namedBindings)
15652                 : ts.forEach(node.namedBindings.elements, action);
15653             if (result)
15654                 return result;
15655         }
15656     }
15657     ts.forEachImportClauseDeclaration = forEachImportClauseDeclaration;
15658     function hasQuestionToken(node) {
15659         if (node) {
15660             switch (node.kind) {
15661                 case 160 /* Parameter */:
15662                 case 165 /* MethodDeclaration */:
15663                 case 164 /* MethodSignature */:
15664                 case 289 /* ShorthandPropertyAssignment */:
15665                 case 288 /* PropertyAssignment */:
15666                 case 163 /* PropertyDeclaration */:
15667                 case 162 /* PropertySignature */:
15668                     return node.questionToken !== undefined;
15669             }
15670         }
15671         return false;
15672     }
15673     ts.hasQuestionToken = hasQuestionToken;
15674     function isJSDocConstructSignature(node) {
15675         var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined;
15676         var name = ts.tryCast(param && param.name, ts.isIdentifier);
15677         return !!name && name.escapedText === "new";
15678     }
15679     ts.isJSDocConstructSignature = isJSDocConstructSignature;
15680     function isJSDocTypeAlias(node) {
15681         return node.kind === 331 /* JSDocTypedefTag */ || node.kind === 324 /* JSDocCallbackTag */ || node.kind === 325 /* JSDocEnumTag */;
15682     }
15683     ts.isJSDocTypeAlias = isJSDocTypeAlias;
15684     function isTypeAlias(node) {
15685         return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
15686     }
15687     ts.isTypeAlias = isTypeAlias;
15688     function getSourceOfAssignment(node) {
15689         return ts.isExpressionStatement(node) &&
15690             ts.isBinaryExpression(node.expression) &&
15691             node.expression.operatorToken.kind === 62 /* EqualsToken */
15692             ? getRightMostAssignedExpression(node.expression)
15693             : undefined;
15694     }
15695     function getSourceOfDefaultedAssignment(node) {
15696         return ts.isExpressionStatement(node) &&
15697             ts.isBinaryExpression(node.expression) &&
15698             getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
15699             ts.isBinaryExpression(node.expression.right) &&
15700             (node.expression.right.operatorToken.kind === 56 /* BarBarToken */ || node.expression.right.operatorToken.kind === 60 /* QuestionQuestionToken */)
15701             ? node.expression.right.right
15702             : undefined;
15703     }
15704     function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
15705         switch (node.kind) {
15706             case 232 /* VariableStatement */:
15707                 var v = getSingleVariableOfVariableStatement(node);
15708                 return v && v.initializer;
15709             case 163 /* PropertyDeclaration */:
15710                 return node.initializer;
15711             case 288 /* PropertyAssignment */:
15712                 return node.initializer;
15713         }
15714     }
15715     ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration;
15716     function getSingleVariableOfVariableStatement(node) {
15717         return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
15718     }
15719     ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement;
15720     function getNestedModuleDeclaration(node) {
15721         return ts.isModuleDeclaration(node) &&
15722             node.body &&
15723             node.body.kind === 256 /* ModuleDeclaration */
15724             ? node.body
15725             : undefined;
15726     }
15727     function getJSDocCommentsAndTags(hostNode, noCache) {
15728         var result;
15729         // Pull parameter comments from declaring function as well
15730         if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
15731             result = ts.append(result, ts.last(hostNode.initializer.jsDoc));
15732         }
15733         var node = hostNode;
15734         while (node && node.parent) {
15735             if (ts.hasJSDocNodes(node)) {
15736                 result = ts.append(result, ts.last(node.jsDoc));
15737             }
15738             if (node.kind === 160 /* Parameter */) {
15739                 result = ts.addRange(result, (noCache ? ts.getJSDocParameterTagsNoCache : ts.getJSDocParameterTags)(node));
15740                 break;
15741             }
15742             if (node.kind === 159 /* TypeParameter */) {
15743                 result = ts.addRange(result, (noCache ? ts.getJSDocTypeParameterTagsNoCache : ts.getJSDocTypeParameterTags)(node));
15744                 break;
15745             }
15746             node = getNextJSDocCommentLocation(node);
15747         }
15748         return result || ts.emptyArray;
15749     }
15750     ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
15751     function getNextJSDocCommentLocation(node) {
15752         var parent = node.parent;
15753         if (parent.kind === 288 /* PropertyAssignment */ ||
15754             parent.kind === 266 /* ExportAssignment */ ||
15755             parent.kind === 163 /* PropertyDeclaration */ ||
15756             parent.kind === 233 /* ExpressionStatement */ && node.kind === 201 /* PropertyAccessExpression */ ||
15757             getNestedModuleDeclaration(parent) ||
15758             ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) {
15759             return parent;
15760         }
15761         // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement.
15762         // /**
15763         //   * @param {number} name
15764         //   * @returns {number}
15765         //   */
15766         // var x = function(name) { return name.length; }
15767         else if (parent.parent &&
15768             (getSingleVariableOfVariableStatement(parent.parent) === node ||
15769                 ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */)) {
15770             return parent.parent;
15771         }
15772         else if (parent.parent && parent.parent.parent &&
15773             (getSingleVariableOfVariableStatement(parent.parent.parent) ||
15774                 getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
15775                 getSourceOfDefaultedAssignment(parent.parent.parent))) {
15776             return parent.parent.parent;
15777         }
15778     }
15779     ts.getNextJSDocCommentLocation = getNextJSDocCommentLocation;
15780     /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
15781     function getParameterSymbolFromJSDoc(node) {
15782         if (node.symbol) {
15783             return node.symbol;
15784         }
15785         if (!ts.isIdentifier(node.name)) {
15786             return undefined;
15787         }
15788         var name = node.name.escapedText;
15789         var decl = getHostSignatureFromJSDoc(node);
15790         if (!decl) {
15791             return undefined;
15792         }
15793         var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 78 /* Identifier */ && p.name.escapedText === name; });
15794         return parameter && parameter.symbol;
15795     }
15796     ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
15797     function getHostSignatureFromJSDoc(node) {
15798         var host = getEffectiveJSDocHost(node);
15799         return host && ts.isFunctionLike(host) ? host : undefined;
15800     }
15801     ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
15802     function getEffectiveJSDocHost(node) {
15803         var host = getJSDocHost(node);
15804         if (host) {
15805             return getSourceOfDefaultedAssignment(host)
15806                 || getSourceOfAssignment(host)
15807                 || getSingleInitializerOfVariableStatementOrPropertyDeclaration(host)
15808                 || getSingleVariableOfVariableStatement(host)
15809                 || getNestedModuleDeclaration(host)
15810                 || host;
15811         }
15812     }
15813     ts.getEffectiveJSDocHost = getEffectiveJSDocHost;
15814     /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments. */
15815     function getJSDocHost(node) {
15816         var jsDoc = getJSDocRoot(node);
15817         if (!jsDoc) {
15818             return undefined;
15819         }
15820         var host = jsDoc.parent;
15821         if (host && host.jsDoc && jsDoc === ts.lastOrUndefined(host.jsDoc)) {
15822             return host;
15823         }
15824     }
15825     ts.getJSDocHost = getJSDocHost;
15826     function getJSDocRoot(node) {
15827         return ts.findAncestor(node.parent, ts.isJSDoc);
15828     }
15829     ts.getJSDocRoot = getJSDocRoot;
15830     function getTypeParameterFromJsDoc(node) {
15831         var name = node.name.escapedText;
15832         var typeParameters = node.parent.parent.parent.typeParameters;
15833         return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
15834     }
15835     ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
15836     function hasRestParameter(s) {
15837         var last = ts.lastOrUndefined(s.parameters);
15838         return !!last && isRestParameter(last);
15839     }
15840     ts.hasRestParameter = hasRestParameter;
15841     function isRestParameter(node) {
15842         var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
15843         return node.dotDotDotToken !== undefined || !!type && type.kind === 309 /* JSDocVariadicType */;
15844     }
15845     ts.isRestParameter = isRestParameter;
15846     function hasTypeArguments(node) {
15847         return !!node.typeArguments;
15848     }
15849     ts.hasTypeArguments = hasTypeArguments;
15850     var AssignmentKind;
15851     (function (AssignmentKind) {
15852         AssignmentKind[AssignmentKind["None"] = 0] = "None";
15853         AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
15854         AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
15855     })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
15856     function getAssignmentTargetKind(node) {
15857         var parent = node.parent;
15858         while (true) {
15859             switch (parent.kind) {
15860                 case 216 /* BinaryExpression */:
15861                     var binaryOperator = parent.operatorToken.kind;
15862                     return isAssignmentOperator(binaryOperator) && parent.left === node ?
15863                         binaryOperator === 62 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */ :
15864                         0 /* None */;
15865                 case 214 /* PrefixUnaryExpression */:
15866                 case 215 /* PostfixUnaryExpression */:
15867                     var unaryOperator = parent.operator;
15868                     return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
15869                 case 238 /* ForInStatement */:
15870                 case 239 /* ForOfStatement */:
15871                     return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
15872                 case 207 /* ParenthesizedExpression */:
15873                 case 199 /* ArrayLiteralExpression */:
15874                 case 220 /* SpreadElement */:
15875                 case 225 /* NonNullExpression */:
15876                     node = parent;
15877                     break;
15878                 case 289 /* ShorthandPropertyAssignment */:
15879                     if (parent.name !== node) {
15880                         return 0 /* None */;
15881                     }
15882                     node = parent.parent;
15883                     break;
15884                 case 288 /* PropertyAssignment */:
15885                     if (parent.name === node) {
15886                         return 0 /* None */;
15887                     }
15888                     node = parent.parent;
15889                     break;
15890                 default:
15891                     return 0 /* None */;
15892             }
15893             parent = node.parent;
15894         }
15895     }
15896     ts.getAssignmentTargetKind = getAssignmentTargetKind;
15897     // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
15898     // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
15899     // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
15900     // (Note that `p` is not a target in the above examples, only `a`.)
15901     function isAssignmentTarget(node) {
15902         return getAssignmentTargetKind(node) !== 0 /* None */;
15903     }
15904     ts.isAssignmentTarget = isAssignmentTarget;
15905     /**
15906      * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to
15907      * the same `var` declaration scope as the node's parent.
15908      */
15909     function isNodeWithPossibleHoistedDeclaration(node) {
15910         switch (node.kind) {
15911             case 230 /* Block */:
15912             case 232 /* VariableStatement */:
15913             case 243 /* WithStatement */:
15914             case 234 /* IfStatement */:
15915             case 244 /* SwitchStatement */:
15916             case 258 /* CaseBlock */:
15917             case 284 /* CaseClause */:
15918             case 285 /* DefaultClause */:
15919             case 245 /* LabeledStatement */:
15920             case 237 /* ForStatement */:
15921             case 238 /* ForInStatement */:
15922             case 239 /* ForOfStatement */:
15923             case 235 /* DoStatement */:
15924             case 236 /* WhileStatement */:
15925             case 247 /* TryStatement */:
15926             case 287 /* CatchClause */:
15927                 return true;
15928         }
15929         return false;
15930     }
15931     ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
15932     function isValueSignatureDeclaration(node) {
15933         return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
15934     }
15935     ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
15936     function walkUp(node, kind) {
15937         while (node && node.kind === kind) {
15938             node = node.parent;
15939         }
15940         return node;
15941     }
15942     function walkUpParenthesizedTypes(node) {
15943         return walkUp(node, 186 /* ParenthesizedType */);
15944     }
15945     ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
15946     function walkUpParenthesizedExpressions(node) {
15947         return walkUp(node, 207 /* ParenthesizedExpression */);
15948     }
15949     ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
15950     /**
15951      * Walks up parenthesized types.
15952      * It returns both the outermost parenthesized type and its parent.
15953      * If given node is not a parenthesiezd type, undefined is return as the former.
15954      */
15955     function walkUpParenthesizedTypesAndGetParentAndChild(node) {
15956         var child;
15957         while (node && node.kind === 186 /* ParenthesizedType */) {
15958             child = node;
15959             node = node.parent;
15960         }
15961         return [child, node];
15962     }
15963     ts.walkUpParenthesizedTypesAndGetParentAndChild = walkUpParenthesizedTypesAndGetParentAndChild;
15964     function skipParentheses(node) {
15965         return ts.skipOuterExpressions(node, 1 /* Parentheses */);
15966     }
15967     ts.skipParentheses = skipParentheses;
15968     function skipParenthesesUp(node) {
15969         while (node.kind === 207 /* ParenthesizedExpression */) {
15970             node = node.parent;
15971         }
15972         return node;
15973     }
15974     // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
15975     function isDeleteTarget(node) {
15976         if (node.kind !== 201 /* PropertyAccessExpression */ && node.kind !== 202 /* ElementAccessExpression */) {
15977             return false;
15978         }
15979         node = walkUpParenthesizedExpressions(node.parent);
15980         return node && node.kind === 210 /* DeleteExpression */;
15981     }
15982     ts.isDeleteTarget = isDeleteTarget;
15983     function isNodeDescendantOf(node, ancestor) {
15984         while (node) {
15985             if (node === ancestor)
15986                 return true;
15987             node = node.parent;
15988         }
15989         return false;
15990     }
15991     ts.isNodeDescendantOf = isNodeDescendantOf;
15992     // True if `name` is the name of a declaration node
15993     function isDeclarationName(name) {
15994         return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
15995     }
15996     ts.isDeclarationName = isDeclarationName;
15997     // See GH#16030
15998     function getDeclarationFromName(name) {
15999         var parent = name.parent;
16000         switch (name.kind) {
16001             case 10 /* StringLiteral */:
16002             case 14 /* NoSubstitutionTemplateLiteral */:
16003             case 8 /* NumericLiteral */:
16004                 if (ts.isComputedPropertyName(parent))
16005                     return parent.parent;
16006             // falls through
16007             case 78 /* Identifier */:
16008                 if (ts.isDeclaration(parent)) {
16009                     return parent.name === name ? parent : undefined;
16010                 }
16011                 else if (ts.isQualifiedName(parent)) {
16012                     var tag = parent.parent;
16013                     return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
16014                 }
16015                 else {
16016                     var binExp = parent.parent;
16017                     return ts.isBinaryExpression(binExp) &&
16018                         getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
16019                         (binExp.left.symbol || binExp.symbol) &&
16020                         ts.getNameOfDeclaration(binExp) === name
16021                         ? binExp
16022                         : undefined;
16023                 }
16024             case 79 /* PrivateIdentifier */:
16025                 return ts.isDeclaration(parent) && parent.name === name ? parent : undefined;
16026             default:
16027                 return undefined;
16028         }
16029     }
16030     ts.getDeclarationFromName = getDeclarationFromName;
16031     function isLiteralComputedPropertyDeclarationName(node) {
16032         return isStringOrNumericLiteralLike(node) &&
16033             node.parent.kind === 158 /* ComputedPropertyName */ &&
16034             ts.isDeclaration(node.parent.parent);
16035     }
16036     ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
16037     // Return true if the given identifier is classified as an IdentifierName
16038     function isIdentifierName(node) {
16039         var parent = node.parent;
16040         switch (parent.kind) {
16041             case 163 /* PropertyDeclaration */:
16042             case 162 /* PropertySignature */:
16043             case 165 /* MethodDeclaration */:
16044             case 164 /* MethodSignature */:
16045             case 167 /* GetAccessor */:
16046             case 168 /* SetAccessor */:
16047             case 291 /* EnumMember */:
16048             case 288 /* PropertyAssignment */:
16049             case 201 /* PropertyAccessExpression */:
16050                 // Name in member declaration or property name in property access
16051                 return parent.name === node;
16052             case 157 /* QualifiedName */:
16053                 // Name on right hand side of dot in a type query or type reference
16054                 return parent.right === node;
16055             case 198 /* BindingElement */:
16056             case 265 /* ImportSpecifier */:
16057                 // Property name in binding element or import specifier
16058                 return parent.propertyName === node;
16059             case 270 /* ExportSpecifier */:
16060             case 280 /* JsxAttribute */:
16061                 // Any name in an export specifier or JSX Attribute
16062                 return true;
16063         }
16064         return false;
16065     }
16066     ts.isIdentifierName = isIdentifierName;
16067     // An alias symbol is created by one of the following declarations:
16068     // import <symbol> = ...
16069     // import <symbol> from ...
16070     // import * as <symbol> from ...
16071     // import { x as <symbol> } from ...
16072     // export { x as <symbol> } from ...
16073     // export * as ns <symbol> from ...
16074     // export = <EntityNameExpression>
16075     // export default <EntityNameExpression>
16076     // module.exports = <EntityNameExpression>
16077     // {<Identifier>}
16078     // {name: <EntityNameExpression>}
16079     function isAliasSymbolDeclaration(node) {
16080         return node.kind === 260 /* ImportEqualsDeclaration */ ||
16081             node.kind === 259 /* NamespaceExportDeclaration */ ||
16082             node.kind === 262 /* ImportClause */ && !!node.name ||
16083             node.kind === 263 /* NamespaceImport */ ||
16084             node.kind === 269 /* NamespaceExport */ ||
16085             node.kind === 265 /* ImportSpecifier */ ||
16086             node.kind === 270 /* ExportSpecifier */ ||
16087             node.kind === 266 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
16088             ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) ||
16089             ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) ||
16090             node.kind === 289 /* ShorthandPropertyAssignment */ ||
16091             node.kind === 288 /* PropertyAssignment */ && isAliasableExpression(node.initializer);
16092     }
16093     ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
16094     function getAliasDeclarationFromName(node) {
16095         switch (node.parent.kind) {
16096             case 262 /* ImportClause */:
16097             case 265 /* ImportSpecifier */:
16098             case 263 /* NamespaceImport */:
16099             case 270 /* ExportSpecifier */:
16100             case 266 /* ExportAssignment */:
16101             case 260 /* ImportEqualsDeclaration */:
16102                 return node.parent;
16103             case 157 /* QualifiedName */:
16104                 do {
16105                     node = node.parent;
16106                 } while (node.parent.kind === 157 /* QualifiedName */);
16107                 return getAliasDeclarationFromName(node);
16108         }
16109     }
16110     ts.getAliasDeclarationFromName = getAliasDeclarationFromName;
16111     function isAliasableExpression(e) {
16112         return isEntityNameExpression(e) || ts.isClassExpression(e);
16113     }
16114     ts.isAliasableExpression = isAliasableExpression;
16115     function exportAssignmentIsAlias(node) {
16116         var e = getExportAssignmentExpression(node);
16117         return isAliasableExpression(e);
16118     }
16119     ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
16120     function getExportAssignmentExpression(node) {
16121         return ts.isExportAssignment(node) ? node.expression : node.right;
16122     }
16123     ts.getExportAssignmentExpression = getExportAssignmentExpression;
16124     function getPropertyAssignmentAliasLikeExpression(node) {
16125         return node.kind === 289 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 288 /* PropertyAssignment */ ? node.initializer :
16126             node.parent.right;
16127     }
16128     ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression;
16129     function getEffectiveBaseTypeNode(node) {
16130         var baseType = getClassExtendsHeritageElement(node);
16131         if (baseType && isInJSFile(node)) {
16132             // Prefer an @augments tag because it may have type parameters.
16133             var tag = ts.getJSDocAugmentsTag(node);
16134             if (tag) {
16135                 return tag.class;
16136             }
16137         }
16138         return baseType;
16139     }
16140     ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
16141     function getClassExtendsHeritageElement(node) {
16142         var heritageClause = getHeritageClause(node.heritageClauses, 93 /* ExtendsKeyword */);
16143         return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
16144     }
16145     ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
16146     function getEffectiveImplementsTypeNodes(node) {
16147         if (isInJSFile(node)) {
16148             return ts.getJSDocImplementsTags(node).map(function (n) { return n.class; });
16149         }
16150         else {
16151             var heritageClause = getHeritageClause(node.heritageClauses, 116 /* ImplementsKeyword */);
16152             return heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.types;
16153         }
16154     }
16155     ts.getEffectiveImplementsTypeNodes = getEffectiveImplementsTypeNodes;
16156     /** Returns the node in an `extends` or `implements` clause of a class or interface. */
16157     function getAllSuperTypeNodes(node) {
16158         return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray :
16159             ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getEffectiveImplementsTypeNodes(node)) || ts.emptyArray :
16160                 ts.emptyArray;
16161     }
16162     ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
16163     function getInterfaceBaseTypeNodes(node) {
16164         var heritageClause = getHeritageClause(node.heritageClauses, 93 /* ExtendsKeyword */);
16165         return heritageClause ? heritageClause.types : undefined;
16166     }
16167     ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
16168     function getHeritageClause(clauses, kind) {
16169         if (clauses) {
16170             for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
16171                 var clause = clauses_1[_i];
16172                 if (clause.token === kind) {
16173                     return clause;
16174                 }
16175             }
16176         }
16177         return undefined;
16178     }
16179     ts.getHeritageClause = getHeritageClause;
16180     function getAncestor(node, kind) {
16181         while (node) {
16182             if (node.kind === kind) {
16183                 return node;
16184             }
16185             node = node.parent;
16186         }
16187         return undefined;
16188     }
16189     ts.getAncestor = getAncestor;
16190     function isKeyword(token) {
16191         return 80 /* FirstKeyword */ <= token && token <= 156 /* LastKeyword */;
16192     }
16193     ts.isKeyword = isKeyword;
16194     function isContextualKeyword(token) {
16195         return 125 /* FirstContextualKeyword */ <= token && token <= 156 /* LastContextualKeyword */;
16196     }
16197     ts.isContextualKeyword = isContextualKeyword;
16198     function isNonContextualKeyword(token) {
16199         return isKeyword(token) && !isContextualKeyword(token);
16200     }
16201     ts.isNonContextualKeyword = isNonContextualKeyword;
16202     function isFutureReservedKeyword(token) {
16203         return 116 /* FirstFutureReservedWord */ <= token && token <= 124 /* LastFutureReservedWord */;
16204     }
16205     ts.isFutureReservedKeyword = isFutureReservedKeyword;
16206     function isStringANonContextualKeyword(name) {
16207         var token = ts.stringToToken(name);
16208         return token !== undefined && isNonContextualKeyword(token);
16209     }
16210     ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
16211     function isStringAKeyword(name) {
16212         var token = ts.stringToToken(name);
16213         return token !== undefined && isKeyword(token);
16214     }
16215     ts.isStringAKeyword = isStringAKeyword;
16216     function isIdentifierANonContextualKeyword(_a) {
16217         var originalKeywordKind = _a.originalKeywordKind;
16218         return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind);
16219     }
16220     ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword;
16221     function isTrivia(token) {
16222         return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
16223     }
16224     ts.isTrivia = isTrivia;
16225     var FunctionFlags;
16226     (function (FunctionFlags) {
16227         FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
16228         FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
16229         FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
16230         FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
16231         FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
16232     })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
16233     function getFunctionFlags(node) {
16234         if (!node) {
16235             return 4 /* Invalid */;
16236         }
16237         var flags = 0 /* Normal */;
16238         switch (node.kind) {
16239             case 251 /* FunctionDeclaration */:
16240             case 208 /* FunctionExpression */:
16241             case 165 /* MethodDeclaration */:
16242                 if (node.asteriskToken) {
16243                     flags |= 1 /* Generator */;
16244                 }
16245             // falls through
16246             case 209 /* ArrowFunction */:
16247                 if (hasSyntacticModifier(node, 256 /* Async */)) {
16248                     flags |= 2 /* Async */;
16249                 }
16250                 break;
16251         }
16252         if (!node.body) {
16253             flags |= 4 /* Invalid */;
16254         }
16255         return flags;
16256     }
16257     ts.getFunctionFlags = getFunctionFlags;
16258     function isAsyncFunction(node) {
16259         switch (node.kind) {
16260             case 251 /* FunctionDeclaration */:
16261             case 208 /* FunctionExpression */:
16262             case 209 /* ArrowFunction */:
16263             case 165 /* MethodDeclaration */:
16264                 return node.body !== undefined
16265                     && node.asteriskToken === undefined
16266                     && hasSyntacticModifier(node, 256 /* Async */);
16267         }
16268         return false;
16269     }
16270     ts.isAsyncFunction = isAsyncFunction;
16271     function isStringOrNumericLiteralLike(node) {
16272         return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
16273     }
16274     ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
16275     function isSignedNumericLiteral(node) {
16276         return ts.isPrefixUnaryExpression(node) && (node.operator === 39 /* PlusToken */ || node.operator === 40 /* MinusToken */) && ts.isNumericLiteral(node.operand);
16277     }
16278     ts.isSignedNumericLiteral = isSignedNumericLiteral;
16279     /**
16280      * A declaration has a dynamic name if all of the following are true:
16281      *   1. The declaration has a computed property name.
16282      *   2. The computed name is *not* expressed as a StringLiteral.
16283      *   3. The computed name is *not* expressed as a NumericLiteral.
16284      *   4. The computed name is *not* expressed as a PlusToken or MinusToken
16285      *      immediately followed by a NumericLiteral.
16286      *   5. The computed name is *not* expressed as `Symbol.<name>`, where `<name>`
16287      *      is a property of the Symbol constructor that denotes a built-in
16288      *      Symbol.
16289      */
16290     function hasDynamicName(declaration) {
16291         var name = ts.getNameOfDeclaration(declaration);
16292         return !!name && isDynamicName(name);
16293     }
16294     ts.hasDynamicName = hasDynamicName;
16295     function isDynamicName(name) {
16296         if (!(name.kind === 158 /* ComputedPropertyName */ || name.kind === 202 /* ElementAccessExpression */)) {
16297             return false;
16298         }
16299         var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression;
16300         return !isStringOrNumericLiteralLike(expr) &&
16301             !isSignedNumericLiteral(expr) &&
16302             !isWellKnownSymbolSyntactically(expr);
16303     }
16304     ts.isDynamicName = isDynamicName;
16305     /**
16306      * Checks if the expression is of the form:
16307      *    Symbol.name
16308      * where Symbol is literally the word "Symbol", and name is any identifierName
16309      */
16310     function isWellKnownSymbolSyntactically(node) {
16311         return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
16312     }
16313     ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically;
16314     function getPropertyNameForPropertyNameNode(name) {
16315         switch (name.kind) {
16316             case 78 /* Identifier */:
16317             case 79 /* PrivateIdentifier */:
16318                 return name.escapedText;
16319             case 10 /* StringLiteral */:
16320             case 8 /* NumericLiteral */:
16321                 return ts.escapeLeadingUnderscores(name.text);
16322             case 158 /* ComputedPropertyName */:
16323                 var nameExpression = name.expression;
16324                 if (isWellKnownSymbolSyntactically(nameExpression)) {
16325                     return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
16326                 }
16327                 else if (isStringOrNumericLiteralLike(nameExpression)) {
16328                     return ts.escapeLeadingUnderscores(nameExpression.text);
16329                 }
16330                 else if (isSignedNumericLiteral(nameExpression)) {
16331                     if (nameExpression.operator === 40 /* MinusToken */) {
16332                         return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
16333                     }
16334                     return nameExpression.operand.text;
16335                 }
16336                 return undefined;
16337             default:
16338                 return ts.Debug.assertNever(name);
16339         }
16340     }
16341     ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
16342     function isPropertyNameLiteral(node) {
16343         switch (node.kind) {
16344             case 78 /* Identifier */:
16345             case 10 /* StringLiteral */:
16346             case 14 /* NoSubstitutionTemplateLiteral */:
16347             case 8 /* NumericLiteral */:
16348                 return true;
16349             default:
16350                 return false;
16351         }
16352     }
16353     ts.isPropertyNameLiteral = isPropertyNameLiteral;
16354     function getTextOfIdentifierOrLiteral(node) {
16355         return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text;
16356     }
16357     ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
16358     function getEscapedTextOfIdentifierOrLiteral(node) {
16359         return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
16360     }
16361     ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
16362     function getPropertyNameForUniqueESSymbol(symbol) {
16363         return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName;
16364     }
16365     ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol;
16366     function getPropertyNameForKnownSymbolName(symbolName) {
16367         return "__@" + symbolName;
16368     }
16369     ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName;
16370     function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) {
16371         return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description;
16372     }
16373     ts.getSymbolNameForPrivateIdentifier = getSymbolNameForPrivateIdentifier;
16374     function isKnownSymbol(symbol) {
16375         return ts.startsWith(symbol.escapedName, "__@");
16376     }
16377     ts.isKnownSymbol = isKnownSymbol;
16378     /**
16379      * Includes the word "Symbol" with unicode escapes
16380      */
16381     function isESSymbolIdentifier(node) {
16382         return node.kind === 78 /* Identifier */ && node.escapedText === "Symbol";
16383     }
16384     ts.isESSymbolIdentifier = isESSymbolIdentifier;
16385     function isPushOrUnshiftIdentifier(node) {
16386         return node.escapedText === "push" || node.escapedText === "unshift";
16387     }
16388     ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
16389     function isParameterDeclaration(node) {
16390         var root = getRootDeclaration(node);
16391         return root.kind === 160 /* Parameter */;
16392     }
16393     ts.isParameterDeclaration = isParameterDeclaration;
16394     function getRootDeclaration(node) {
16395         while (node.kind === 198 /* BindingElement */) {
16396             node = node.parent.parent;
16397         }
16398         return node;
16399     }
16400     ts.getRootDeclaration = getRootDeclaration;
16401     function nodeStartsNewLexicalEnvironment(node) {
16402         var kind = node.kind;
16403         return kind === 166 /* Constructor */
16404             || kind === 208 /* FunctionExpression */
16405             || kind === 251 /* FunctionDeclaration */
16406             || kind === 209 /* ArrowFunction */
16407             || kind === 165 /* MethodDeclaration */
16408             || kind === 167 /* GetAccessor */
16409             || kind === 168 /* SetAccessor */
16410             || kind === 256 /* ModuleDeclaration */
16411             || kind === 297 /* SourceFile */;
16412     }
16413     ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
16414     function nodeIsSynthesized(range) {
16415         return positionIsSynthesized(range.pos)
16416             || positionIsSynthesized(range.end);
16417     }
16418     ts.nodeIsSynthesized = nodeIsSynthesized;
16419     function getOriginalSourceFile(sourceFile) {
16420         return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
16421     }
16422     ts.getOriginalSourceFile = getOriginalSourceFile;
16423     var Associativity;
16424     (function (Associativity) {
16425         Associativity[Associativity["Left"] = 0] = "Left";
16426         Associativity[Associativity["Right"] = 1] = "Right";
16427     })(Associativity = ts.Associativity || (ts.Associativity = {}));
16428     function getExpressionAssociativity(expression) {
16429         var operator = getOperator(expression);
16430         var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined;
16431         return getOperatorAssociativity(expression.kind, operator, hasArguments);
16432     }
16433     ts.getExpressionAssociativity = getExpressionAssociativity;
16434     function getOperatorAssociativity(kind, operator, hasArguments) {
16435         switch (kind) {
16436             case 204 /* NewExpression */:
16437                 return hasArguments ? 0 /* Left */ : 1 /* Right */;
16438             case 214 /* PrefixUnaryExpression */:
16439             case 211 /* TypeOfExpression */:
16440             case 212 /* VoidExpression */:
16441             case 210 /* DeleteExpression */:
16442             case 213 /* AwaitExpression */:
16443             case 217 /* ConditionalExpression */:
16444             case 219 /* YieldExpression */:
16445                 return 1 /* Right */;
16446             case 216 /* BinaryExpression */:
16447                 switch (operator) {
16448                     case 42 /* AsteriskAsteriskToken */:
16449                     case 62 /* EqualsToken */:
16450                     case 63 /* PlusEqualsToken */:
16451                     case 64 /* MinusEqualsToken */:
16452                     case 66 /* AsteriskAsteriskEqualsToken */:
16453                     case 65 /* AsteriskEqualsToken */:
16454                     case 67 /* SlashEqualsToken */:
16455                     case 68 /* PercentEqualsToken */:
16456                     case 69 /* LessThanLessThanEqualsToken */:
16457                     case 70 /* GreaterThanGreaterThanEqualsToken */:
16458                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
16459                     case 72 /* AmpersandEqualsToken */:
16460                     case 77 /* CaretEqualsToken */:
16461                     case 73 /* BarEqualsToken */:
16462                     case 74 /* BarBarEqualsToken */:
16463                     case 75 /* AmpersandAmpersandEqualsToken */:
16464                     case 76 /* QuestionQuestionEqualsToken */:
16465                         return 1 /* Right */;
16466                 }
16467         }
16468         return 0 /* Left */;
16469     }
16470     ts.getOperatorAssociativity = getOperatorAssociativity;
16471     function getExpressionPrecedence(expression) {
16472         var operator = getOperator(expression);
16473         var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined;
16474         return getOperatorPrecedence(expression.kind, operator, hasArguments);
16475     }
16476     ts.getExpressionPrecedence = getExpressionPrecedence;
16477     function getOperator(expression) {
16478         if (expression.kind === 216 /* BinaryExpression */) {
16479             return expression.operatorToken.kind;
16480         }
16481         else if (expression.kind === 214 /* PrefixUnaryExpression */ || expression.kind === 215 /* PostfixUnaryExpression */) {
16482             return expression.operator;
16483         }
16484         else {
16485             return expression.kind;
16486         }
16487     }
16488     ts.getOperator = getOperator;
16489     var OperatorPrecedence;
16490     (function (OperatorPrecedence) {
16491         // Expression:
16492         //     AssignmentExpression
16493         //     Expression `,` AssignmentExpression
16494         OperatorPrecedence[OperatorPrecedence["Comma"] = 0] = "Comma";
16495         // NOTE: `Spread` is higher than `Comma` due to how it is parsed in |ElementList|
16496         // SpreadElement:
16497         //     `...` AssignmentExpression
16498         OperatorPrecedence[OperatorPrecedence["Spread"] = 1] = "Spread";
16499         // AssignmentExpression:
16500         //     ConditionalExpression
16501         //     YieldExpression
16502         //     ArrowFunction
16503         //     AsyncArrowFunction
16504         //     LeftHandSideExpression `=` AssignmentExpression
16505         //     LeftHandSideExpression AssignmentOperator AssignmentExpression
16506         //
16507         // NOTE: AssignmentExpression is broken down into several precedences due to the requirements
16508         //       of the parenthesizer rules.
16509         // AssignmentExpression: YieldExpression
16510         // YieldExpression:
16511         //     `yield`
16512         //     `yield` AssignmentExpression
16513         //     `yield` `*` AssignmentExpression
16514         OperatorPrecedence[OperatorPrecedence["Yield"] = 2] = "Yield";
16515         // AssignmentExpression: LeftHandSideExpression `=` AssignmentExpression
16516         // AssignmentExpression: LeftHandSideExpression AssignmentOperator AssignmentExpression
16517         // AssignmentOperator: one of
16518         //     `*=` `/=` `%=` `+=` `-=` `<<=` `>>=` `>>>=` `&=` `^=` `|=` `**=`
16519         OperatorPrecedence[OperatorPrecedence["Assignment"] = 3] = "Assignment";
16520         // NOTE: `Conditional` is considered higher than `Assignment` here, but in reality they have
16521         //       the same precedence.
16522         // AssignmentExpression: ConditionalExpression
16523         // ConditionalExpression:
16524         //     ShortCircuitExpression
16525         //     ShortCircuitExpression `?` AssignmentExpression `:` AssignmentExpression
16526         // ShortCircuitExpression:
16527         //     LogicalORExpression
16528         //     CoalesceExpression
16529         OperatorPrecedence[OperatorPrecedence["Conditional"] = 4] = "Conditional";
16530         // CoalesceExpression:
16531         //     CoalesceExpressionHead `??` BitwiseORExpression
16532         // CoalesceExpressionHead:
16533         //     CoalesceExpression
16534         //     BitwiseORExpression
16535         OperatorPrecedence[OperatorPrecedence["Coalesce"] = 4] = "Coalesce";
16536         // LogicalORExpression:
16537         //     LogicalANDExpression
16538         //     LogicalORExpression `||` LogicalANDExpression
16539         OperatorPrecedence[OperatorPrecedence["LogicalOR"] = 5] = "LogicalOR";
16540         // LogicalANDExpression:
16541         //     BitwiseORExpression
16542         //     LogicalANDExprerssion `&&` BitwiseORExpression
16543         OperatorPrecedence[OperatorPrecedence["LogicalAND"] = 6] = "LogicalAND";
16544         // BitwiseORExpression:
16545         //     BitwiseXORExpression
16546         //     BitwiseORExpression `^` BitwiseXORExpression
16547         OperatorPrecedence[OperatorPrecedence["BitwiseOR"] = 7] = "BitwiseOR";
16548         // BitwiseXORExpression:
16549         //     BitwiseANDExpression
16550         //     BitwiseXORExpression `^` BitwiseANDExpression
16551         OperatorPrecedence[OperatorPrecedence["BitwiseXOR"] = 8] = "BitwiseXOR";
16552         // BitwiseANDExpression:
16553         //     EqualityExpression
16554         //     BitwiseANDExpression `^` EqualityExpression
16555         OperatorPrecedence[OperatorPrecedence["BitwiseAND"] = 9] = "BitwiseAND";
16556         // EqualityExpression:
16557         //     RelationalExpression
16558         //     EqualityExpression `==` RelationalExpression
16559         //     EqualityExpression `!=` RelationalExpression
16560         //     EqualityExpression `===` RelationalExpression
16561         //     EqualityExpression `!==` RelationalExpression
16562         OperatorPrecedence[OperatorPrecedence["Equality"] = 10] = "Equality";
16563         // RelationalExpression:
16564         //     ShiftExpression
16565         //     RelationalExpression `<` ShiftExpression
16566         //     RelationalExpression `>` ShiftExpression
16567         //     RelationalExpression `<=` ShiftExpression
16568         //     RelationalExpression `>=` ShiftExpression
16569         //     RelationalExpression `instanceof` ShiftExpression
16570         //     RelationalExpression `in` ShiftExpression
16571         //     [+TypeScript] RelationalExpression `as` Type
16572         OperatorPrecedence[OperatorPrecedence["Relational"] = 11] = "Relational";
16573         // ShiftExpression:
16574         //     AdditiveExpression
16575         //     ShiftExpression `<<` AdditiveExpression
16576         //     ShiftExpression `>>` AdditiveExpression
16577         //     ShiftExpression `>>>` AdditiveExpression
16578         OperatorPrecedence[OperatorPrecedence["Shift"] = 12] = "Shift";
16579         // AdditiveExpression:
16580         //     MultiplicativeExpression
16581         //     AdditiveExpression `+` MultiplicativeExpression
16582         //     AdditiveExpression `-` MultiplicativeExpression
16583         OperatorPrecedence[OperatorPrecedence["Additive"] = 13] = "Additive";
16584         // MultiplicativeExpression:
16585         //     ExponentiationExpression
16586         //     MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
16587         // MultiplicativeOperator: one of `*`, `/`, `%`
16588         OperatorPrecedence[OperatorPrecedence["Multiplicative"] = 14] = "Multiplicative";
16589         // ExponentiationExpression:
16590         //     UnaryExpression
16591         //     UpdateExpression `**` ExponentiationExpression
16592         OperatorPrecedence[OperatorPrecedence["Exponentiation"] = 15] = "Exponentiation";
16593         // UnaryExpression:
16594         //     UpdateExpression
16595         //     `delete` UnaryExpression
16596         //     `void` UnaryExpression
16597         //     `typeof` UnaryExpression
16598         //     `+` UnaryExpression
16599         //     `-` UnaryExpression
16600         //     `~` UnaryExpression
16601         //     `!` UnaryExpression
16602         //     AwaitExpression
16603         // UpdateExpression:            // TODO: Do we need to investigate the precedence here?
16604         //     `++` UnaryExpression
16605         //     `--` UnaryExpression
16606         OperatorPrecedence[OperatorPrecedence["Unary"] = 16] = "Unary";
16607         // UpdateExpression:
16608         //     LeftHandSideExpression
16609         //     LeftHandSideExpression `++`
16610         //     LeftHandSideExpression `--`
16611         OperatorPrecedence[OperatorPrecedence["Update"] = 17] = "Update";
16612         // LeftHandSideExpression:
16613         //     NewExpression
16614         //     CallExpression
16615         // NewExpression:
16616         //     MemberExpression
16617         //     `new` NewExpression
16618         OperatorPrecedence[OperatorPrecedence["LeftHandSide"] = 18] = "LeftHandSide";
16619         // CallExpression:
16620         //     CoverCallExpressionAndAsyncArrowHead
16621         //     SuperCall
16622         //     ImportCall
16623         //     CallExpression Arguments
16624         //     CallExpression `[` Expression `]`
16625         //     CallExpression `.` IdentifierName
16626         //     CallExpression TemplateLiteral
16627         // MemberExpression:
16628         //     PrimaryExpression
16629         //     MemberExpression `[` Expression `]`
16630         //     MemberExpression `.` IdentifierName
16631         //     MemberExpression TemplateLiteral
16632         //     SuperProperty
16633         //     MetaProperty
16634         //     `new` MemberExpression Arguments
16635         OperatorPrecedence[OperatorPrecedence["Member"] = 19] = "Member";
16636         // TODO: JSXElement?
16637         // PrimaryExpression:
16638         //     `this`
16639         //     IdentifierReference
16640         //     Literal
16641         //     ArrayLiteral
16642         //     ObjectLiteral
16643         //     FunctionExpression
16644         //     ClassExpression
16645         //     GeneratorExpression
16646         //     AsyncFunctionExpression
16647         //     AsyncGeneratorExpression
16648         //     RegularExpressionLiteral
16649         //     TemplateLiteral
16650         //     CoverParenthesizedExpressionAndArrowParameterList
16651         OperatorPrecedence[OperatorPrecedence["Primary"] = 20] = "Primary";
16652         OperatorPrecedence[OperatorPrecedence["Highest"] = 20] = "Highest";
16653         OperatorPrecedence[OperatorPrecedence["Lowest"] = 0] = "Lowest";
16654         // -1 is lower than all other precedences. Returning it will cause binary expression
16655         // parsing to stop.
16656         OperatorPrecedence[OperatorPrecedence["Invalid"] = -1] = "Invalid";
16657     })(OperatorPrecedence = ts.OperatorPrecedence || (ts.OperatorPrecedence = {}));
16658     function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
16659         switch (nodeKind) {
16660             case 337 /* CommaListExpression */:
16661                 return 0 /* Comma */;
16662             case 220 /* SpreadElement */:
16663                 return 1 /* Spread */;
16664             case 219 /* YieldExpression */:
16665                 return 2 /* Yield */;
16666             case 217 /* ConditionalExpression */:
16667                 return 4 /* Conditional */;
16668             case 216 /* BinaryExpression */:
16669                 switch (operatorKind) {
16670                     case 27 /* CommaToken */:
16671                         return 0 /* Comma */;
16672                     case 62 /* EqualsToken */:
16673                     case 63 /* PlusEqualsToken */:
16674                     case 64 /* MinusEqualsToken */:
16675                     case 66 /* AsteriskAsteriskEqualsToken */:
16676                     case 65 /* AsteriskEqualsToken */:
16677                     case 67 /* SlashEqualsToken */:
16678                     case 68 /* PercentEqualsToken */:
16679                     case 69 /* LessThanLessThanEqualsToken */:
16680                     case 70 /* GreaterThanGreaterThanEqualsToken */:
16681                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
16682                     case 72 /* AmpersandEqualsToken */:
16683                     case 77 /* CaretEqualsToken */:
16684                     case 73 /* BarEqualsToken */:
16685                     case 74 /* BarBarEqualsToken */:
16686                     case 75 /* AmpersandAmpersandEqualsToken */:
16687                     case 76 /* QuestionQuestionEqualsToken */:
16688                         return 3 /* Assignment */;
16689                     default:
16690                         return getBinaryOperatorPrecedence(operatorKind);
16691                 }
16692             // TODO: Should prefix `++` and `--` be moved to the `Update` precedence?
16693             case 206 /* TypeAssertionExpression */:
16694             case 225 /* NonNullExpression */:
16695             case 214 /* PrefixUnaryExpression */:
16696             case 211 /* TypeOfExpression */:
16697             case 212 /* VoidExpression */:
16698             case 210 /* DeleteExpression */:
16699             case 213 /* AwaitExpression */:
16700                 return 16 /* Unary */;
16701             case 215 /* PostfixUnaryExpression */:
16702                 return 17 /* Update */;
16703             case 203 /* CallExpression */:
16704                 return 18 /* LeftHandSide */;
16705             case 204 /* NewExpression */:
16706                 return hasArguments ? 19 /* Member */ : 18 /* LeftHandSide */;
16707             case 205 /* TaggedTemplateExpression */:
16708             case 201 /* PropertyAccessExpression */:
16709             case 202 /* ElementAccessExpression */:
16710                 return 19 /* Member */;
16711             case 224 /* AsExpression */:
16712                 return 11 /* Relational */;
16713             case 107 /* ThisKeyword */:
16714             case 105 /* SuperKeyword */:
16715             case 78 /* Identifier */:
16716             case 103 /* NullKeyword */:
16717             case 109 /* TrueKeyword */:
16718             case 94 /* FalseKeyword */:
16719             case 8 /* NumericLiteral */:
16720             case 9 /* BigIntLiteral */:
16721             case 10 /* StringLiteral */:
16722             case 199 /* ArrayLiteralExpression */:
16723             case 200 /* ObjectLiteralExpression */:
16724             case 208 /* FunctionExpression */:
16725             case 209 /* ArrowFunction */:
16726             case 221 /* ClassExpression */:
16727             case 13 /* RegularExpressionLiteral */:
16728             case 14 /* NoSubstitutionTemplateLiteral */:
16729             case 218 /* TemplateExpression */:
16730             case 207 /* ParenthesizedExpression */:
16731             case 222 /* OmittedExpression */:
16732             case 273 /* JsxElement */:
16733             case 274 /* JsxSelfClosingElement */:
16734             case 277 /* JsxFragment */:
16735                 return 20 /* Primary */;
16736             default:
16737                 return -1 /* Invalid */;
16738         }
16739     }
16740     ts.getOperatorPrecedence = getOperatorPrecedence;
16741     function getBinaryOperatorPrecedence(kind) {
16742         switch (kind) {
16743             case 60 /* QuestionQuestionToken */:
16744                 return 4 /* Coalesce */;
16745             case 56 /* BarBarToken */:
16746                 return 5 /* LogicalOR */;
16747             case 55 /* AmpersandAmpersandToken */:
16748                 return 6 /* LogicalAND */;
16749             case 51 /* BarToken */:
16750                 return 7 /* BitwiseOR */;
16751             case 52 /* CaretToken */:
16752                 return 8 /* BitwiseXOR */;
16753             case 50 /* AmpersandToken */:
16754                 return 9 /* BitwiseAND */;
16755             case 34 /* EqualsEqualsToken */:
16756             case 35 /* ExclamationEqualsToken */:
16757             case 36 /* EqualsEqualsEqualsToken */:
16758             case 37 /* ExclamationEqualsEqualsToken */:
16759                 return 10 /* Equality */;
16760             case 29 /* LessThanToken */:
16761             case 31 /* GreaterThanToken */:
16762             case 32 /* LessThanEqualsToken */:
16763             case 33 /* GreaterThanEqualsToken */:
16764             case 101 /* InstanceOfKeyword */:
16765             case 100 /* InKeyword */:
16766             case 126 /* AsKeyword */:
16767                 return 11 /* Relational */;
16768             case 47 /* LessThanLessThanToken */:
16769             case 48 /* GreaterThanGreaterThanToken */:
16770             case 49 /* GreaterThanGreaterThanGreaterThanToken */:
16771                 return 12 /* Shift */;
16772             case 39 /* PlusToken */:
16773             case 40 /* MinusToken */:
16774                 return 13 /* Additive */;
16775             case 41 /* AsteriskToken */:
16776             case 43 /* SlashToken */:
16777             case 44 /* PercentToken */:
16778                 return 14 /* Multiplicative */;
16779             case 42 /* AsteriskAsteriskToken */:
16780                 return 15 /* Exponentiation */;
16781         }
16782         // -1 is lower than all other precedences.  Returning it will cause binary expression
16783         // parsing to stop.
16784         return -1;
16785     }
16786     ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
16787     function getSemanticJsxChildren(children) {
16788         return ts.filter(children, function (i) {
16789             switch (i.kind) {
16790                 case 283 /* JsxExpression */:
16791                     return !!i.expression;
16792                 case 11 /* JsxText */:
16793                     return !i.containsOnlyTriviaWhiteSpaces;
16794                 default:
16795                     return true;
16796             }
16797         });
16798     }
16799     ts.getSemanticJsxChildren = getSemanticJsxChildren;
16800     function createDiagnosticCollection() {
16801         var nonFileDiagnostics = []; // See GH#19873
16802         var filesWithDiagnostics = [];
16803         var fileDiagnostics = new ts.Map();
16804         var hasReadNonFileDiagnostics = false;
16805         return {
16806             add: add,
16807             lookup: lookup,
16808             getGlobalDiagnostics: getGlobalDiagnostics,
16809             getDiagnostics: getDiagnostics,
16810         };
16811         function lookup(diagnostic) {
16812             var diagnostics;
16813             if (diagnostic.file) {
16814                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
16815             }
16816             else {
16817                 diagnostics = nonFileDiagnostics;
16818             }
16819             if (!diagnostics) {
16820                 return undefined;
16821             }
16822             var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, compareDiagnosticsSkipRelatedInformation);
16823             if (result >= 0) {
16824                 return diagnostics[result];
16825             }
16826             return undefined;
16827         }
16828         function add(diagnostic) {
16829             var diagnostics;
16830             if (diagnostic.file) {
16831                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
16832                 if (!diagnostics) {
16833                     diagnostics = []; // See GH#19873
16834                     fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
16835                     ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive);
16836                 }
16837             }
16838             else {
16839                 // If we've already read the non-file diagnostics, do not modify the existing array.
16840                 if (hasReadNonFileDiagnostics) {
16841                     hasReadNonFileDiagnostics = false;
16842                     nonFileDiagnostics = nonFileDiagnostics.slice();
16843                 }
16844                 diagnostics = nonFileDiagnostics;
16845             }
16846             ts.insertSorted(diagnostics, diagnostic, compareDiagnostics);
16847         }
16848         function getGlobalDiagnostics() {
16849             hasReadNonFileDiagnostics = true;
16850             return nonFileDiagnostics;
16851         }
16852         function getDiagnostics(fileName) {
16853             if (fileName) {
16854                 return fileDiagnostics.get(fileName) || [];
16855             }
16856             var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
16857             if (!nonFileDiagnostics.length) {
16858                 return fileDiags;
16859             }
16860             fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
16861             return fileDiags;
16862         }
16863     }
16864     ts.createDiagnosticCollection = createDiagnosticCollection;
16865     var templateSubstitutionRegExp = /\$\{/g;
16866     function escapeTemplateSubstitution(str) {
16867         return str.replace(templateSubstitutionRegExp, "\\${");
16868     }
16869     /** @internal */
16870     function hasInvalidEscape(template) {
16871         return template && !!(ts.isNoSubstitutionTemplateLiteral(template)
16872             ? template.templateFlags
16873             : (template.head.templateFlags || ts.some(template.templateSpans, function (span) { return !!span.literal.templateFlags; })));
16874     }
16875     ts.hasInvalidEscape = hasInvalidEscape;
16876     // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
16877     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16878     // the language service. These characters should be escaped when printing, and if any characters are added,
16879     // the map below must be updated. Note that this regexp *does not* include the 'delete' character.
16880     // There is no reason for this other than that JSON.stringify does not handle it either.
16881     var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16882     var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16883     // Template strings should be preserved as much as possible
16884     var backtickQuoteEscapedCharsRegExp = /[\\`]/g;
16885     var escapedCharsMap = new ts.Map(ts.getEntries({
16886         "\t": "\\t",
16887         "\v": "\\v",
16888         "\f": "\\f",
16889         "\b": "\\b",
16890         "\r": "\\r",
16891         "\n": "\\n",
16892         "\\": "\\\\",
16893         "\"": "\\\"",
16894         "\'": "\\\'",
16895         "\`": "\\\`",
16896         "\u2028": "\\u2028",
16897         "\u2029": "\\u2029",
16898         "\u0085": "\\u0085" // nextLine
16899     }));
16900     function encodeUtf16EscapeSequence(charCode) {
16901         var hexCharCode = charCode.toString(16).toUpperCase();
16902         var paddedHexCode = ("0000" + hexCharCode).slice(-4);
16903         return "\\u" + paddedHexCode;
16904     }
16905     function getReplacement(c, offset, input) {
16906         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16907             var lookAhead = input.charCodeAt(offset + c.length);
16908             if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) {
16909                 // 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)
16910                 return "\\x00";
16911             }
16912             // Otherwise, keep printing a literal \0 for the null character
16913             return "\\0";
16914         }
16915         return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0));
16916     }
16917     /**
16918      * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
16919      * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
16920      * Note that this doesn't actually wrap the input in double quotes.
16921      */
16922     function escapeString(s, quoteChar) {
16923         var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
16924             quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
16925                 doubleQuoteEscapedCharsRegExp;
16926         return s.replace(escapedCharsRegExp, getReplacement);
16927     }
16928     ts.escapeString = escapeString;
16929     var nonAsciiCharacters = /[^\u0000-\u007F]/g;
16930     function escapeNonAsciiString(s, quoteChar) {
16931         s = escapeString(s, quoteChar);
16932         // Replace non-ASCII characters with '\uNNNN' escapes if any exist.
16933         // Otherwise just return the original string.
16934         return nonAsciiCharacters.test(s) ?
16935             s.replace(nonAsciiCharacters, function (c) { return encodeUtf16EscapeSequence(c.charCodeAt(0)); }) :
16936             s;
16937     }
16938     ts.escapeNonAsciiString = escapeNonAsciiString;
16939     // This consists of the first 19 unprintable ASCII characters, JSX canonical escapes, lineSeparator,
16940     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16941     // the language service. These characters should be escaped when printing, and if any characters are added,
16942     // the map below must be updated.
16943     var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g;
16944     var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g;
16945     var jsxEscapedCharsMap = new ts.Map(ts.getEntries({
16946         "\"": "&quot;",
16947         "\'": "&apos;"
16948     }));
16949     function encodeJsxCharacterEntity(charCode) {
16950         var hexCharCode = charCode.toString(16).toUpperCase();
16951         return "&#x" + hexCharCode + ";";
16952     }
16953     function getJsxAttributeStringReplacement(c) {
16954         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16955             return "&#0;";
16956         }
16957         return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0));
16958     }
16959     function escapeJsxAttributeString(s, quoteChar) {
16960         var escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp :
16961             jsxDoubleQuoteEscapedCharsRegExp;
16962         return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement);
16963     }
16964     ts.escapeJsxAttributeString = escapeJsxAttributeString;
16965     /**
16966      * Strip off existed surrounding single quotes, double quotes, or backticks from a given string
16967      *
16968      * @return non-quoted string
16969      */
16970     function stripQuotes(name) {
16971         var length = name.length;
16972         if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isQuoteOrBacktick(name.charCodeAt(0))) {
16973             return name.substring(1, length - 1);
16974         }
16975         return name;
16976     }
16977     ts.stripQuotes = stripQuotes;
16978     function isQuoteOrBacktick(charCode) {
16979         return charCode === 39 /* singleQuote */ ||
16980             charCode === 34 /* doubleQuote */ ||
16981             charCode === 96 /* backtick */;
16982     }
16983     function isIntrinsicJsxName(name) {
16984         var ch = name.charCodeAt(0);
16985         return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-") || ts.stringContains(name, ":");
16986     }
16987     ts.isIntrinsicJsxName = isIntrinsicJsxName;
16988     var indentStrings = ["", "    "];
16989     function getIndentString(level) {
16990         // prepopulate cache
16991         var singleLevel = indentStrings[1];
16992         for (var current = indentStrings.length; current <= level; current++) {
16993             indentStrings.push(indentStrings[current - 1] + singleLevel);
16994         }
16995         return indentStrings[level];
16996     }
16997     ts.getIndentString = getIndentString;
16998     function getIndentSize() {
16999         return indentStrings[1].length;
17000     }
17001     ts.getIndentSize = getIndentSize;
17002     function createTextWriter(newLine) {
17003         var output;
17004         var indent;
17005         var lineStart;
17006         var lineCount;
17007         var linePos;
17008         var hasTrailingComment = false;
17009         function updateLineCountAndPosFor(s) {
17010             var lineStartsOfS = ts.computeLineStarts(s);
17011             if (lineStartsOfS.length > 1) {
17012                 lineCount = lineCount + lineStartsOfS.length - 1;
17013                 linePos = output.length - s.length + ts.last(lineStartsOfS);
17014                 lineStart = (linePos - output.length) === 0;
17015             }
17016             else {
17017                 lineStart = false;
17018             }
17019         }
17020         function writeText(s) {
17021             if (s && s.length) {
17022                 if (lineStart) {
17023                     s = getIndentString(indent) + s;
17024                     lineStart = false;
17025                 }
17026                 output += s;
17027                 updateLineCountAndPosFor(s);
17028             }
17029         }
17030         function write(s) {
17031             if (s)
17032                 hasTrailingComment = false;
17033             writeText(s);
17034         }
17035         function writeComment(s) {
17036             if (s)
17037                 hasTrailingComment = true;
17038             writeText(s);
17039         }
17040         function reset() {
17041             output = "";
17042             indent = 0;
17043             lineStart = true;
17044             lineCount = 0;
17045             linePos = 0;
17046             hasTrailingComment = false;
17047         }
17048         function rawWrite(s) {
17049             if (s !== undefined) {
17050                 output += s;
17051                 updateLineCountAndPosFor(s);
17052                 hasTrailingComment = false;
17053             }
17054         }
17055         function writeLiteral(s) {
17056             if (s && s.length) {
17057                 write(s);
17058             }
17059         }
17060         function writeLine(force) {
17061             if (!lineStart || force) {
17062                 output += newLine;
17063                 lineCount++;
17064                 linePos = output.length;
17065                 lineStart = true;
17066                 hasTrailingComment = false;
17067             }
17068         }
17069         function getTextPosWithWriteLine() {
17070             return lineStart ? output.length : (output.length + newLine.length);
17071         }
17072         reset();
17073         return {
17074             write: write,
17075             rawWrite: rawWrite,
17076             writeLiteral: writeLiteral,
17077             writeLine: writeLine,
17078             increaseIndent: function () { indent++; },
17079             decreaseIndent: function () { indent--; },
17080             getIndent: function () { return indent; },
17081             getTextPos: function () { return output.length; },
17082             getLine: function () { return lineCount; },
17083             getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
17084             getText: function () { return output; },
17085             isAtStartOfLine: function () { return lineStart; },
17086             hasTrailingComment: function () { return hasTrailingComment; },
17087             hasTrailingWhitespace: function () { return !!output.length && ts.isWhiteSpaceLike(output.charCodeAt(output.length - 1)); },
17088             clear: reset,
17089             reportInaccessibleThisError: ts.noop,
17090             reportPrivateInBaseOfClassExpression: ts.noop,
17091             reportInaccessibleUniqueSymbolError: ts.noop,
17092             trackSymbol: ts.noop,
17093             writeKeyword: write,
17094             writeOperator: write,
17095             writeParameter: write,
17096             writeProperty: write,
17097             writePunctuation: write,
17098             writeSpace: write,
17099             writeStringLiteral: write,
17100             writeSymbol: function (s, _) { return write(s); },
17101             writeTrailingSemicolon: write,
17102             writeComment: writeComment,
17103             getTextPosWithWriteLine: getTextPosWithWriteLine
17104         };
17105     }
17106     ts.createTextWriter = createTextWriter;
17107     function getTrailingSemicolonDeferringWriter(writer) {
17108         var pendingTrailingSemicolon = false;
17109         function commitPendingTrailingSemicolon() {
17110             if (pendingTrailingSemicolon) {
17111                 writer.writeTrailingSemicolon(";");
17112                 pendingTrailingSemicolon = false;
17113             }
17114         }
17115         return __assign(__assign({}, writer), { writeTrailingSemicolon: function () {
17116                 pendingTrailingSemicolon = true;
17117             },
17118             writeLiteral: function (s) {
17119                 commitPendingTrailingSemicolon();
17120                 writer.writeLiteral(s);
17121             },
17122             writeStringLiteral: function (s) {
17123                 commitPendingTrailingSemicolon();
17124                 writer.writeStringLiteral(s);
17125             },
17126             writeSymbol: function (s, sym) {
17127                 commitPendingTrailingSemicolon();
17128                 writer.writeSymbol(s, sym);
17129             },
17130             writePunctuation: function (s) {
17131                 commitPendingTrailingSemicolon();
17132                 writer.writePunctuation(s);
17133             },
17134             writeKeyword: function (s) {
17135                 commitPendingTrailingSemicolon();
17136                 writer.writeKeyword(s);
17137             },
17138             writeOperator: function (s) {
17139                 commitPendingTrailingSemicolon();
17140                 writer.writeOperator(s);
17141             },
17142             writeParameter: function (s) {
17143                 commitPendingTrailingSemicolon();
17144                 writer.writeParameter(s);
17145             },
17146             writeSpace: function (s) {
17147                 commitPendingTrailingSemicolon();
17148                 writer.writeSpace(s);
17149             },
17150             writeProperty: function (s) {
17151                 commitPendingTrailingSemicolon();
17152                 writer.writeProperty(s);
17153             },
17154             writeComment: function (s) {
17155                 commitPendingTrailingSemicolon();
17156                 writer.writeComment(s);
17157             },
17158             writeLine: function () {
17159                 commitPendingTrailingSemicolon();
17160                 writer.writeLine();
17161             },
17162             increaseIndent: function () {
17163                 commitPendingTrailingSemicolon();
17164                 writer.increaseIndent();
17165             },
17166             decreaseIndent: function () {
17167                 commitPendingTrailingSemicolon();
17168                 writer.decreaseIndent();
17169             } });
17170     }
17171     ts.getTrailingSemicolonDeferringWriter = getTrailingSemicolonDeferringWriter;
17172     function hostUsesCaseSensitiveFileNames(host) {
17173         return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false;
17174     }
17175     ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames;
17176     function hostGetCanonicalFileName(host) {
17177         return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
17178     }
17179     ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
17180     function getResolvedExternalModuleName(host, file, referenceFile) {
17181         return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
17182     }
17183     ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
17184     function getCanonicalAbsolutePath(host, path) {
17185         return host.getCanonicalFileName(ts.getNormalizedAbsolutePath(path, host.getCurrentDirectory()));
17186     }
17187     function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
17188         var file = resolver.getExternalModuleFileFromDeclaration(declaration);
17189         if (!file || file.isDeclarationFile) {
17190             return undefined;
17191         }
17192         // If the declaration already uses a non-relative name, and is outside the common source directory, continue to use it
17193         var specifier = getExternalModuleName(declaration);
17194         if (specifier && ts.isStringLiteralLike(specifier) && !ts.pathIsRelative(specifier.text) &&
17195             getCanonicalAbsolutePath(host, file.path).indexOf(getCanonicalAbsolutePath(host, ts.ensureTrailingDirectorySeparator(host.getCommonSourceDirectory()))) === -1) {
17196             return undefined;
17197         }
17198         return getResolvedExternalModuleName(host, file);
17199     }
17200     ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
17201     /**
17202      * Resolves a local path to a path which is absolute to the base of the emit
17203      */
17204     function getExternalModuleNameFromPath(host, fileName, referencePath) {
17205         var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
17206         var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
17207         var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
17208         var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
17209         var extensionless = removeFileExtension(relativePath);
17210         return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
17211     }
17212     ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
17213     function getOwnEmitOutputFilePath(fileName, host, extension) {
17214         var compilerOptions = host.getCompilerOptions();
17215         var emitOutputFilePathWithoutExtension;
17216         if (compilerOptions.outDir) {
17217             emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
17218         }
17219         else {
17220             emitOutputFilePathWithoutExtension = removeFileExtension(fileName);
17221         }
17222         return emitOutputFilePathWithoutExtension + extension;
17223     }
17224     ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
17225     function getDeclarationEmitOutputFilePath(fileName, host) {
17226         return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
17227     }
17228     ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
17229     function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
17230         var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
17231         var path = outputDir
17232             ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
17233             : fileName;
17234         return removeFileExtension(path) + ".d.ts" /* Dts */;
17235     }
17236     ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
17237     function outFile(options) {
17238         return options.outFile || options.out;
17239     }
17240     ts.outFile = outFile;
17241     /** Returns 'undefined' if and only if 'options.paths' is undefined. */
17242     function getPathsBasePath(options, host) {
17243         var _a, _b;
17244         if (!options.paths)
17245             return undefined;
17246         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'.");
17247     }
17248     ts.getPathsBasePath = getPathsBasePath;
17249     /**
17250      * Gets the source files that are expected to have an emit output.
17251      *
17252      * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
17253      * transformations.
17254      *
17255      * @param host An EmitHost.
17256      * @param targetSourceFile An optional target source file to emit.
17257      */
17258     function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) {
17259         var options = host.getCompilerOptions();
17260         if (outFile(options)) {
17261             var moduleKind = getEmitModuleKind(options);
17262             var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
17263             // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
17264             return ts.filter(host.getSourceFiles(), function (sourceFile) {
17265                 return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) &&
17266                     sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit);
17267             });
17268         }
17269         else {
17270             var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
17271             return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit); });
17272         }
17273     }
17274     ts.getSourceFilesToEmit = getSourceFilesToEmit;
17275     /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
17276     function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) {
17277         var options = host.getCompilerOptions();
17278         return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
17279             !sourceFile.isDeclarationFile &&
17280             !host.isSourceFileFromExternalLibrary(sourceFile) &&
17281             !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) &&
17282             (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName));
17283     }
17284     ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
17285     function getSourceFilePathInNewDir(fileName, host, newDirPath) {
17286         return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
17287     }
17288     ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
17289     function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
17290         var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
17291         var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
17292         sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
17293         return ts.combinePaths(newDirPath, sourceFilePath);
17294     }
17295     ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
17296     function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
17297         host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
17298             diagnostics.add(createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
17299         }, sourceFiles);
17300     }
17301     ts.writeFile = writeFile;
17302     function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) {
17303         if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
17304             var parentDirectory = ts.getDirectoryPath(directoryPath);
17305             ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists);
17306             createDirectory(directoryPath);
17307         }
17308     }
17309     function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) {
17310         // PERF: Checking for directory existence is expensive.  Instead, assume the directory exists
17311         // and fall back to creating it if the file write fails.
17312         try {
17313             writeFile(path, data, writeByteOrderMark);
17314         }
17315         catch (_a) {
17316             ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists);
17317             writeFile(path, data, writeByteOrderMark);
17318         }
17319     }
17320     ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories;
17321     function getLineOfLocalPosition(sourceFile, pos) {
17322         var lineStarts = ts.getLineStarts(sourceFile);
17323         return ts.computeLineOfPosition(lineStarts, pos);
17324     }
17325     ts.getLineOfLocalPosition = getLineOfLocalPosition;
17326     function getLineOfLocalPositionFromLineMap(lineMap, pos) {
17327         return ts.computeLineOfPosition(lineMap, pos);
17328     }
17329     ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
17330     function getFirstConstructorWithBody(node) {
17331         return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
17332     }
17333     ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
17334     function getSetAccessorValueParameter(accessor) {
17335         if (accessor && accessor.parameters.length > 0) {
17336             var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
17337             return accessor.parameters[hasThis ? 1 : 0];
17338         }
17339     }
17340     ts.getSetAccessorValueParameter = getSetAccessorValueParameter;
17341     /** Get the type annotation for the value parameter. */
17342     function getSetAccessorTypeAnnotationNode(accessor) {
17343         var parameter = getSetAccessorValueParameter(accessor);
17344         return parameter && parameter.type;
17345     }
17346     ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
17347     function getThisParameter(signature) {
17348         // callback tags do not currently support this parameters
17349         if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
17350             var thisParameter = signature.parameters[0];
17351             if (parameterIsThisKeyword(thisParameter)) {
17352                 return thisParameter;
17353             }
17354         }
17355     }
17356     ts.getThisParameter = getThisParameter;
17357     function parameterIsThisKeyword(parameter) {
17358         return isThisIdentifier(parameter.name);
17359     }
17360     ts.parameterIsThisKeyword = parameterIsThisKeyword;
17361     function isThisIdentifier(node) {
17362         return !!node && node.kind === 78 /* Identifier */ && identifierIsThisKeyword(node);
17363     }
17364     ts.isThisIdentifier = isThisIdentifier;
17365     function identifierIsThisKeyword(id) {
17366         return id.originalKeywordKind === 107 /* ThisKeyword */;
17367     }
17368     ts.identifierIsThisKeyword = identifierIsThisKeyword;
17369     function getAllAccessorDeclarations(declarations, accessor) {
17370         // TODO: GH#18217
17371         var firstAccessor;
17372         var secondAccessor;
17373         var getAccessor;
17374         var setAccessor;
17375         if (hasDynamicName(accessor)) {
17376             firstAccessor = accessor;
17377             if (accessor.kind === 167 /* GetAccessor */) {
17378                 getAccessor = accessor;
17379             }
17380             else if (accessor.kind === 168 /* SetAccessor */) {
17381                 setAccessor = accessor;
17382             }
17383             else {
17384                 ts.Debug.fail("Accessor has wrong kind");
17385             }
17386         }
17387         else {
17388             ts.forEach(declarations, function (member) {
17389                 if (ts.isAccessor(member)
17390                     && hasSyntacticModifier(member, 32 /* Static */) === hasSyntacticModifier(accessor, 32 /* Static */)) {
17391                     var memberName = getPropertyNameForPropertyNameNode(member.name);
17392                     var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
17393                     if (memberName === accessorName) {
17394                         if (!firstAccessor) {
17395                             firstAccessor = member;
17396                         }
17397                         else if (!secondAccessor) {
17398                             secondAccessor = member;
17399                         }
17400                         if (member.kind === 167 /* GetAccessor */ && !getAccessor) {
17401                             getAccessor = member;
17402                         }
17403                         if (member.kind === 168 /* SetAccessor */ && !setAccessor) {
17404                             setAccessor = member;
17405                         }
17406                     }
17407                 }
17408             });
17409         }
17410         return {
17411             firstAccessor: firstAccessor,
17412             secondAccessor: secondAccessor,
17413             getAccessor: getAccessor,
17414             setAccessor: setAccessor
17415         };
17416     }
17417     ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
17418     /**
17419      * Gets the effective type annotation of a variable, parameter, or property. If the node was
17420      * parsed in a JavaScript file, gets the type annotation from JSDoc.  Also gets the type of
17421      * functions only the JSDoc case.
17422      */
17423     function getEffectiveTypeAnnotationNode(node) {
17424         if (!isInJSFile(node) && ts.isFunctionDeclaration(node))
17425             return undefined;
17426         var type = node.type;
17427         if (type || !isInJSFile(node))
17428             return type;
17429         return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
17430     }
17431     ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
17432     function getTypeAnnotationNode(node) {
17433         return node.type;
17434     }
17435     ts.getTypeAnnotationNode = getTypeAnnotationNode;
17436     /**
17437      * Gets the effective return type annotation of a signature. If the node was parsed in a
17438      * JavaScript file, gets the return type annotation from JSDoc.
17439      */
17440     function getEffectiveReturnTypeNode(node) {
17441         return ts.isJSDocSignature(node) ?
17442             node.type && node.type.typeExpression && node.type.typeExpression.type :
17443             node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
17444     }
17445     ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
17446     function getJSDocTypeParameterDeclarations(node) {
17447         return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; });
17448     }
17449     ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
17450     /** template tags are only available when a typedef isn't already using them */
17451     function isNonTypeAliasTemplate(tag) {
17452         return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 311 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
17453     }
17454     /**
17455      * Gets the effective type annotation of the value parameter of a set accessor. If the node
17456      * was parsed in a JavaScript file, gets the type annotation from JSDoc.
17457      */
17458     function getEffectiveSetAccessorTypeAnnotationNode(node) {
17459         var parameter = getSetAccessorValueParameter(node);
17460         return parameter && getEffectiveTypeAnnotationNode(parameter);
17461     }
17462     ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
17463     function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
17464         emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
17465     }
17466     ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
17467     function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
17468         // If the leading comments start on different line than the start of node, write new line
17469         if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
17470             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
17471             writer.writeLine();
17472         }
17473     }
17474     ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition;
17475     function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
17476         // If the leading comments start on different line than the start of node, write new line
17477         if (pos !== commentPos &&
17478             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
17479             writer.writeLine();
17480         }
17481     }
17482     ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
17483     function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
17484         if (comments && comments.length > 0) {
17485             if (leadingSeparator) {
17486                 writer.writeSpace(" ");
17487             }
17488             var emitInterveningSeparator = false;
17489             for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
17490                 var comment = comments_1[_i];
17491                 if (emitInterveningSeparator) {
17492                     writer.writeSpace(" ");
17493                     emitInterveningSeparator = false;
17494                 }
17495                 writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
17496                 if (comment.hasTrailingNewLine) {
17497                     writer.writeLine();
17498                 }
17499                 else {
17500                     emitInterveningSeparator = true;
17501                 }
17502             }
17503             if (emitInterveningSeparator && trailingSeparator) {
17504                 writer.writeSpace(" ");
17505             }
17506         }
17507     }
17508     ts.emitComments = emitComments;
17509     /**
17510      * Detached comment is a comment at the top of file or function body that is separated from
17511      * the next statement by space.
17512      */
17513     function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
17514         var leadingComments;
17515         var currentDetachedCommentInfo;
17516         if (removeComments) {
17517             // removeComments is true, only reserve pinned comment at the top of file
17518             // For example:
17519             //      /*! Pinned Comment */
17520             //
17521             //      var x = 10;
17522             if (node.pos === 0) {
17523                 leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
17524             }
17525         }
17526         else {
17527             // removeComments is false, just get detached as normal and bypass the process to filter comment
17528             leadingComments = ts.getLeadingCommentRanges(text, node.pos);
17529         }
17530         if (leadingComments) {
17531             var detachedComments = [];
17532             var lastComment = void 0;
17533             for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
17534                 var comment = leadingComments_1[_i];
17535                 if (lastComment) {
17536                     var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
17537                     var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
17538                     if (commentLine >= lastCommentLine + 2) {
17539                         // There was a blank line between the last comment and this comment.  This
17540                         // comment is not part of the copyright comments.  Return what we have so
17541                         // far.
17542                         break;
17543                     }
17544                 }
17545                 detachedComments.push(comment);
17546                 lastComment = comment;
17547             }
17548             if (detachedComments.length) {
17549                 // All comments look like they could have been part of the copyright header.  Make
17550                 // sure there is at least one blank line between it and the node.  If not, it's not
17551                 // a copyright header.
17552                 var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end);
17553                 var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
17554                 if (nodeLine >= lastCommentLine + 2) {
17555                     // Valid detachedComments
17556                     emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
17557                     emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
17558                     currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
17559                 }
17560             }
17561         }
17562         return currentDetachedCommentInfo;
17563         function isPinnedCommentLocal(comment) {
17564             return isPinnedComment(text, comment.pos);
17565         }
17566     }
17567     ts.emitDetachedComments = emitDetachedComments;
17568     function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
17569         if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
17570             var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
17571             var lineCount = lineMap.length;
17572             var firstCommentLineIndent = void 0;
17573             for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
17574                 var nextLineStart = (currentLine + 1) === lineCount
17575                     ? text.length + 1
17576                     : lineMap[currentLine + 1];
17577                 if (pos !== commentPos) {
17578                     // If we are not emitting first line, we need to write the spaces to adjust the alignment
17579                     if (firstCommentLineIndent === undefined) {
17580                         firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
17581                     }
17582                     // These are number of spaces writer is going to write at current indent
17583                     var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
17584                     // Number of spaces we want to be writing
17585                     // eg: Assume writer indent
17586                     // module m {
17587                     //         /* starts at character 9 this is line 1
17588                     //    * starts at character pos 4 line                        --1  = 8 - 8 + 3
17589                     //   More left indented comment */                            --2  = 8 - 8 + 2
17590                     //     class c { }
17591                     // }
17592                     // module m {
17593                     //     /* this is line 1 -- Assume current writer indent 8
17594                     //      * line                                                --3 = 8 - 4 + 5
17595                     //            More right indented comment */                  --4 = 8 - 4 + 11
17596                     //     class c { }
17597                     // }
17598                     var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
17599                     if (spacesToEmit > 0) {
17600                         var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
17601                         var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
17602                         // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
17603                         writer.rawWrite(indentSizeSpaceString);
17604                         // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
17605                         while (numberOfSingleSpacesToEmit) {
17606                             writer.rawWrite(" ");
17607                             numberOfSingleSpacesToEmit--;
17608                         }
17609                     }
17610                     else {
17611                         // No spaces to emit write empty string
17612                         writer.rawWrite("");
17613                     }
17614                 }
17615                 // Write the comment line text
17616                 writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
17617                 pos = nextLineStart;
17618             }
17619         }
17620         else {
17621             // Single line comment of style //....
17622             writer.writeComment(text.substring(commentPos, commentEnd));
17623         }
17624     }
17625     ts.writeCommentRange = writeCommentRange;
17626     function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
17627         var end = Math.min(commentEnd, nextLineStart - 1);
17628         var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
17629         if (currentLineText) {
17630             // trimmed forward and ending spaces text
17631             writer.writeComment(currentLineText);
17632             if (end !== commentEnd) {
17633                 writer.writeLine();
17634             }
17635         }
17636         else {
17637             // Empty string - make sure we write empty line
17638             writer.rawWrite(newLine);
17639         }
17640     }
17641     function calculateIndent(text, pos, end) {
17642         var currentLineIndent = 0;
17643         for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
17644             if (text.charCodeAt(pos) === 9 /* tab */) {
17645                 // Tabs = TabSize = indent size and go to next tabStop
17646                 currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
17647             }
17648             else {
17649                 // Single space
17650                 currentLineIndent++;
17651             }
17652         }
17653         return currentLineIndent;
17654     }
17655     function hasEffectiveModifiers(node) {
17656         return getEffectiveModifierFlags(node) !== 0 /* None */;
17657     }
17658     ts.hasEffectiveModifiers = hasEffectiveModifiers;
17659     function hasSyntacticModifiers(node) {
17660         return getSyntacticModifierFlags(node) !== 0 /* None */;
17661     }
17662     ts.hasSyntacticModifiers = hasSyntacticModifiers;
17663     function hasEffectiveModifier(node, flags) {
17664         return !!getSelectedEffectiveModifierFlags(node, flags);
17665     }
17666     ts.hasEffectiveModifier = hasEffectiveModifier;
17667     function hasSyntacticModifier(node, flags) {
17668         return !!getSelectedSyntacticModifierFlags(node, flags);
17669     }
17670     ts.hasSyntacticModifier = hasSyntacticModifier;
17671     function hasStaticModifier(node) {
17672         return hasSyntacticModifier(node, 32 /* Static */);
17673     }
17674     ts.hasStaticModifier = hasStaticModifier;
17675     function hasEffectiveReadonlyModifier(node) {
17676         return hasEffectiveModifier(node, 64 /* Readonly */);
17677     }
17678     ts.hasEffectiveReadonlyModifier = hasEffectiveReadonlyModifier;
17679     function getSelectedEffectiveModifierFlags(node, flags) {
17680         return getEffectiveModifierFlags(node) & flags;
17681     }
17682     ts.getSelectedEffectiveModifierFlags = getSelectedEffectiveModifierFlags;
17683     function getSelectedSyntacticModifierFlags(node, flags) {
17684         return getSyntacticModifierFlags(node) & flags;
17685     }
17686     ts.getSelectedSyntacticModifierFlags = getSelectedSyntacticModifierFlags;
17687     function getModifierFlagsWorker(node, includeJSDoc, alwaysIncludeJSDoc) {
17688         if (node.kind >= 0 /* FirstToken */ && node.kind <= 156 /* LastToken */) {
17689             return 0 /* None */;
17690         }
17691         if (!(node.modifierFlagsCache & 536870912 /* HasComputedFlags */)) {
17692             node.modifierFlagsCache = getSyntacticModifierFlagsNoCache(node) | 536870912 /* HasComputedFlags */;
17693         }
17694         if (includeJSDoc && !(node.modifierFlagsCache & 4096 /* HasComputedJSDocModifiers */) && (alwaysIncludeJSDoc || isInJSFile(node)) && node.parent) {
17695             node.modifierFlagsCache |= getJSDocModifierFlagsNoCache(node) | 4096 /* HasComputedJSDocModifiers */;
17696         }
17697         return node.modifierFlagsCache & ~(536870912 /* HasComputedFlags */ | 4096 /* HasComputedJSDocModifiers */);
17698     }
17699     /**
17700      * Gets the effective ModifierFlags for the provided node, including JSDoc modifiers. The modifiers will be cached on the node to improve performance.
17701      *
17702      * NOTE: This function may use `parent` pointers.
17703      */
17704     function getEffectiveModifierFlags(node) {
17705         return getModifierFlagsWorker(node, /*includeJSDoc*/ true);
17706     }
17707     ts.getEffectiveModifierFlags = getEffectiveModifierFlags;
17708     function getEffectiveModifierFlagsAlwaysIncludeJSDoc(node) {
17709         return getModifierFlagsWorker(node, /*includeJSDOc*/ true, /*alwaysIncludeJSDOc*/ true);
17710     }
17711     ts.getEffectiveModifierFlagsAlwaysIncludeJSDoc = getEffectiveModifierFlagsAlwaysIncludeJSDoc;
17712     /**
17713      * Gets the ModifierFlags for syntactic modifiers on the provided node. The modifiers will be cached on the node to improve performance.
17714      *
17715      * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc.
17716      */
17717     function getSyntacticModifierFlags(node) {
17718         return getModifierFlagsWorker(node, /*includeJSDoc*/ false);
17719     }
17720     ts.getSyntacticModifierFlags = getSyntacticModifierFlags;
17721     function getJSDocModifierFlagsNoCache(node) {
17722         var flags = 0 /* None */;
17723         if (!!node.parent && !ts.isParameter(node)) {
17724             if (isInJSFile(node)) {
17725                 if (ts.getJSDocPublicTagNoCache(node))
17726                     flags |= 4 /* Public */;
17727                 if (ts.getJSDocPrivateTagNoCache(node))
17728                     flags |= 8 /* Private */;
17729                 if (ts.getJSDocProtectedTagNoCache(node))
17730                     flags |= 16 /* Protected */;
17731                 if (ts.getJSDocReadonlyTagNoCache(node))
17732                     flags |= 64 /* Readonly */;
17733             }
17734             if (ts.getJSDocDeprecatedTagNoCache(node))
17735                 flags |= 8192 /* Deprecated */;
17736         }
17737         return flags;
17738     }
17739     /**
17740      * Gets the effective ModifierFlags for the provided node, including JSDoc modifiers. The modifier flags cache on the node is ignored.
17741      *
17742      * NOTE: This function may use `parent` pointers.
17743      */
17744     function getEffectiveModifierFlagsNoCache(node) {
17745         return getSyntacticModifierFlagsNoCache(node) | getJSDocModifierFlagsNoCache(node);
17746     }
17747     ts.getEffectiveModifierFlagsNoCache = getEffectiveModifierFlagsNoCache;
17748     /**
17749      * Gets the ModifierFlags for syntactic modifiers on the provided node. The modifier flags cache on the node is ignored.
17750      *
17751      * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc.
17752      */
17753     function getSyntacticModifierFlagsNoCache(node) {
17754         var flags = modifiersToFlags(node.modifiers);
17755         if (node.flags & 4 /* NestedNamespace */ || (node.kind === 78 /* Identifier */ && node.isInJSDocNamespace)) {
17756             flags |= 1 /* Export */;
17757         }
17758         return flags;
17759     }
17760     ts.getSyntacticModifierFlagsNoCache = getSyntacticModifierFlagsNoCache;
17761     function modifiersToFlags(modifiers) {
17762         var flags = 0 /* None */;
17763         if (modifiers) {
17764             for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) {
17765                 var modifier = modifiers_1[_i];
17766                 flags |= modifierToFlag(modifier.kind);
17767             }
17768         }
17769         return flags;
17770     }
17771     ts.modifiersToFlags = modifiersToFlags;
17772     function modifierToFlag(token) {
17773         switch (token) {
17774             case 123 /* StaticKeyword */: return 32 /* Static */;
17775             case 122 /* PublicKeyword */: return 4 /* Public */;
17776             case 121 /* ProtectedKeyword */: return 16 /* Protected */;
17777             case 120 /* PrivateKeyword */: return 8 /* Private */;
17778             case 125 /* AbstractKeyword */: return 128 /* Abstract */;
17779             case 92 /* ExportKeyword */: return 1 /* Export */;
17780             case 133 /* DeclareKeyword */: return 2 /* Ambient */;
17781             case 84 /* ConstKeyword */: return 2048 /* Const */;
17782             case 87 /* DefaultKeyword */: return 512 /* Default */;
17783             case 129 /* AsyncKeyword */: return 256 /* Async */;
17784             case 142 /* ReadonlyKeyword */: return 64 /* Readonly */;
17785         }
17786         return 0 /* None */;
17787     }
17788     ts.modifierToFlag = modifierToFlag;
17789     function isLogicalOperator(token) {
17790         return token === 56 /* BarBarToken */
17791             || token === 55 /* AmpersandAmpersandToken */
17792             || token === 53 /* ExclamationToken */;
17793     }
17794     ts.isLogicalOperator = isLogicalOperator;
17795     function isLogicalOrCoalescingAssignmentOperator(token) {
17796         return token === 74 /* BarBarEqualsToken */
17797             || token === 75 /* AmpersandAmpersandEqualsToken */
17798             || token === 76 /* QuestionQuestionEqualsToken */;
17799     }
17800     ts.isLogicalOrCoalescingAssignmentOperator = isLogicalOrCoalescingAssignmentOperator;
17801     function isLogicalOrCoalescingAssignmentExpression(expr) {
17802         return isLogicalOrCoalescingAssignmentOperator(expr.operatorToken.kind);
17803     }
17804     ts.isLogicalOrCoalescingAssignmentExpression = isLogicalOrCoalescingAssignmentExpression;
17805     function isAssignmentOperator(token) {
17806         return token >= 62 /* FirstAssignment */ && token <= 77 /* LastAssignment */;
17807     }
17808     ts.isAssignmentOperator = isAssignmentOperator;
17809     /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
17810     function tryGetClassExtendingExpressionWithTypeArguments(node) {
17811         var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
17812         return cls && !cls.isImplements ? cls.class : undefined;
17813     }
17814     ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
17815     function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) {
17816         return ts.isExpressionWithTypeArguments(node)
17817             && ts.isHeritageClause(node.parent)
17818             && ts.isClassLike(node.parent.parent)
17819             ? { class: node.parent.parent, isImplements: node.parent.token === 116 /* ImplementsKeyword */ }
17820             : undefined;
17821     }
17822     ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments;
17823     function isAssignmentExpression(node, excludeCompoundAssignment) {
17824         return ts.isBinaryExpression(node)
17825             && (excludeCompoundAssignment
17826                 ? node.operatorToken.kind === 62 /* EqualsToken */
17827                 : isAssignmentOperator(node.operatorToken.kind))
17828             && ts.isLeftHandSideExpression(node.left);
17829     }
17830     ts.isAssignmentExpression = isAssignmentExpression;
17831     function isDestructuringAssignment(node) {
17832         if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
17833             var kind = node.left.kind;
17834             return kind === 200 /* ObjectLiteralExpression */
17835                 || kind === 199 /* ArrayLiteralExpression */;
17836         }
17837         return false;
17838     }
17839     ts.isDestructuringAssignment = isDestructuringAssignment;
17840     function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
17841         return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
17842     }
17843     ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
17844     function isEntityNameExpression(node) {
17845         return node.kind === 78 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
17846     }
17847     ts.isEntityNameExpression = isEntityNameExpression;
17848     function getFirstIdentifier(node) {
17849         switch (node.kind) {
17850             case 78 /* Identifier */:
17851                 return node;
17852             case 157 /* QualifiedName */:
17853                 do {
17854                     node = node.left;
17855                 } while (node.kind !== 78 /* Identifier */);
17856                 return node;
17857             case 201 /* PropertyAccessExpression */:
17858                 do {
17859                     node = node.expression;
17860                 } while (node.kind !== 78 /* Identifier */);
17861                 return node;
17862         }
17863     }
17864     ts.getFirstIdentifier = getFirstIdentifier;
17865     function isDottedName(node) {
17866         return node.kind === 78 /* Identifier */ || node.kind === 107 /* ThisKeyword */ || node.kind === 105 /* SuperKeyword */ ||
17867             node.kind === 201 /* PropertyAccessExpression */ && isDottedName(node.expression) ||
17868             node.kind === 207 /* ParenthesizedExpression */ && isDottedName(node.expression);
17869     }
17870     ts.isDottedName = isDottedName;
17871     function isPropertyAccessEntityNameExpression(node) {
17872         return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression);
17873     }
17874     ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
17875     function tryGetPropertyAccessOrIdentifierToString(expr) {
17876         if (ts.isPropertyAccessExpression(expr)) {
17877             var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
17878             if (baseStr !== undefined) {
17879                 return baseStr + "." + entityNameToString(expr.name);
17880             }
17881         }
17882         else if (ts.isElementAccessExpression(expr)) {
17883             var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
17884             if (baseStr !== undefined && ts.isPropertyName(expr.argumentExpression)) {
17885                 return baseStr + "." + getPropertyNameForPropertyNameNode(expr.argumentExpression);
17886             }
17887         }
17888         else if (ts.isIdentifier(expr)) {
17889             return ts.unescapeLeadingUnderscores(expr.escapedText);
17890         }
17891         return undefined;
17892     }
17893     ts.tryGetPropertyAccessOrIdentifierToString = tryGetPropertyAccessOrIdentifierToString;
17894     function isPrototypeAccess(node) {
17895         return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype";
17896     }
17897     ts.isPrototypeAccess = isPrototypeAccess;
17898     function isRightSideOfQualifiedNameOrPropertyAccess(node) {
17899         return (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) ||
17900             (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node);
17901     }
17902     ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
17903     function isEmptyObjectLiteral(expression) {
17904         return expression.kind === 200 /* ObjectLiteralExpression */ &&
17905             expression.properties.length === 0;
17906     }
17907     ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
17908     function isEmptyArrayLiteral(expression) {
17909         return expression.kind === 199 /* ArrayLiteralExpression */ &&
17910             expression.elements.length === 0;
17911     }
17912     ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
17913     function getLocalSymbolForExportDefault(symbol) {
17914         if (!isExportDefaultSymbol(symbol))
17915             return undefined;
17916         for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
17917             var decl = _a[_i];
17918             if (decl.localSymbol)
17919                 return decl.localSymbol;
17920         }
17921         return undefined;
17922     }
17923     ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
17924     function isExportDefaultSymbol(symbol) {
17925         return symbol && ts.length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations[0], 512 /* Default */);
17926     }
17927     /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
17928     function tryExtractTSExtension(fileName) {
17929         return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
17930     }
17931     ts.tryExtractTSExtension = tryExtractTSExtension;
17932     /**
17933      * Replace each instance of non-ascii characters by one, two, three, or four escape sequences
17934      * representing the UTF-8 encoding of the character, and return the expanded char code list.
17935      */
17936     function getExpandedCharCodes(input) {
17937         var output = [];
17938         var length = input.length;
17939         for (var i = 0; i < length; i++) {
17940             var charCode = input.charCodeAt(i);
17941             // handle utf8
17942             if (charCode < 0x80) {
17943                 output.push(charCode);
17944             }
17945             else if (charCode < 0x800) {
17946                 output.push((charCode >> 6) | 192);
17947                 output.push((charCode & 63) | 128);
17948             }
17949             else if (charCode < 0x10000) {
17950                 output.push((charCode >> 12) | 224);
17951                 output.push(((charCode >> 6) & 63) | 128);
17952                 output.push((charCode & 63) | 128);
17953             }
17954             else if (charCode < 0x20000) {
17955                 output.push((charCode >> 18) | 240);
17956                 output.push(((charCode >> 12) & 63) | 128);
17957                 output.push(((charCode >> 6) & 63) | 128);
17958                 output.push((charCode & 63) | 128);
17959             }
17960             else {
17961                 ts.Debug.assert(false, "Unexpected code point");
17962             }
17963         }
17964         return output;
17965     }
17966     var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
17967     /**
17968      * Converts a string to a base-64 encoded ASCII string.
17969      */
17970     function convertToBase64(input) {
17971         var result = "";
17972         var charCodes = getExpandedCharCodes(input);
17973         var i = 0;
17974         var length = charCodes.length;
17975         var byte1, byte2, byte3, byte4;
17976         while (i < length) {
17977             // Convert every 6-bits in the input 3 character points
17978             // into a base64 digit
17979             byte1 = charCodes[i] >> 2;
17980             byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
17981             byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
17982             byte4 = charCodes[i + 2] & 63;
17983             // We are out of characters in the input, set the extra
17984             // digits to 64 (padding character).
17985             if (i + 1 >= length) {
17986                 byte3 = byte4 = 64;
17987             }
17988             else if (i + 2 >= length) {
17989                 byte4 = 64;
17990             }
17991             // Write to the output
17992             result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
17993             i += 3;
17994         }
17995         return result;
17996     }
17997     ts.convertToBase64 = convertToBase64;
17998     function getStringFromExpandedCharCodes(codes) {
17999         var output = "";
18000         var i = 0;
18001         var length = codes.length;
18002         while (i < length) {
18003             var charCode = codes[i];
18004             if (charCode < 0x80) {
18005                 output += String.fromCharCode(charCode);
18006                 i++;
18007             }
18008             else if ((charCode & 192) === 192) {
18009                 var value = charCode & 63;
18010                 i++;
18011                 var nextCode = codes[i];
18012                 while ((nextCode & 192) === 128) {
18013                     value = (value << 6) | (nextCode & 63);
18014                     i++;
18015                     nextCode = codes[i];
18016                 }
18017                 // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us
18018                 output += String.fromCharCode(value);
18019             }
18020             else {
18021                 // We don't want to kill the process when decoding fails (due to a following char byte not
18022                 // following a leading char), so we just print the (bad) value
18023                 output += String.fromCharCode(charCode);
18024                 i++;
18025             }
18026         }
18027         return output;
18028     }
18029     function base64encode(host, input) {
18030         if (host && host.base64encode) {
18031             return host.base64encode(input);
18032         }
18033         return convertToBase64(input);
18034     }
18035     ts.base64encode = base64encode;
18036     function base64decode(host, input) {
18037         if (host && host.base64decode) {
18038             return host.base64decode(input);
18039         }
18040         var length = input.length;
18041         var expandedCharCodes = [];
18042         var i = 0;
18043         while (i < length) {
18044             // Stop decoding once padding characters are present
18045             if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) {
18046                 break;
18047             }
18048             // convert 4 input digits into three characters, ignoring padding characters at the end
18049             var ch1 = base64Digits.indexOf(input[i]);
18050             var ch2 = base64Digits.indexOf(input[i + 1]);
18051             var ch3 = base64Digits.indexOf(input[i + 2]);
18052             var ch4 = base64Digits.indexOf(input[i + 3]);
18053             var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3);
18054             var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15);
18055             var code3 = ((ch3 & 3) << 6) | (ch4 & 63);
18056             if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
18057                 expandedCharCodes.push(code1);
18058             }
18059             else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
18060                 expandedCharCodes.push(code1, code2);
18061             }
18062             else {
18063                 expandedCharCodes.push(code1, code2, code3);
18064             }
18065             i += 4;
18066         }
18067         return getStringFromExpandedCharCodes(expandedCharCodes);
18068     }
18069     ts.base64decode = base64decode;
18070     function readJson(path, host) {
18071         try {
18072             var jsonText = host.readFile(path);
18073             if (!jsonText)
18074                 return {};
18075             var result = ts.parseConfigFileTextToJson(path, jsonText);
18076             if (result.error) {
18077                 return {};
18078             }
18079             return result.config;
18080         }
18081         catch (e) {
18082             // gracefully handle if readFile fails or returns not JSON
18083             return {};
18084         }
18085     }
18086     ts.readJson = readJson;
18087     function directoryProbablyExists(directoryName, host) {
18088         // if host does not support 'directoryExists' assume that directory will exist
18089         return !host.directoryExists || host.directoryExists(directoryName);
18090     }
18091     ts.directoryProbablyExists = directoryProbablyExists;
18092     var carriageReturnLineFeed = "\r\n";
18093     var lineFeed = "\n";
18094     function getNewLineCharacter(options, getNewLine) {
18095         switch (options.newLine) {
18096             case 0 /* CarriageReturnLineFeed */:
18097                 return carriageReturnLineFeed;
18098             case 1 /* LineFeed */:
18099                 return lineFeed;
18100         }
18101         return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
18102     }
18103     ts.getNewLineCharacter = getNewLineCharacter;
18104     /**
18105      * Creates a new TextRange from the provided pos and end.
18106      *
18107      * @param pos The start position.
18108      * @param end The end position.
18109      */
18110     function createRange(pos, end) {
18111         if (end === void 0) { end = pos; }
18112         ts.Debug.assert(end >= pos || end === -1);
18113         return { pos: pos, end: end };
18114     }
18115     ts.createRange = createRange;
18116     /**
18117      * Creates a new TextRange from a provided range with a new end position.
18118      *
18119      * @param range A TextRange.
18120      * @param end The new end position.
18121      */
18122     function moveRangeEnd(range, end) {
18123         return createRange(range.pos, end);
18124     }
18125     ts.moveRangeEnd = moveRangeEnd;
18126     /**
18127      * Creates a new TextRange from a provided range with a new start position.
18128      *
18129      * @param range A TextRange.
18130      * @param pos The new Start position.
18131      */
18132     function moveRangePos(range, pos) {
18133         return createRange(pos, range.end);
18134     }
18135     ts.moveRangePos = moveRangePos;
18136     /**
18137      * Moves the start position of a range past any decorators.
18138      */
18139     function moveRangePastDecorators(node) {
18140         return node.decorators && node.decorators.length > 0
18141             ? moveRangePos(node, node.decorators.end)
18142             : node;
18143     }
18144     ts.moveRangePastDecorators = moveRangePastDecorators;
18145     /**
18146      * Moves the start position of a range past any decorators or modifiers.
18147      */
18148     function moveRangePastModifiers(node) {
18149         return node.modifiers && node.modifiers.length > 0
18150             ? moveRangePos(node, node.modifiers.end)
18151             : moveRangePastDecorators(node);
18152     }
18153     ts.moveRangePastModifiers = moveRangePastModifiers;
18154     /**
18155      * Determines whether a TextRange has the same start and end positions.
18156      *
18157      * @param range A TextRange.
18158      */
18159     function isCollapsedRange(range) {
18160         return range.pos === range.end;
18161     }
18162     ts.isCollapsedRange = isCollapsedRange;
18163     /**
18164      * Creates a new TextRange for a token at the provides start position.
18165      *
18166      * @param pos The start position.
18167      * @param token The token.
18168      */
18169     function createTokenRange(pos, token) {
18170         return createRange(pos, pos + ts.tokenToString(token).length);
18171     }
18172     ts.createTokenRange = createTokenRange;
18173     function rangeIsOnSingleLine(range, sourceFile) {
18174         return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
18175     }
18176     ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
18177     function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
18178         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
18179     }
18180     ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
18181     function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
18182         return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
18183     }
18184     ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
18185     function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
18186         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile);
18187     }
18188     ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
18189     function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
18190         return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
18191     }
18192     ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
18193     function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) {
18194         var range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments);
18195         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2Start);
18196     }
18197     ts.getLinesBetweenRangeEndAndRangeStart = getLinesBetweenRangeEndAndRangeStart;
18198     function getLinesBetweenRangeEndPositions(range1, range2, sourceFile) {
18199         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2.end);
18200     }
18201     ts.getLinesBetweenRangeEndPositions = getLinesBetweenRangeEndPositions;
18202     function isNodeArrayMultiLine(list, sourceFile) {
18203         return !positionsAreOnSameLine(list.pos, list.end, sourceFile);
18204     }
18205     ts.isNodeArrayMultiLine = isNodeArrayMultiLine;
18206     function positionsAreOnSameLine(pos1, pos2, sourceFile) {
18207         return ts.getLinesBetweenPositions(sourceFile, pos1, pos2) === 0;
18208     }
18209     ts.positionsAreOnSameLine = positionsAreOnSameLine;
18210     function getStartPositionOfRange(range, sourceFile, includeComments) {
18211         return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments);
18212     }
18213     ts.getStartPositionOfRange = getStartPositionOfRange;
18214     function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
18215         var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
18216         var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile);
18217         return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos);
18218     }
18219     ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter;
18220     function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
18221         var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
18222         return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos));
18223     }
18224     ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter;
18225     function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) {
18226         if (stopPos === void 0) { stopPos = 0; }
18227         while (pos-- > stopPos) {
18228             if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) {
18229                 return pos;
18230             }
18231         }
18232     }
18233     /**
18234      * Determines whether a name was originally the declaration name of an enum or namespace
18235      * declaration.
18236      */
18237     function isDeclarationNameOfEnumOrNamespace(node) {
18238         var parseNode = ts.getParseTreeNode(node);
18239         if (parseNode) {
18240             switch (parseNode.parent.kind) {
18241                 case 255 /* EnumDeclaration */:
18242                 case 256 /* ModuleDeclaration */:
18243                     return parseNode === parseNode.parent.name;
18244             }
18245         }
18246         return false;
18247     }
18248     ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
18249     function getInitializedVariables(node) {
18250         return ts.filter(node.declarations, isInitializedVariable);
18251     }
18252     ts.getInitializedVariables = getInitializedVariables;
18253     function isInitializedVariable(node) {
18254         return node.initializer !== undefined;
18255     }
18256     function isWatchSet(options) {
18257         // Firefox has Object.prototype.watch
18258         return options.watch && options.hasOwnProperty("watch");
18259     }
18260     ts.isWatchSet = isWatchSet;
18261     function closeFileWatcher(watcher) {
18262         watcher.close();
18263     }
18264     ts.closeFileWatcher = closeFileWatcher;
18265     function getCheckFlags(symbol) {
18266         return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
18267     }
18268     ts.getCheckFlags = getCheckFlags;
18269     function getDeclarationModifierFlagsFromSymbol(s) {
18270         if (s.valueDeclaration) {
18271             var flags = ts.getCombinedModifierFlags(s.valueDeclaration);
18272             return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
18273         }
18274         if (getCheckFlags(s) & 6 /* Synthetic */) {
18275             var checkFlags = s.checkFlags;
18276             var accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 8 /* Private */ :
18277                 checkFlags & 256 /* ContainsPublic */ ? 4 /* Public */ :
18278                     16 /* Protected */;
18279             var staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 32 /* Static */ : 0;
18280             return accessModifier | staticModifier;
18281         }
18282         if (s.flags & 4194304 /* Prototype */) {
18283             return 4 /* Public */ | 32 /* Static */;
18284         }
18285         return 0;
18286     }
18287     ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
18288     function skipAlias(symbol, checker) {
18289         return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol;
18290     }
18291     ts.skipAlias = skipAlias;
18292     /** See comment on `declareModuleMember` in `binder.ts`. */
18293     function getCombinedLocalAndExportSymbolFlags(symbol) {
18294         return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags;
18295     }
18296     ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags;
18297     function isWriteOnlyAccess(node) {
18298         return accessKind(node) === 1 /* Write */;
18299     }
18300     ts.isWriteOnlyAccess = isWriteOnlyAccess;
18301     function isWriteAccess(node) {
18302         return accessKind(node) !== 0 /* Read */;
18303     }
18304     ts.isWriteAccess = isWriteAccess;
18305     var AccessKind;
18306     (function (AccessKind) {
18307         /** Only reads from a variable. */
18308         AccessKind[AccessKind["Read"] = 0] = "Read";
18309         /** Only writes to a variable without using the result. E.g.: `x++;`. */
18310         AccessKind[AccessKind["Write"] = 1] = "Write";
18311         /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */
18312         AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
18313     })(AccessKind || (AccessKind = {}));
18314     function accessKind(node) {
18315         var parent = node.parent;
18316         if (!parent)
18317             return 0 /* Read */;
18318         switch (parent.kind) {
18319             case 207 /* ParenthesizedExpression */:
18320                 return accessKind(parent);
18321             case 215 /* PostfixUnaryExpression */:
18322             case 214 /* PrefixUnaryExpression */:
18323                 var operator = parent.operator;
18324                 return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
18325             case 216 /* BinaryExpression */:
18326                 var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
18327                 return left === node && isAssignmentOperator(operatorToken.kind) ?
18328                     operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
18329                     : 0 /* Read */;
18330             case 201 /* PropertyAccessExpression */:
18331                 return parent.name !== node ? 0 /* Read */ : accessKind(parent);
18332             case 288 /* PropertyAssignment */: {
18333                 var parentAccess = accessKind(parent.parent);
18334                 // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
18335                 return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
18336             }
18337             case 289 /* ShorthandPropertyAssignment */:
18338                 // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
18339                 return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
18340             case 199 /* ArrayLiteralExpression */:
18341                 return accessKind(parent);
18342             default:
18343                 return 0 /* Read */;
18344         }
18345         function writeOrReadWrite() {
18346             // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
18347             return parent.parent && skipParenthesesUp(parent.parent).kind === 233 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
18348         }
18349     }
18350     function reverseAccessKind(a) {
18351         switch (a) {
18352             case 0 /* Read */:
18353                 return 1 /* Write */;
18354             case 1 /* Write */:
18355                 return 0 /* Read */;
18356             case 2 /* ReadWrite */:
18357                 return 2 /* ReadWrite */;
18358             default:
18359                 return ts.Debug.assertNever(a);
18360         }
18361     }
18362     function compareDataObjects(dst, src) {
18363         if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
18364             return false;
18365         }
18366         for (var e in dst) {
18367             if (typeof dst[e] === "object") {
18368                 if (!compareDataObjects(dst[e], src[e])) {
18369                     return false;
18370                 }
18371             }
18372             else if (typeof dst[e] !== "function") {
18373                 if (dst[e] !== src[e]) {
18374                     return false;
18375                 }
18376             }
18377         }
18378         return true;
18379     }
18380     ts.compareDataObjects = compareDataObjects;
18381     /**
18382      * clears already present map by calling onDeleteExistingValue callback before deleting that key/value
18383      */
18384     function clearMap(map, onDeleteValue) {
18385         // Remove all
18386         map.forEach(onDeleteValue);
18387         map.clear();
18388     }
18389     ts.clearMap = clearMap;
18390     /**
18391      * Mutates the map with newMap such that keys in map will be same as newMap.
18392      */
18393     function mutateMapSkippingNewValues(map, newMap, options) {
18394         var onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue;
18395         // Needs update
18396         map.forEach(function (existingValue, key) {
18397             var valueInNewMap = newMap.get(key);
18398             // Not present any more in new map, remove it
18399             if (valueInNewMap === undefined) {
18400                 map.delete(key);
18401                 onDeleteValue(existingValue, key);
18402             }
18403             // If present notify about existing values
18404             else if (onExistingValue) {
18405                 onExistingValue(existingValue, valueInNewMap, key);
18406             }
18407         });
18408     }
18409     ts.mutateMapSkippingNewValues = mutateMapSkippingNewValues;
18410     /**
18411      * Mutates the map with newMap such that keys in map will be same as newMap.
18412      */
18413     function mutateMap(map, newMap, options) {
18414         // Needs update
18415         mutateMapSkippingNewValues(map, newMap, options);
18416         var createNewValue = options.createNewValue;
18417         // Add new values that are not already present
18418         newMap.forEach(function (valueInNewMap, key) {
18419             if (!map.has(key)) {
18420                 // New values
18421                 map.set(key, createNewValue(key, valueInNewMap));
18422             }
18423         });
18424     }
18425     ts.mutateMap = mutateMap;
18426     function isAbstractConstructorSymbol(symbol) {
18427         if (symbol.flags & 32 /* Class */) {
18428             var declaration = getClassLikeDeclarationOfSymbol(symbol);
18429             return !!declaration && hasSyntacticModifier(declaration, 128 /* Abstract */);
18430         }
18431         return false;
18432     }
18433     ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
18434     function getClassLikeDeclarationOfSymbol(symbol) {
18435         return ts.find(symbol.declarations, ts.isClassLike);
18436     }
18437     ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
18438     function getObjectFlags(type) {
18439         return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0;
18440     }
18441     ts.getObjectFlags = getObjectFlags;
18442     function typeHasCallOrConstructSignatures(type, checker) {
18443         return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
18444     }
18445     ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
18446     function forSomeAncestorDirectory(directory, callback) {
18447         return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
18448     }
18449     ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
18450     function isUMDExportSymbol(symbol) {
18451         return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
18452     }
18453     ts.isUMDExportSymbol = isUMDExportSymbol;
18454     function showModuleSpecifier(_a) {
18455         var moduleSpecifier = _a.moduleSpecifier;
18456         return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
18457     }
18458     ts.showModuleSpecifier = showModuleSpecifier;
18459     function getLastChild(node) {
18460         var lastChild;
18461         ts.forEachChild(node, function (child) {
18462             if (nodeIsPresent(child))
18463                 lastChild = child;
18464         }, function (children) {
18465             // As an optimization, jump straight to the end of the list.
18466             for (var i = children.length - 1; i >= 0; i--) {
18467                 if (nodeIsPresent(children[i])) {
18468                     lastChild = children[i];
18469                     break;
18470                 }
18471             }
18472         });
18473         return lastChild;
18474     }
18475     ts.getLastChild = getLastChild;
18476     function addToSeen(seen, key, value) {
18477         if (value === void 0) { value = true; }
18478         key = String(key);
18479         if (seen.has(key)) {
18480             return false;
18481         }
18482         seen.set(key, value);
18483         return true;
18484     }
18485     ts.addToSeen = addToSeen;
18486     function isObjectTypeDeclaration(node) {
18487         return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
18488     }
18489     ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
18490     function isTypeNodeKind(kind) {
18491         return (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */)
18492             || kind === 128 /* AnyKeyword */
18493             || kind === 152 /* UnknownKeyword */
18494             || kind === 144 /* NumberKeyword */
18495             || kind === 155 /* BigIntKeyword */
18496             || kind === 145 /* ObjectKeyword */
18497             || kind === 131 /* BooleanKeyword */
18498             || kind === 147 /* StringKeyword */
18499             || kind === 148 /* SymbolKeyword */
18500             || kind === 113 /* VoidKeyword */
18501             || kind === 150 /* UndefinedKeyword */
18502             || kind === 141 /* NeverKeyword */
18503             || kind === 223 /* ExpressionWithTypeArguments */
18504             || kind === 303 /* JSDocAllType */
18505             || kind === 304 /* JSDocUnknownType */
18506             || kind === 305 /* JSDocNullableType */
18507             || kind === 306 /* JSDocNonNullableType */
18508             || kind === 307 /* JSDocOptionalType */
18509             || kind === 308 /* JSDocFunctionType */
18510             || kind === 309 /* JSDocVariadicType */;
18511     }
18512     ts.isTypeNodeKind = isTypeNodeKind;
18513     function isAccessExpression(node) {
18514         return node.kind === 201 /* PropertyAccessExpression */ || node.kind === 202 /* ElementAccessExpression */;
18515     }
18516     ts.isAccessExpression = isAccessExpression;
18517     function getNameOfAccessExpression(node) {
18518         if (node.kind === 201 /* PropertyAccessExpression */) {
18519             return node.name;
18520         }
18521         ts.Debug.assert(node.kind === 202 /* ElementAccessExpression */);
18522         return node.argumentExpression;
18523     }
18524     ts.getNameOfAccessExpression = getNameOfAccessExpression;
18525     function isBundleFileTextLike(section) {
18526         switch (section.kind) {
18527             case "text" /* Text */:
18528             case "internal" /* Internal */:
18529                 return true;
18530             default:
18531                 return false;
18532         }
18533     }
18534     ts.isBundleFileTextLike = isBundleFileTextLike;
18535     function isNamedImportsOrExports(node) {
18536         return node.kind === 264 /* NamedImports */ || node.kind === 268 /* NamedExports */;
18537     }
18538     ts.isNamedImportsOrExports = isNamedImportsOrExports;
18539     function getLeftmostAccessExpression(expr) {
18540         while (isAccessExpression(expr)) {
18541             expr = expr.expression;
18542         }
18543         return expr;
18544     }
18545     ts.getLeftmostAccessExpression = getLeftmostAccessExpression;
18546     function getLeftmostExpression(node, stopAtCallExpressions) {
18547         while (true) {
18548             switch (node.kind) {
18549                 case 215 /* PostfixUnaryExpression */:
18550                     node = node.operand;
18551                     continue;
18552                 case 216 /* BinaryExpression */:
18553                     node = node.left;
18554                     continue;
18555                 case 217 /* ConditionalExpression */:
18556                     node = node.condition;
18557                     continue;
18558                 case 205 /* TaggedTemplateExpression */:
18559                     node = node.tag;
18560                     continue;
18561                 case 203 /* CallExpression */:
18562                     if (stopAtCallExpressions) {
18563                         return node;
18564                     }
18565                 // falls through
18566                 case 224 /* AsExpression */:
18567                 case 202 /* ElementAccessExpression */:
18568                 case 201 /* PropertyAccessExpression */:
18569                 case 225 /* NonNullExpression */:
18570                 case 336 /* PartiallyEmittedExpression */:
18571                     node = node.expression;
18572                     continue;
18573             }
18574             return node;
18575         }
18576     }
18577     ts.getLeftmostExpression = getLeftmostExpression;
18578     function Symbol(flags, name) {
18579         this.flags = flags;
18580         this.escapedName = name;
18581         this.declarations = undefined;
18582         this.valueDeclaration = undefined;
18583         this.id = undefined;
18584         this.mergeId = undefined;
18585         this.parent = undefined;
18586     }
18587     function Type(checker, flags) {
18588         this.flags = flags;
18589         if (ts.Debug.isDebugging || ts.tracing) {
18590             this.checker = checker;
18591         }
18592     }
18593     function Signature(checker, flags) {
18594         this.flags = flags;
18595         if (ts.Debug.isDebugging) {
18596             this.checker = checker;
18597         }
18598     }
18599     function Node(kind, pos, end) {
18600         this.pos = pos;
18601         this.end = end;
18602         this.kind = kind;
18603         this.id = 0;
18604         this.flags = 0 /* None */;
18605         this.modifierFlagsCache = 0 /* None */;
18606         this.transformFlags = 0 /* None */;
18607         this.parent = undefined;
18608         this.original = undefined;
18609     }
18610     function Token(kind, pos, end) {
18611         this.pos = pos;
18612         this.end = end;
18613         this.kind = kind;
18614         this.id = 0;
18615         this.flags = 0 /* None */;
18616         this.transformFlags = 0 /* None */;
18617         this.parent = undefined;
18618     }
18619     function Identifier(kind, pos, end) {
18620         this.pos = pos;
18621         this.end = end;
18622         this.kind = kind;
18623         this.id = 0;
18624         this.flags = 0 /* None */;
18625         this.transformFlags = 0 /* None */;
18626         this.parent = undefined;
18627         this.original = undefined;
18628         this.flowNode = undefined;
18629     }
18630     function SourceMapSource(fileName, text, skipTrivia) {
18631         this.fileName = fileName;
18632         this.text = text;
18633         this.skipTrivia = skipTrivia || (function (pos) { return pos; });
18634     }
18635     // eslint-disable-next-line prefer-const
18636     ts.objectAllocator = {
18637         getNodeConstructor: function () { return Node; },
18638         getTokenConstructor: function () { return Token; },
18639         getIdentifierConstructor: function () { return Identifier; },
18640         getPrivateIdentifierConstructor: function () { return Node; },
18641         getSourceFileConstructor: function () { return Node; },
18642         getSymbolConstructor: function () { return Symbol; },
18643         getTypeConstructor: function () { return Type; },
18644         getSignatureConstructor: function () { return Signature; },
18645         getSourceMapSourceConstructor: function () { return SourceMapSource; },
18646     };
18647     function setObjectAllocator(alloc) {
18648         ts.objectAllocator = alloc;
18649     }
18650     ts.setObjectAllocator = setObjectAllocator;
18651     function formatStringFromArgs(text, args, baseIndex) {
18652         if (baseIndex === void 0) { baseIndex = 0; }
18653         return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); });
18654     }
18655     ts.formatStringFromArgs = formatStringFromArgs;
18656     /* @internal */
18657     function setLocalizedDiagnosticMessages(messages) {
18658         ts.localizedDiagnosticMessages = messages;
18659     }
18660     ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages;
18661     function getLocaleSpecificMessage(message) {
18662         return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
18663     }
18664     ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
18665     function createDetachedDiagnostic(fileName, start, length, message) {
18666         assertDiagnosticLocation(/*file*/ undefined, start, length);
18667         var text = getLocaleSpecificMessage(message);
18668         if (arguments.length > 4) {
18669             text = formatStringFromArgs(text, arguments, 4);
18670         }
18671         return {
18672             file: undefined,
18673             start: start,
18674             length: length,
18675             messageText: text,
18676             category: message.category,
18677             code: message.code,
18678             reportsUnnecessary: message.reportsUnnecessary,
18679             fileName: fileName,
18680         };
18681     }
18682     ts.createDetachedDiagnostic = createDetachedDiagnostic;
18683     function isDiagnosticWithDetachedLocation(diagnostic) {
18684         return diagnostic.file === undefined
18685             && diagnostic.start !== undefined
18686             && diagnostic.length !== undefined
18687             && typeof diagnostic.fileName === "string";
18688     }
18689     function attachFileToDiagnostic(diagnostic, file) {
18690         var fileName = file.fileName || "";
18691         var length = file.text.length;
18692         ts.Debug.assertEqual(diagnostic.fileName, fileName);
18693         ts.Debug.assertLessThanOrEqual(diagnostic.start, length);
18694         ts.Debug.assertLessThanOrEqual(diagnostic.start + diagnostic.length, length);
18695         var diagnosticWithLocation = {
18696             file: file,
18697             start: diagnostic.start,
18698             length: diagnostic.length,
18699             messageText: diagnostic.messageText,
18700             category: diagnostic.category,
18701             code: diagnostic.code,
18702             reportsUnnecessary: diagnostic.reportsUnnecessary
18703         };
18704         if (diagnostic.relatedInformation) {
18705             diagnosticWithLocation.relatedInformation = [];
18706             for (var _i = 0, _a = diagnostic.relatedInformation; _i < _a.length; _i++) {
18707                 var related = _a[_i];
18708                 if (isDiagnosticWithDetachedLocation(related) && related.fileName === fileName) {
18709                     ts.Debug.assertLessThanOrEqual(related.start, length);
18710                     ts.Debug.assertLessThanOrEqual(related.start + related.length, length);
18711                     diagnosticWithLocation.relatedInformation.push(attachFileToDiagnostic(related, file));
18712                 }
18713                 else {
18714                     diagnosticWithLocation.relatedInformation.push(related);
18715                 }
18716             }
18717         }
18718         return diagnosticWithLocation;
18719     }
18720     function attachFileToDiagnostics(diagnostics, file) {
18721         var diagnosticsWithLocation = [];
18722         for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
18723             var diagnostic = diagnostics_1[_i];
18724             diagnosticsWithLocation.push(attachFileToDiagnostic(diagnostic, file));
18725         }
18726         return diagnosticsWithLocation;
18727     }
18728     ts.attachFileToDiagnostics = attachFileToDiagnostics;
18729     function createFileDiagnostic(file, start, length, message) {
18730         assertDiagnosticLocation(file, start, length);
18731         var text = getLocaleSpecificMessage(message);
18732         if (arguments.length > 4) {
18733             text = formatStringFromArgs(text, arguments, 4);
18734         }
18735         return {
18736             file: file,
18737             start: start,
18738             length: length,
18739             messageText: text,
18740             category: message.category,
18741             code: message.code,
18742             reportsUnnecessary: message.reportsUnnecessary,
18743             reportsDeprecated: message.reportsDeprecated
18744         };
18745     }
18746     ts.createFileDiagnostic = createFileDiagnostic;
18747     function formatMessage(_dummy, message) {
18748         var text = getLocaleSpecificMessage(message);
18749         if (arguments.length > 2) {
18750             text = formatStringFromArgs(text, arguments, 2);
18751         }
18752         return text;
18753     }
18754     ts.formatMessage = formatMessage;
18755     function createCompilerDiagnostic(message) {
18756         var text = getLocaleSpecificMessage(message);
18757         if (arguments.length > 1) {
18758             text = formatStringFromArgs(text, arguments, 1);
18759         }
18760         return {
18761             file: undefined,
18762             start: undefined,
18763             length: undefined,
18764             messageText: text,
18765             category: message.category,
18766             code: message.code,
18767             reportsUnnecessary: message.reportsUnnecessary,
18768             reportsDeprecated: message.reportsDeprecated
18769         };
18770     }
18771     ts.createCompilerDiagnostic = createCompilerDiagnostic;
18772     function createCompilerDiagnosticFromMessageChain(chain, relatedInformation) {
18773         return {
18774             file: undefined,
18775             start: undefined,
18776             length: undefined,
18777             code: chain.code,
18778             category: chain.category,
18779             messageText: chain.next ? chain : chain.messageText,
18780             relatedInformation: relatedInformation
18781         };
18782     }
18783     ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
18784     function chainDiagnosticMessages(details, message) {
18785         var text = getLocaleSpecificMessage(message);
18786         if (arguments.length > 2) {
18787             text = formatStringFromArgs(text, arguments, 2);
18788         }
18789         return {
18790             messageText: text,
18791             category: message.category,
18792             code: message.code,
18793             next: details === undefined || Array.isArray(details) ? details : [details]
18794         };
18795     }
18796     ts.chainDiagnosticMessages = chainDiagnosticMessages;
18797     function concatenateDiagnosticMessageChains(headChain, tailChain) {
18798         var lastChain = headChain;
18799         while (lastChain.next) {
18800             lastChain = lastChain.next[0];
18801         }
18802         lastChain.next = [tailChain];
18803     }
18804     ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
18805     function getDiagnosticFilePath(diagnostic) {
18806         return diagnostic.file ? diagnostic.file.path : undefined;
18807     }
18808     function compareDiagnostics(d1, d2) {
18809         return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
18810             compareRelatedInformation(d1, d2) ||
18811             0 /* EqualTo */;
18812     }
18813     ts.compareDiagnostics = compareDiagnostics;
18814     function compareDiagnosticsSkipRelatedInformation(d1, d2) {
18815         return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
18816             ts.compareValues(d1.start, d2.start) ||
18817             ts.compareValues(d1.length, d2.length) ||
18818             ts.compareValues(d1.code, d2.code) ||
18819             compareMessageText(d1.messageText, d2.messageText) ||
18820             0 /* EqualTo */;
18821     }
18822     ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
18823     function compareRelatedInformation(d1, d2) {
18824         if (!d1.relatedInformation && !d2.relatedInformation) {
18825             return 0 /* EqualTo */;
18826         }
18827         if (d1.relatedInformation && d2.relatedInformation) {
18828             return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
18829                 var d2i = d2.relatedInformation[index];
18830                 return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
18831             }) || 0 /* EqualTo */;
18832         }
18833         return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
18834     }
18835     function compareMessageText(t1, t2) {
18836         if (typeof t1 === "string" && typeof t2 === "string") {
18837             return ts.compareStringsCaseSensitive(t1, t2);
18838         }
18839         else if (typeof t1 === "string") {
18840             return -1 /* LessThan */;
18841         }
18842         else if (typeof t2 === "string") {
18843             return 1 /* GreaterThan */;
18844         }
18845         var res = ts.compareStringsCaseSensitive(t1.messageText, t2.messageText);
18846         if (res) {
18847             return res;
18848         }
18849         if (!t1.next && !t2.next) {
18850             return 0 /* EqualTo */;
18851         }
18852         if (!t1.next) {
18853             return -1 /* LessThan */;
18854         }
18855         if (!t2.next) {
18856             return 1 /* GreaterThan */;
18857         }
18858         var len = Math.min(t1.next.length, t2.next.length);
18859         for (var i = 0; i < len; i++) {
18860             res = compareMessageText(t1.next[i], t2.next[i]);
18861             if (res) {
18862                 return res;
18863             }
18864         }
18865         if (t1.next.length < t2.next.length) {
18866             return -1 /* LessThan */;
18867         }
18868         else if (t1.next.length > t2.next.length) {
18869             return 1 /* GreaterThan */;
18870         }
18871         return 0 /* EqualTo */;
18872     }
18873     function getLanguageVariant(scriptKind) {
18874         // .tsx and .jsx files are treated as jsx language variant.
18875         return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */;
18876     }
18877     ts.getLanguageVariant = getLanguageVariant;
18878     function getEmitScriptTarget(compilerOptions) {
18879         return compilerOptions.target || 0 /* ES3 */;
18880     }
18881     ts.getEmitScriptTarget = getEmitScriptTarget;
18882     function getEmitModuleKind(compilerOptions) {
18883         return typeof compilerOptions.module === "number" ?
18884             compilerOptions.module :
18885             getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
18886     }
18887     ts.getEmitModuleKind = getEmitModuleKind;
18888     function getEmitModuleResolutionKind(compilerOptions) {
18889         var moduleResolution = compilerOptions.moduleResolution;
18890         if (moduleResolution === undefined) {
18891             moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
18892         }
18893         return moduleResolution;
18894     }
18895     ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
18896     function hasJsonModuleEmitEnabled(options) {
18897         switch (getEmitModuleKind(options)) {
18898             case ts.ModuleKind.CommonJS:
18899             case ts.ModuleKind.AMD:
18900             case ts.ModuleKind.ES2015:
18901             case ts.ModuleKind.ES2020:
18902             case ts.ModuleKind.ESNext:
18903                 return true;
18904             default:
18905                 return false;
18906         }
18907     }
18908     ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
18909     function unreachableCodeIsError(options) {
18910         return options.allowUnreachableCode === false;
18911     }
18912     ts.unreachableCodeIsError = unreachableCodeIsError;
18913     function unusedLabelIsError(options) {
18914         return options.allowUnusedLabels === false;
18915     }
18916     ts.unusedLabelIsError = unusedLabelIsError;
18917     function getAreDeclarationMapsEnabled(options) {
18918         return !!(getEmitDeclarations(options) && options.declarationMap);
18919     }
18920     ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
18921     function getAllowSyntheticDefaultImports(compilerOptions) {
18922         var moduleKind = getEmitModuleKind(compilerOptions);
18923         return compilerOptions.allowSyntheticDefaultImports !== undefined
18924             ? compilerOptions.allowSyntheticDefaultImports
18925             : compilerOptions.esModuleInterop ||
18926                 moduleKind === ts.ModuleKind.System;
18927     }
18928     ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
18929     function getEmitDeclarations(compilerOptions) {
18930         return !!(compilerOptions.declaration || compilerOptions.composite);
18931     }
18932     ts.getEmitDeclarations = getEmitDeclarations;
18933     function shouldPreserveConstEnums(compilerOptions) {
18934         return !!(compilerOptions.preserveConstEnums || compilerOptions.isolatedModules);
18935     }
18936     ts.shouldPreserveConstEnums = shouldPreserveConstEnums;
18937     function isIncrementalCompilation(options) {
18938         return !!(options.incremental || options.composite);
18939     }
18940     ts.isIncrementalCompilation = isIncrementalCompilation;
18941     function getStrictOptionValue(compilerOptions, flag) {
18942         return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
18943     }
18944     ts.getStrictOptionValue = getStrictOptionValue;
18945     function getAllowJSCompilerOption(compilerOptions) {
18946         return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs;
18947     }
18948     ts.getAllowJSCompilerOption = getAllowJSCompilerOption;
18949     function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
18950         return oldOptions !== newOptions &&
18951             ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
18952     }
18953     ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
18954     function compilerOptionsAffectEmit(newOptions, oldOptions) {
18955         return oldOptions !== newOptions &&
18956             ts.affectsEmitOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
18957     }
18958     ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit;
18959     function getCompilerOptionValue(options, option) {
18960         return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
18961     }
18962     ts.getCompilerOptionValue = getCompilerOptionValue;
18963     function getJSXTransformEnabled(options) {
18964         var jsx = options.jsx;
18965         return jsx === 2 /* React */ || jsx === 4 /* ReactJSX */ || jsx === 5 /* ReactJSXDev */;
18966     }
18967     ts.getJSXTransformEnabled = getJSXTransformEnabled;
18968     function getJSXImplicitImportBase(compilerOptions, file) {
18969         var jsxImportSourcePragmas = file === null || file === void 0 ? void 0 : file.pragmas.get("jsximportsource");
18970         var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[0] : jsxImportSourcePragmas;
18971         return compilerOptions.jsx === 4 /* ReactJSX */ ||
18972             compilerOptions.jsx === 5 /* ReactJSXDev */ ||
18973             compilerOptions.jsxImportSource ||
18974             jsxImportSourcePragma ?
18975             (jsxImportSourcePragma === null || jsxImportSourcePragma === void 0 ? void 0 : jsxImportSourcePragma.arguments.factory) || compilerOptions.jsxImportSource || "react" :
18976             undefined;
18977     }
18978     ts.getJSXImplicitImportBase = getJSXImplicitImportBase;
18979     function getJSXRuntimeImport(base, options) {
18980         return base ? base + "/" + (options.jsx === 5 /* ReactJSXDev */ ? "jsx-dev-runtime" : "jsx-runtime") : undefined;
18981     }
18982     ts.getJSXRuntimeImport = getJSXRuntimeImport;
18983     function hasZeroOrOneAsteriskCharacter(str) {
18984         var seenAsterisk = false;
18985         for (var i = 0; i < str.length; i++) {
18986             if (str.charCodeAt(i) === 42 /* asterisk */) {
18987                 if (!seenAsterisk) {
18988                     seenAsterisk = true;
18989                 }
18990                 else {
18991                     // have already seen asterisk
18992                     return false;
18993                 }
18994             }
18995         }
18996         return true;
18997     }
18998     ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
18999     function createSymlinkCache(cwd, getCanonicalFileName) {
19000         var symlinkedDirectories;
19001         var symlinkedDirectoriesByRealpath;
19002         var symlinkedFiles;
19003         return {
19004             getSymlinkedFiles: function () { return symlinkedFiles; },
19005             getSymlinkedDirectories: function () { return symlinkedDirectories; },
19006             getSymlinkedDirectoriesByRealpath: function () { return symlinkedDirectoriesByRealpath; },
19007             setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); },
19008             setSymlinkedDirectory: function (symlink, real) {
19009                 // Large, interconnected dependency graphs in pnpm will have a huge number of symlinks
19010                 // where both the realpath and the symlink path are inside node_modules/.pnpm. Since
19011                 // this path is never a candidate for a module specifier, we can ignore it entirely.
19012                 var symlinkPath = ts.toPath(symlink, cwd, getCanonicalFileName);
19013                 if (!containsIgnoredPath(symlinkPath)) {
19014                     symlinkPath = ts.ensureTrailingDirectorySeparator(symlinkPath);
19015                     if (real !== false && !(symlinkedDirectories === null || symlinkedDirectories === void 0 ? void 0 : symlinkedDirectories.has(symlinkPath))) {
19016                         (symlinkedDirectoriesByRealpath || (symlinkedDirectoriesByRealpath = ts.createMultiMap())).add(ts.ensureTrailingDirectorySeparator(real.realPath), symlink);
19017                     }
19018                     (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(symlinkPath, real);
19019                 }
19020             }
19021         };
19022     }
19023     ts.createSymlinkCache = createSymlinkCache;
19024     function discoverProbableSymlinks(files, getCanonicalFileName, cwd) {
19025         var cache = createSymlinkCache(cwd, getCanonicalFileName);
19026         var symlinks = ts.flatten(ts.mapDefined(files, function (sf) {
19027             return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) {
19028                 return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined;
19029             })));
19030         }));
19031         for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) {
19032             var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1];
19033             var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1];
19034             if (commonResolved && commonOriginal) {
19035                 cache.setSymlinkedDirectory(commonOriginal, { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) });
19036             }
19037         }
19038         return cache;
19039     }
19040     ts.discoverProbableSymlinks = discoverProbableSymlinks;
19041     function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
19042         var aParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(a, cwd));
19043         var bParts = ts.getPathComponents(ts.getNormalizedAbsolutePath(b, cwd));
19044         var isDirectory = false;
19045         while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
19046             !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
19047             getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) {
19048             aParts.pop();
19049             bParts.pop();
19050             isDirectory = true;
19051         }
19052         return isDirectory ? [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)] : undefined;
19053     }
19054     // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
19055     // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
19056     function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
19057         return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@");
19058     }
19059     function stripLeadingDirectorySeparator(s) {
19060         return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
19061     }
19062     function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
19063         var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
19064         return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
19065     }
19066     ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix;
19067     // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
19068     // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
19069     // proof.
19070     var reservedCharacterPattern = /[^\w\s\/]/g;
19071     function regExpEscape(text) {
19072         return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
19073     }
19074     ts.regExpEscape = regExpEscape;
19075     function escapeRegExpCharacter(match) {
19076         return "\\" + match;
19077     }
19078     var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
19079     ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
19080     var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))";
19081     var filesMatcher = {
19082         /**
19083          * Matches any single directory segment unless it is the last segment and a .min.js file
19084          * Breakdown:
19085          *  [^./]                   # matches everything up to the first . character (excluding directory separators)
19086          *  (\\.(?!min\\.js$))?     # matches . characters but not if they are part of the .min.js file extension
19087          */
19088         singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
19089         /**
19090          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
19091          * files or directories, does not match subdirectories that start with a . character
19092          */
19093         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
19094         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); }
19095     };
19096     var directoriesMatcher = {
19097         singleAsteriskRegexFragment: "[^/]*",
19098         /**
19099          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
19100          * files or directories, does not match subdirectories that start with a . character
19101          */
19102         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
19103         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
19104     };
19105     var excludeMatcher = {
19106         singleAsteriskRegexFragment: "[^/]*",
19107         doubleAsteriskRegexFragment: "(/.+?)?",
19108         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
19109     };
19110     var wildcardMatchers = {
19111         files: filesMatcher,
19112         directories: directoriesMatcher,
19113         exclude: excludeMatcher
19114     };
19115     function getRegularExpressionForWildcard(specs, basePath, usage) {
19116         var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
19117         if (!patterns || !patterns.length) {
19118             return undefined;
19119         }
19120         var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
19121         // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
19122         var terminator = usage === "exclude" ? "($|/)" : "$";
19123         return "^(" + pattern + ")" + terminator;
19124     }
19125     ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
19126     function getRegularExpressionsForWildcards(specs, basePath, usage) {
19127         if (specs === undefined || specs.length === 0) {
19128             return undefined;
19129         }
19130         return ts.flatMap(specs, function (spec) {
19131             return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
19132         });
19133     }
19134     ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards;
19135     /**
19136      * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
19137      * and does not contain any glob characters itself.
19138      */
19139     function isImplicitGlob(lastPathComponent) {
19140         return !/[.*?]/.test(lastPathComponent);
19141     }
19142     ts.isImplicitGlob = isImplicitGlob;
19143     function getPatternFromSpec(spec, basePath, usage) {
19144         var pattern = spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
19145         return pattern && "^(" + pattern + ")" + (usage === "exclude" ? "($|/)" : "$");
19146     }
19147     ts.getPatternFromSpec = getPatternFromSpec;
19148     function getSubPatternFromSpec(spec, basePath, usage, _a) {
19149         var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
19150         var subpattern = "";
19151         var hasWrittenComponent = false;
19152         var components = ts.getNormalizedPathComponents(spec, basePath);
19153         var lastComponent = ts.last(components);
19154         if (usage !== "exclude" && lastComponent === "**") {
19155             return undefined;
19156         }
19157         // getNormalizedPathComponents includes the separator for the root component.
19158         // We need to remove to create our regex correctly.
19159         components[0] = ts.removeTrailingDirectorySeparator(components[0]);
19160         if (isImplicitGlob(lastComponent)) {
19161             components.push("**", "*");
19162         }
19163         var optionalCount = 0;
19164         for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
19165             var component = components_1[_i];
19166             if (component === "**") {
19167                 subpattern += doubleAsteriskRegexFragment;
19168             }
19169             else {
19170                 if (usage === "directories") {
19171                     subpattern += "(";
19172                     optionalCount++;
19173                 }
19174                 if (hasWrittenComponent) {
19175                     subpattern += ts.directorySeparator;
19176                 }
19177                 if (usage !== "exclude") {
19178                     var componentPattern = "";
19179                     // The * and ? wildcards should not match directories or files that start with . if they
19180                     // appear first in a component. Dotted directories and files can be included explicitly
19181                     // like so: **/.*/.*
19182                     if (component.charCodeAt(0) === 42 /* asterisk */) {
19183                         componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
19184                         component = component.substr(1);
19185                     }
19186                     else if (component.charCodeAt(0) === 63 /* question */) {
19187                         componentPattern += "[^./]";
19188                         component = component.substr(1);
19189                     }
19190                     componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
19191                     // Patterns should not include subfolders like node_modules unless they are
19192                     // explicitly included as part of the path.
19193                     //
19194                     // As an optimization, if the component pattern is the same as the component,
19195                     // then there definitely were no wildcard characters and we do not need to
19196                     // add the exclusion pattern.
19197                     if (componentPattern !== component) {
19198                         subpattern += implicitExcludePathRegexPattern;
19199                     }
19200                     subpattern += componentPattern;
19201                 }
19202                 else {
19203                     subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
19204                 }
19205             }
19206             hasWrittenComponent = true;
19207         }
19208         while (optionalCount > 0) {
19209             subpattern += ")?";
19210             optionalCount--;
19211         }
19212         return subpattern;
19213     }
19214     function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
19215         return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
19216     }
19217     /** @param path directory of the tsconfig.json */
19218     function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
19219         path = ts.normalizePath(path);
19220         currentDirectory = ts.normalizePath(currentDirectory);
19221         var absolutePath = ts.combinePaths(currentDirectory, path);
19222         return {
19223             includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }),
19224             includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
19225             includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
19226             excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
19227             basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
19228         };
19229     }
19230     ts.getFileMatcherPatterns = getFileMatcherPatterns;
19231     function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
19232         return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
19233     }
19234     ts.getRegexFromPattern = getRegexFromPattern;
19235     /** @param path directory of the tsconfig.json */
19236     function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
19237         path = ts.normalizePath(path);
19238         currentDirectory = ts.normalizePath(currentDirectory);
19239         var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
19240         var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); });
19241         var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
19242         var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
19243         // Associate an array of results with each include regex. This keeps results in order of the "include" order.
19244         // If there are no "includes", then just put everything in results[0].
19245         var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
19246         var visited = new ts.Map();
19247         var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
19248         for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
19249             var basePath = _a[_i];
19250             visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth);
19251         }
19252         return ts.flatten(results);
19253         function visitDirectory(path, absolutePath, depth) {
19254             var canonicalPath = toCanonical(realpath(absolutePath));
19255             if (visited.has(canonicalPath))
19256                 return;
19257             visited.set(canonicalPath, true);
19258             var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
19259             var _loop_1 = function (current) {
19260                 var name = ts.combinePaths(path, current);
19261                 var absoluteName = ts.combinePaths(absolutePath, current);
19262                 if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
19263                     return "continue";
19264                 if (excludeRegex && excludeRegex.test(absoluteName))
19265                     return "continue";
19266                 if (!includeFileRegexes) {
19267                     results[0].push(name);
19268                 }
19269                 else {
19270                     var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
19271                     if (includeIndex !== -1) {
19272                         results[includeIndex].push(name);
19273                     }
19274                 }
19275             };
19276             for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
19277                 var current = _b[_i];
19278                 _loop_1(current);
19279             }
19280             if (depth !== undefined) {
19281                 depth--;
19282                 if (depth === 0) {
19283                     return;
19284                 }
19285             }
19286             for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
19287                 var current = _d[_c];
19288                 var name = ts.combinePaths(path, current);
19289                 var absoluteName = ts.combinePaths(absolutePath, current);
19290                 if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
19291                     (!excludeRegex || !excludeRegex.test(absoluteName))) {
19292                     visitDirectory(name, absoluteName, depth);
19293                 }
19294             }
19295         }
19296     }
19297     ts.matchFiles = matchFiles;
19298     /**
19299      * Computes the unique non-wildcard base paths amongst the provided include patterns.
19300      */
19301     function getBasePaths(path, includes, useCaseSensitiveFileNames) {
19302         // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
19303         var basePaths = [path];
19304         if (includes) {
19305             // Storage for literal base paths amongst the include patterns.
19306             var includeBasePaths = [];
19307             for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) {
19308                 var include = includes_1[_i];
19309                 // We also need to check the relative paths by converting them to absolute and normalizing
19310                 // in case they escape the base path (e.g "..\somedirectory")
19311                 var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include));
19312                 // Append the literal and canonical candidate base paths.
19313                 includeBasePaths.push(getIncludeBasePath(absolute));
19314             }
19315             // Sort the offsets array using either the literal or canonical path representations.
19316             includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames));
19317             var _loop_2 = function (includeBasePath) {
19318                 if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
19319                     basePaths.push(includeBasePath);
19320                 }
19321             };
19322             // Iterate over each include base path and include unique base paths that are not a
19323             // subpath of an existing base path
19324             for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
19325                 var includeBasePath = includeBasePaths_1[_a];
19326                 _loop_2(includeBasePath);
19327             }
19328         }
19329         return basePaths;
19330     }
19331     function getIncludeBasePath(absolute) {
19332         var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
19333         if (wildcardOffset < 0) {
19334             // No "*" or "?" in the path
19335             return !ts.hasExtension(absolute)
19336                 ? absolute
19337                 : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
19338         }
19339         return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
19340     }
19341     function ensureScriptKind(fileName, scriptKind) {
19342         // Using scriptKind as a condition handles both:
19343         // - 'scriptKind' is unspecified and thus it is `undefined`
19344         // - 'scriptKind' is set and it is `Unknown` (0)
19345         // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
19346         // to get the ScriptKind from the file name. If it cannot be resolved
19347         // from the file name then the default 'TS' script kind is returned.
19348         return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */;
19349     }
19350     ts.ensureScriptKind = ensureScriptKind;
19351     function getScriptKindFromFileName(fileName) {
19352         var ext = fileName.substr(fileName.lastIndexOf("."));
19353         switch (ext.toLowerCase()) {
19354             case ".js" /* Js */:
19355                 return 1 /* JS */;
19356             case ".jsx" /* Jsx */:
19357                 return 2 /* JSX */;
19358             case ".ts" /* Ts */:
19359                 return 3 /* TS */;
19360             case ".tsx" /* Tsx */:
19361                 return 4 /* TSX */;
19362             case ".json" /* Json */:
19363                 return 6 /* JSON */;
19364             default:
19365                 return 0 /* Unknown */;
19366         }
19367     }
19368     ts.getScriptKindFromFileName = getScriptKindFromFileName;
19369     /**
19370      *  List of supported extensions in order of file resolution precedence.
19371      */
19372     ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */];
19373     ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */];
19374     /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
19375     ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
19376     ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
19377     ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
19378     var allSupportedExtensions = __spreadArray(__spreadArray([], ts.supportedTSExtensions), ts.supportedJSExtensions);
19379     var allSupportedExtensionsWithJson = __spreadArray(__spreadArray(__spreadArray([], ts.supportedTSExtensions), ts.supportedJSExtensions), [".json" /* Json */]);
19380     function getSupportedExtensions(options, extraFileExtensions) {
19381         var needJsExtensions = options && getAllowJSCompilerOption(options);
19382         if (!extraFileExtensions || extraFileExtensions.length === 0) {
19383             return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
19384         }
19385         var extensions = __spreadArray(__spreadArray([], needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions), ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
19386         return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
19387     }
19388     ts.getSupportedExtensions = getSupportedExtensions;
19389     function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) {
19390         if (!options || !options.resolveJsonModule) {
19391             return supportedExtensions;
19392         }
19393         if (supportedExtensions === allSupportedExtensions) {
19394             return allSupportedExtensionsWithJson;
19395         }
19396         if (supportedExtensions === ts.supportedTSExtensions) {
19397             return ts.supportedTSExtensionsWithJson;
19398         }
19399         return __spreadArray(__spreadArray([], supportedExtensions), [".json" /* Json */]);
19400     }
19401     ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule;
19402     function isJSLike(scriptKind) {
19403         return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
19404     }
19405     function hasJSFileExtension(fileName) {
19406         return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
19407     }
19408     ts.hasJSFileExtension = hasJSFileExtension;
19409     function hasTSFileExtension(fileName) {
19410         return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
19411     }
19412     ts.hasTSFileExtension = hasTSFileExtension;
19413     function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
19414         if (!fileName) {
19415             return false;
19416         }
19417         var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
19418         for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) {
19419             var extension = _a[_i];
19420             if (ts.fileExtensionIs(fileName, extension)) {
19421                 return true;
19422             }
19423         }
19424         return false;
19425     }
19426     ts.isSupportedSourceFileName = isSupportedSourceFileName;
19427     function numberOfDirectorySeparators(str) {
19428         var match = str.match(/\//g);
19429         return match ? match.length : 0;
19430     }
19431     function compareNumberOfDirectorySeparators(path1, path2) {
19432         return ts.compareValues(numberOfDirectorySeparators(path1), numberOfDirectorySeparators(path2));
19433     }
19434     ts.compareNumberOfDirectorySeparators = compareNumberOfDirectorySeparators;
19435     /**
19436      * Extension boundaries by priority. Lower numbers indicate higher priorities, and are
19437      * aligned to the offset of the highest priority extension in the
19438      * allSupportedExtensions array.
19439      */
19440     var ExtensionPriority;
19441     (function (ExtensionPriority) {
19442         ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
19443         ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
19444         ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
19445         ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
19446     })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
19447     function getExtensionPriority(path, supportedExtensions) {
19448         for (var i = supportedExtensions.length - 1; i >= 0; i--) {
19449             if (ts.fileExtensionIs(path, supportedExtensions[i])) {
19450                 return adjustExtensionPriority(i, supportedExtensions);
19451             }
19452         }
19453         // If its not in the list of supported extensions, this is likely a
19454         // TypeScript file with a non-ts extension
19455         return 0 /* Highest */;
19456     }
19457     ts.getExtensionPriority = getExtensionPriority;
19458     /**
19459      * Adjusts an extension priority to be the highest priority within the same range.
19460      */
19461     function adjustExtensionPriority(extensionPriority, supportedExtensions) {
19462         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
19463             return 0 /* TypeScriptFiles */;
19464         }
19465         else if (extensionPriority < supportedExtensions.length) {
19466             return 2 /* DeclarationAndJavaScriptFiles */;
19467         }
19468         else {
19469             return supportedExtensions.length;
19470         }
19471     }
19472     ts.adjustExtensionPriority = adjustExtensionPriority;
19473     /**
19474      * Gets the next lowest extension priority for a given priority.
19475      */
19476     function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
19477         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
19478             return 2 /* DeclarationAndJavaScriptFiles */;
19479         }
19480         else {
19481             return supportedExtensions.length;
19482         }
19483     }
19484     ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
19485     var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
19486     function removeFileExtension(path) {
19487         for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
19488             var ext = extensionsToRemove_1[_i];
19489             var extensionless = tryRemoveExtension(path, ext);
19490             if (extensionless !== undefined) {
19491                 return extensionless;
19492             }
19493         }
19494         return path;
19495     }
19496     ts.removeFileExtension = removeFileExtension;
19497     function tryRemoveExtension(path, extension) {
19498         return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
19499     }
19500     ts.tryRemoveExtension = tryRemoveExtension;
19501     function removeExtension(path, extension) {
19502         return path.substring(0, path.length - extension.length);
19503     }
19504     ts.removeExtension = removeExtension;
19505     function changeExtension(path, newExtension) {
19506         return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
19507     }
19508     ts.changeExtension = changeExtension;
19509     function tryParsePattern(pattern) {
19510         // This should be verified outside of here and a proper error thrown.
19511         ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
19512         var indexOfStar = pattern.indexOf("*");
19513         return indexOfStar === -1 ? undefined : {
19514             prefix: pattern.substr(0, indexOfStar),
19515             suffix: pattern.substr(indexOfStar + 1)
19516         };
19517     }
19518     ts.tryParsePattern = tryParsePattern;
19519     function positionIsSynthesized(pos) {
19520         // This is a fast way of testing the following conditions:
19521         //  pos === undefined || pos === null || isNaN(pos) || pos < 0;
19522         return !(pos >= 0);
19523     }
19524     ts.positionIsSynthesized = positionIsSynthesized;
19525     /** True if an extension is one of the supported TypeScript extensions. */
19526     function extensionIsTS(ext) {
19527         return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
19528     }
19529     ts.extensionIsTS = extensionIsTS;
19530     function resolutionExtensionIsTSOrJson(ext) {
19531         return extensionIsTS(ext) || ext === ".json" /* Json */;
19532     }
19533     ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
19534     /**
19535      * Gets the extension from a path.
19536      * Path must have a valid extension.
19537      */
19538     function extensionFromPath(path) {
19539         var ext = tryGetExtensionFromPath(path);
19540         return ext !== undefined ? ext : ts.Debug.fail("File " + path + " has unknown extension.");
19541     }
19542     ts.extensionFromPath = extensionFromPath;
19543     function isAnySupportedFileExtension(path) {
19544         return tryGetExtensionFromPath(path) !== undefined;
19545     }
19546     ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
19547     function tryGetExtensionFromPath(path) {
19548         return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
19549     }
19550     ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
19551     function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
19552         return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
19553     }
19554     ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
19555     ts.emptyFileSystemEntries = {
19556         files: ts.emptyArray,
19557         directories: ts.emptyArray
19558     };
19559     /**
19560      * patternStrings contains both pattern strings (containing "*") and regular strings.
19561      * Return an exact match if possible, or a pattern match, or undefined.
19562      * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
19563      */
19564     function matchPatternOrExact(patternStrings, candidate) {
19565         var patterns = [];
19566         for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
19567             var patternString = patternStrings_1[_i];
19568             if (!hasZeroOrOneAsteriskCharacter(patternString))
19569                 continue;
19570             var pattern = tryParsePattern(patternString);
19571             if (pattern) {
19572                 patterns.push(pattern);
19573             }
19574             else if (patternString === candidate) {
19575                 // pattern was matched as is - no need to search further
19576                 return patternString;
19577             }
19578         }
19579         return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
19580     }
19581     ts.matchPatternOrExact = matchPatternOrExact;
19582     function sliceAfter(arr, value) {
19583         var index = arr.indexOf(value);
19584         ts.Debug.assert(index !== -1);
19585         return arr.slice(index);
19586     }
19587     ts.sliceAfter = sliceAfter;
19588     function addRelatedInfo(diagnostic) {
19589         var _a;
19590         var relatedInformation = [];
19591         for (var _i = 1; _i < arguments.length; _i++) {
19592             relatedInformation[_i - 1] = arguments[_i];
19593         }
19594         if (!relatedInformation.length) {
19595             return diagnostic;
19596         }
19597         if (!diagnostic.relatedInformation) {
19598             diagnostic.relatedInformation = [];
19599         }
19600         ts.Debug.assert(diagnostic.relatedInformation !== ts.emptyArray, "Diagnostic had empty array singleton for related info, but is still being constructed!");
19601         (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
19602         return diagnostic;
19603     }
19604     ts.addRelatedInfo = addRelatedInfo;
19605     function minAndMax(arr, getValue) {
19606         ts.Debug.assert(arr.length !== 0);
19607         var min = getValue(arr[0]);
19608         var max = min;
19609         for (var i = 1; i < arr.length; i++) {
19610             var value = getValue(arr[i]);
19611             if (value < min) {
19612                 min = value;
19613             }
19614             else if (value > max) {
19615                 max = value;
19616             }
19617         }
19618         return { min: min, max: max };
19619     }
19620     ts.minAndMax = minAndMax;
19621     function rangeOfNode(node) {
19622         return { pos: getTokenPosOfNode(node), end: node.end };
19623     }
19624     ts.rangeOfNode = rangeOfNode;
19625     function rangeOfTypeParameters(sourceFile, typeParameters) {
19626         // Include the `<>`
19627         var pos = typeParameters.pos - 1;
19628         var end = ts.skipTrivia(sourceFile.text, typeParameters.end) + 1;
19629         return { pos: pos, end: end };
19630     }
19631     ts.rangeOfTypeParameters = rangeOfTypeParameters;
19632     function skipTypeChecking(sourceFile, options, host) {
19633         // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
19634         // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
19635         // '/// <reference no-default-lib="true"/>' directive.
19636         return (options.skipLibCheck && sourceFile.isDeclarationFile ||
19637             options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) ||
19638             host.isSourceOfProjectReferenceRedirect(sourceFile.fileName);
19639     }
19640     ts.skipTypeChecking = skipTypeChecking;
19641     function isJsonEqual(a, b) {
19642         // eslint-disable-next-line no-null/no-null
19643         return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
19644     }
19645     ts.isJsonEqual = isJsonEqual;
19646     /**
19647      * Converts a bigint literal string, e.g. `0x1234n`,
19648      * to its decimal string representation, e.g. `4660`.
19649      */
19650     function parsePseudoBigInt(stringValue) {
19651         var log2Base;
19652         switch (stringValue.charCodeAt(1)) { // "x" in "0x123"
19653             case 98 /* b */:
19654             case 66 /* B */: // 0b or 0B
19655                 log2Base = 1;
19656                 break;
19657             case 111 /* o */:
19658             case 79 /* O */: // 0o or 0O
19659                 log2Base = 3;
19660                 break;
19661             case 120 /* x */:
19662             case 88 /* X */: // 0x or 0X
19663                 log2Base = 4;
19664                 break;
19665             default: // already in decimal; omit trailing "n"
19666                 var nIndex = stringValue.length - 1;
19667                 // Skip leading 0s
19668                 var nonZeroStart = 0;
19669                 while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) {
19670                     nonZeroStart++;
19671                 }
19672                 return stringValue.slice(nonZeroStart, nIndex) || "0";
19673         }
19674         // Omit leading "0b", "0o", or "0x", and trailing "n"
19675         var startIndex = 2, endIndex = stringValue.length - 1;
19676         var bitsNeeded = (endIndex - startIndex) * log2Base;
19677         // Stores the value specified by the string as a LE array of 16-bit integers
19678         // using Uint16 instead of Uint32 so combining steps can use bitwise operators
19679         var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0));
19680         // Add the digits, one at a time
19681         for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) {
19682             var segment = bitOffset >>> 4;
19683             var digitChar = stringValue.charCodeAt(i);
19684             // Find character range: 0-9 < A-F < a-f
19685             var digit = digitChar <= 57 /* _9 */
19686                 ? digitChar - 48 /* _0 */
19687                 : 10 + digitChar -
19688                     (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */);
19689             var shiftedDigit = digit << (bitOffset & 15);
19690             segments[segment] |= shiftedDigit;
19691             var residual = shiftedDigit >>> 16;
19692             if (residual)
19693                 segments[segment + 1] |= residual; // overflows segment
19694         }
19695         // Repeatedly divide segments by 10 and add remainder to base10Value
19696         var base10Value = "";
19697         var firstNonzeroSegment = segments.length - 1;
19698         var segmentsRemaining = true;
19699         while (segmentsRemaining) {
19700             var mod10 = 0;
19701             segmentsRemaining = false;
19702             for (var segment = firstNonzeroSegment; segment >= 0; segment--) {
19703                 var newSegment = mod10 << 16 | segments[segment];
19704                 var segmentValue = (newSegment / 10) | 0;
19705                 segments[segment] = segmentValue;
19706                 mod10 = newSegment - segmentValue * 10;
19707                 if (segmentValue && !segmentsRemaining) {
19708                     firstNonzeroSegment = segment;
19709                     segmentsRemaining = true;
19710                 }
19711             }
19712             base10Value = mod10 + base10Value;
19713         }
19714         return base10Value;
19715     }
19716     ts.parsePseudoBigInt = parsePseudoBigInt;
19717     function pseudoBigIntToString(_a) {
19718         var negative = _a.negative, base10Value = _a.base10Value;
19719         return (negative && base10Value !== "0" ? "-" : "") + base10Value;
19720     }
19721     ts.pseudoBigIntToString = pseudoBigIntToString;
19722     function isValidTypeOnlyAliasUseSite(useSite) {
19723         return !!(useSite.flags & 8388608 /* Ambient */)
19724             || isPartOfTypeQuery(useSite)
19725             || isIdentifierInNonEmittingHeritageClause(useSite)
19726             || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite)
19727             || !isExpressionNode(useSite);
19728     }
19729     ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite;
19730     function typeOnlyDeclarationIsExport(typeOnlyDeclaration) {
19731         return typeOnlyDeclaration.kind === 270 /* ExportSpecifier */;
19732     }
19733     ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport;
19734     function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) {
19735         while (node.kind === 78 /* Identifier */ || node.kind === 201 /* PropertyAccessExpression */) {
19736             node = node.parent;
19737         }
19738         if (node.kind !== 158 /* ComputedPropertyName */) {
19739             return false;
19740         }
19741         if (hasSyntacticModifier(node.parent, 128 /* Abstract */)) {
19742             return true;
19743         }
19744         var containerKind = node.parent.parent.kind;
19745         return containerKind === 253 /* InterfaceDeclaration */ || containerKind === 177 /* TypeLiteral */;
19746     }
19747     /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */
19748     function isIdentifierInNonEmittingHeritageClause(node) {
19749         if (node.kind !== 78 /* Identifier */)
19750             return false;
19751         var heritageClause = ts.findAncestor(node.parent, function (parent) {
19752             switch (parent.kind) {
19753                 case 286 /* HeritageClause */:
19754                     return true;
19755                 case 201 /* PropertyAccessExpression */:
19756                 case 223 /* ExpressionWithTypeArguments */:
19757                     return false;
19758                 default:
19759                     return "quit";
19760             }
19761         });
19762         return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 253 /* InterfaceDeclaration */;
19763     }
19764     function isIdentifierTypeReference(node) {
19765         return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName);
19766     }
19767     ts.isIdentifierTypeReference = isIdentifierTypeReference;
19768     function arrayIsHomogeneous(array, comparer) {
19769         if (comparer === void 0) { comparer = ts.equateValues; }
19770         if (array.length < 2)
19771             return true;
19772         var first = array[0];
19773         for (var i = 1, length_1 = array.length; i < length_1; i++) {
19774             var target = array[i];
19775             if (!comparer(first, target))
19776                 return false;
19777         }
19778         return true;
19779     }
19780     ts.arrayIsHomogeneous = arrayIsHomogeneous;
19781     /**
19782      * Bypasses immutability and directly sets the `pos` property of a `TextRange` or `Node`.
19783      */
19784     /* @internal */
19785     function setTextRangePos(range, pos) {
19786         range.pos = pos;
19787         return range;
19788     }
19789     ts.setTextRangePos = setTextRangePos;
19790     /**
19791      * Bypasses immutability and directly sets the `end` property of a `TextRange` or `Node`.
19792      */
19793     /* @internal */
19794     function setTextRangeEnd(range, end) {
19795         range.end = end;
19796         return range;
19797     }
19798     ts.setTextRangeEnd = setTextRangeEnd;
19799     /**
19800      * Bypasses immutability and directly sets the `pos` and `end` properties of a `TextRange` or `Node`.
19801      */
19802     /* @internal */
19803     function setTextRangePosEnd(range, pos, end) {
19804         return setTextRangeEnd(setTextRangePos(range, pos), end);
19805     }
19806     ts.setTextRangePosEnd = setTextRangePosEnd;
19807     /**
19808      * Bypasses immutability and directly sets the `pos` and `end` properties of a `TextRange` or `Node` from the
19809      * provided position and width.
19810      */
19811     /* @internal */
19812     function setTextRangePosWidth(range, pos, width) {
19813         return setTextRangePosEnd(range, pos, pos + width);
19814     }
19815     ts.setTextRangePosWidth = setTextRangePosWidth;
19816     function setNodeFlags(node, newFlags) {
19817         if (node) {
19818             node.flags = newFlags;
19819         }
19820         return node;
19821     }
19822     ts.setNodeFlags = setNodeFlags;
19823     function setParent(child, parent) {
19824         if (child && parent) {
19825             child.parent = parent;
19826         }
19827         return child;
19828     }
19829     ts.setParent = setParent;
19830     function setEachParent(children, parent) {
19831         if (children) {
19832             for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
19833                 var child = children_1[_i];
19834                 setParent(child, parent);
19835             }
19836         }
19837         return children;
19838     }
19839     ts.setEachParent = setEachParent;
19840     function setParentRecursive(rootNode, incremental) {
19841         if (!rootNode)
19842             return rootNode;
19843         ts.forEachChildRecursively(rootNode, ts.isJSDocNode(rootNode) ? bindParentToChildIgnoringJSDoc : bindParentToChild);
19844         return rootNode;
19845         function bindParentToChildIgnoringJSDoc(child, parent) {
19846             if (incremental && child.parent === parent) {
19847                 return "skip";
19848             }
19849             setParent(child, parent);
19850         }
19851         function bindJSDoc(child) {
19852             if (ts.hasJSDocNodes(child)) {
19853                 for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
19854                     var doc = _a[_i];
19855                     bindParentToChildIgnoringJSDoc(doc, child);
19856                     ts.forEachChildRecursively(doc, bindParentToChildIgnoringJSDoc);
19857                 }
19858             }
19859         }
19860         function bindParentToChild(child, parent) {
19861             return bindParentToChildIgnoringJSDoc(child, parent) || bindJSDoc(child);
19862         }
19863     }
19864     ts.setParentRecursive = setParentRecursive;
19865     function isPackedElement(node) {
19866         return !ts.isOmittedExpression(node);
19867     }
19868     /**
19869      * Determines whether the provided node is an ArrayLiteralExpression that contains no missing elements.
19870      */
19871     function isPackedArrayLiteral(node) {
19872         return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement);
19873     }
19874     ts.isPackedArrayLiteral = isPackedArrayLiteral;
19875     /**
19876      * Indicates whether the result of an `Expression` will be unused.
19877      *
19878      * NOTE: This requires a node with a valid `parent` pointer.
19879      */
19880     function expressionResultIsUnused(node) {
19881         ts.Debug.assertIsDefined(node.parent);
19882         while (true) {
19883             var parent = node.parent;
19884             // walk up parenthesized expressions, but keep a pointer to the top-most parenthesized expression
19885             if (ts.isParenthesizedExpression(parent)) {
19886                 node = parent;
19887                 continue;
19888             }
19889             // result is unused in an expression statement, `void` expression, or the initializer or incrementer of a `for` loop
19890             if (ts.isExpressionStatement(parent) ||
19891                 ts.isVoidExpression(parent) ||
19892                 ts.isForStatement(parent) && (parent.initializer === node || parent.incrementor === node)) {
19893                 return true;
19894             }
19895             if (ts.isCommaListExpression(parent)) {
19896                 // left side of comma is always unused
19897                 if (node !== ts.last(parent.elements))
19898                     return true;
19899                 // right side of comma is unused if parent is unused
19900                 node = parent;
19901                 continue;
19902             }
19903             if (ts.isBinaryExpression(parent) && parent.operatorToken.kind === 27 /* CommaToken */) {
19904                 // left side of comma is always unused
19905                 if (node === parent.left)
19906                     return true;
19907                 // right side of comma is unused if parent is unused
19908                 node = parent;
19909                 continue;
19910             }
19911             return false;
19912         }
19913     }
19914     ts.expressionResultIsUnused = expressionResultIsUnused;
19915     function containsIgnoredPath(path) {
19916         return ts.some(ts.ignoredPaths, function (p) { return ts.stringContains(path, p); });
19917     }
19918     ts.containsIgnoredPath = containsIgnoredPath;
19919 })(ts || (ts = {}));
19920 /* @internal */
19921 var ts;
19922 (function (ts) {
19923     /**
19924      * Creates a `BaseNodeFactory` which can be used to create `Node` instances from the constructors provided by the object allocator.
19925      */
19926     function createBaseNodeFactory() {
19927         // tslint:disable variable-name
19928         var NodeConstructor;
19929         var TokenConstructor;
19930         var IdentifierConstructor;
19931         var PrivateIdentifierConstructor;
19932         var SourceFileConstructor;
19933         // tslint:enable variable-name
19934         return {
19935             createBaseSourceFileNode: createBaseSourceFileNode,
19936             createBaseIdentifierNode: createBaseIdentifierNode,
19937             createBasePrivateIdentifierNode: createBasePrivateIdentifierNode,
19938             createBaseTokenNode: createBaseTokenNode,
19939             createBaseNode: createBaseNode
19940         };
19941         function createBaseSourceFileNode(kind) {
19942             return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
19943         }
19944         function createBaseIdentifierNode(kind) {
19945             return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
19946         }
19947         function createBasePrivateIdentifierNode(kind) {
19948             return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
19949         }
19950         function createBaseTokenNode(kind) {
19951             return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
19952         }
19953         function createBaseNode(kind) {
19954             return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
19955         }
19956     }
19957     ts.createBaseNodeFactory = createBaseNodeFactory;
19958 })(ts || (ts = {}));
19959 /* @internal */
19960 var ts;
19961 (function (ts) {
19962     function createParenthesizerRules(factory) {
19963         return {
19964             parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary,
19965             parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary,
19966             parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName,
19967             parenthesizeConditionOfConditionalExpression: parenthesizeConditionOfConditionalExpression,
19968             parenthesizeBranchOfConditionalExpression: parenthesizeBranchOfConditionalExpression,
19969             parenthesizeExpressionOfExportDefault: parenthesizeExpressionOfExportDefault,
19970             parenthesizeExpressionOfNew: parenthesizeExpressionOfNew,
19971             parenthesizeLeftSideOfAccess: parenthesizeLeftSideOfAccess,
19972             parenthesizeOperandOfPostfixUnary: parenthesizeOperandOfPostfixUnary,
19973             parenthesizeOperandOfPrefixUnary: parenthesizeOperandOfPrefixUnary,
19974             parenthesizeExpressionsOfCommaDelimitedList: parenthesizeExpressionsOfCommaDelimitedList,
19975             parenthesizeExpressionForDisallowedComma: parenthesizeExpressionForDisallowedComma,
19976             parenthesizeExpressionOfExpressionStatement: parenthesizeExpressionOfExpressionStatement,
19977             parenthesizeConciseBodyOfArrowFunction: parenthesizeConciseBodyOfArrowFunction,
19978             parenthesizeMemberOfConditionalType: parenthesizeMemberOfConditionalType,
19979             parenthesizeMemberOfElementType: parenthesizeMemberOfElementType,
19980             parenthesizeElementTypeOfArrayType: parenthesizeElementTypeOfArrayType,
19981             parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType,
19982             parenthesizeTypeArguments: parenthesizeTypeArguments,
19983         };
19984         /**
19985          * Determines whether the operand to a BinaryExpression needs to be parenthesized.
19986          *
19987          * @param binaryOperator The operator for the BinaryExpression.
19988          * @param operand The operand for the BinaryExpression.
19989          * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
19990          *                           BinaryExpression.
19991          */
19992         function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
19993             // If the operand has lower precedence, then it needs to be parenthesized to preserve the
19994             // intent of the expression. For example, if the operand is `a + b` and the operator is
19995             // `*`, then we need to parenthesize the operand to preserve the intended order of
19996             // operations: `(a + b) * x`.
19997             //
19998             // If the operand has higher precedence, then it does not need to be parenthesized. For
19999             // example, if the operand is `a * b` and the operator is `+`, then we do not need to
20000             // parenthesize to preserve the intended order of operations: `a * b + x`.
20001             //
20002             // If the operand has the same precedence, then we need to check the associativity of
20003             // the operator based on whether this is the left or right operand of the expression.
20004             //
20005             // For example, if `a / d` is on the right of operator `*`, we need to parenthesize
20006             // to preserve the intended order of operations: `x * (a / d)`
20007             //
20008             // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
20009             // the intended order of operations: `(a ** b) ** c`
20010             var binaryOperatorPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, binaryOperator);
20011             var binaryOperatorAssociativity = ts.getOperatorAssociativity(216 /* BinaryExpression */, binaryOperator);
20012             var emittedOperand = ts.skipPartiallyEmittedExpressions(operand);
20013             if (!isLeftSideOfBinary && operand.kind === 209 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) {
20014                 // We need to parenthesize arrow functions on the right side to avoid it being
20015                 // parsed as parenthesized expression: `a && (() => {})`
20016                 return true;
20017             }
20018             var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
20019             switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
20020                 case -1 /* LessThan */:
20021                     // If the operand is the right side of a right-associative binary operation
20022                     // and is a yield expression, then we do not need parentheses.
20023                     if (!isLeftSideOfBinary
20024                         && binaryOperatorAssociativity === 1 /* Right */
20025                         && operand.kind === 219 /* YieldExpression */) {
20026                         return false;
20027                     }
20028                     return true;
20029                 case 1 /* GreaterThan */:
20030                     return false;
20031                 case 0 /* EqualTo */:
20032                     if (isLeftSideOfBinary) {
20033                         // No need to parenthesize the left operand when the binary operator is
20034                         // left associative:
20035                         //  (a*b)/x    -> a*b/x
20036                         //  (a**b)/x   -> a**b/x
20037                         //
20038                         // Parentheses are needed for the left operand when the binary operator is
20039                         // right associative:
20040                         //  (a/b)**x   -> (a/b)**x
20041                         //  (a**b)**x  -> (a**b)**x
20042                         return binaryOperatorAssociativity === 1 /* Right */;
20043                     }
20044                     else {
20045                         if (ts.isBinaryExpression(emittedOperand)
20046                             && emittedOperand.operatorToken.kind === binaryOperator) {
20047                             // No need to parenthesize the right operand when the binary operator and
20048                             // operand are the same and one of the following:
20049                             //  x*(a*b)     => x*a*b
20050                             //  x|(a|b)     => x|a|b
20051                             //  x&(a&b)     => x&a&b
20052                             //  x^(a^b)     => x^a^b
20053                             if (operatorHasAssociativeProperty(binaryOperator)) {
20054                                 return false;
20055                             }
20056                             // No need to parenthesize the right operand when the binary operator
20057                             // is plus (+) if both the left and right operands consist solely of either
20058                             // literals of the same kind or binary plus (+) expressions for literals of
20059                             // the same kind (recursively).
20060                             //  "a"+(1+2)       => "a"+(1+2)
20061                             //  "a"+("b"+"c")   => "a"+"b"+"c"
20062                             if (binaryOperator === 39 /* PlusToken */) {
20063                                 var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
20064                                 if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
20065                                     return false;
20066                                 }
20067                             }
20068                         }
20069                         // No need to parenthesize the right operand when the operand is right
20070                         // associative:
20071                         //  x/(a**b)    -> x/a**b
20072                         //  x**(a**b)   -> x**a**b
20073                         //
20074                         // Parentheses are needed for the right operand when the operand is left
20075                         // associative:
20076                         //  x/(a*b)     -> x/(a*b)
20077                         //  x**(a/b)    -> x**(a/b)
20078                         var operandAssociativity = ts.getExpressionAssociativity(emittedOperand);
20079                         return operandAssociativity === 0 /* Left */;
20080                     }
20081             }
20082         }
20083         /**
20084          * Determines whether a binary operator is mathematically associative.
20085          *
20086          * @param binaryOperator The binary operator.
20087          */
20088         function operatorHasAssociativeProperty(binaryOperator) {
20089             // The following operators are associative in JavaScript:
20090             //  (a*b)*c     -> a*(b*c)  -> a*b*c
20091             //  (a|b)|c     -> a|(b|c)  -> a|b|c
20092             //  (a&b)&c     -> a&(b&c)  -> a&b&c
20093             //  (a^b)^c     -> a^(b^c)  -> a^b^c
20094             //
20095             // While addition is associative in mathematics, JavaScript's `+` is not
20096             // guaranteed to be associative as it is overloaded with string concatenation.
20097             return binaryOperator === 41 /* AsteriskToken */
20098                 || binaryOperator === 51 /* BarToken */
20099                 || binaryOperator === 50 /* AmpersandToken */
20100                 || binaryOperator === 52 /* CaretToken */;
20101         }
20102         /**
20103          * This function determines whether an expression consists of a homogeneous set of
20104          * literal expressions or binary plus expressions that all share the same literal kind.
20105          * It is used to determine whether the right-hand operand of a binary plus expression can be
20106          * emitted without parentheses.
20107          */
20108         function getLiteralKindOfBinaryPlusOperand(node) {
20109             node = ts.skipPartiallyEmittedExpressions(node);
20110             if (ts.isLiteralKind(node.kind)) {
20111                 return node.kind;
20112             }
20113             if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) {
20114                 if (node.cachedLiteralKind !== undefined) {
20115                     return node.cachedLiteralKind;
20116                 }
20117                 var leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
20118                 var literalKind = ts.isLiteralKind(leftKind)
20119                     && leftKind === getLiteralKindOfBinaryPlusOperand(node.right)
20120                     ? leftKind
20121                     : 0 /* Unknown */;
20122                 node.cachedLiteralKind = literalKind;
20123                 return literalKind;
20124             }
20125             return 0 /* Unknown */;
20126         }
20127         /**
20128          * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
20129          * order of operations.
20130          *
20131          * @param binaryOperator The operator for the BinaryExpression.
20132          * @param operand The operand for the BinaryExpression.
20133          * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
20134          *                           BinaryExpression.
20135          */
20136         function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
20137             var skipped = ts.skipPartiallyEmittedExpressions(operand);
20138             // If the resulting expression is already parenthesized, we do not need to do any further processing.
20139             if (skipped.kind === 207 /* ParenthesizedExpression */) {
20140                 return operand;
20141             }
20142             return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
20143                 ? factory.createParenthesizedExpression(operand)
20144                 : operand;
20145         }
20146         function parenthesizeLeftSideOfBinary(binaryOperator, leftSide) {
20147             return parenthesizeBinaryOperand(binaryOperator, leftSide, /*isLeftSideOfBinary*/ true);
20148         }
20149         function parenthesizeRightSideOfBinary(binaryOperator, leftSide, rightSide) {
20150             return parenthesizeBinaryOperand(binaryOperator, rightSide, /*isLeftSideOfBinary*/ false, leftSide);
20151         }
20152         function parenthesizeExpressionOfComputedPropertyName(expression) {
20153             return ts.isCommaSequence(expression) ? factory.createParenthesizedExpression(expression) : expression;
20154         }
20155         function parenthesizeConditionOfConditionalExpression(condition) {
20156             var conditionalPrecedence = ts.getOperatorPrecedence(217 /* ConditionalExpression */, 57 /* QuestionToken */);
20157             var emittedCondition = ts.skipPartiallyEmittedExpressions(condition);
20158             var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
20159             if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) {
20160                 return factory.createParenthesizedExpression(condition);
20161             }
20162             return condition;
20163         }
20164         function parenthesizeBranchOfConditionalExpression(branch) {
20165             // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
20166             // so in case when comma expression is introduced as a part of previous transformations
20167             // if should be wrapped in parens since comma operator has the lowest precedence
20168             var emittedExpression = ts.skipPartiallyEmittedExpressions(branch);
20169             return ts.isCommaSequence(emittedExpression)
20170                 ? factory.createParenthesizedExpression(branch)
20171                 : branch;
20172         }
20173         /**
20174          *  [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
20175          *  has a lookahead restriction for `function`, `async function`, and `class`.
20176          *
20177          * Basically, that means we need to parenthesize in the following cases:
20178          *
20179          * - BinaryExpression of CommaToken
20180          * - CommaList (synthetic list of multiple comma expressions)
20181          * - FunctionExpression
20182          * - ClassExpression
20183          */
20184         function parenthesizeExpressionOfExportDefault(expression) {
20185             var check = ts.skipPartiallyEmittedExpressions(expression);
20186             var needsParens = ts.isCommaSequence(check);
20187             if (!needsParens) {
20188                 switch (ts.getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) {
20189                     case 221 /* ClassExpression */:
20190                     case 208 /* FunctionExpression */:
20191                         needsParens = true;
20192                 }
20193             }
20194             return needsParens ? factory.createParenthesizedExpression(expression) : expression;
20195         }
20196         /**
20197          * Wraps an expression in parentheses if it is needed in order to use the expression
20198          * as the expression of a `NewExpression` node.
20199          */
20200         function parenthesizeExpressionOfNew(expression) {
20201             var leftmostExpr = ts.getLeftmostExpression(expression, /*stopAtCallExpressions*/ true);
20202             switch (leftmostExpr.kind) {
20203                 case 203 /* CallExpression */:
20204                     return factory.createParenthesizedExpression(expression);
20205                 case 204 /* NewExpression */:
20206                     return !leftmostExpr.arguments
20207                         ? factory.createParenthesizedExpression(expression)
20208                         : expression; // TODO(rbuckton): Verify this assertion holds
20209             }
20210             return parenthesizeLeftSideOfAccess(expression);
20211         }
20212         /**
20213          * Wraps an expression in parentheses if it is needed in order to use the expression for
20214          * property or element access.
20215          */
20216         function parenthesizeLeftSideOfAccess(expression) {
20217             // isLeftHandSideExpression is almost the correct criterion for when it is not necessary
20218             // to parenthesize the expression before a dot. The known exception is:
20219             //
20220             //    NewExpression:
20221             //       new C.x        -> not the same as (new C).x
20222             //
20223             var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
20224             if (ts.isLeftHandSideExpression(emittedExpression)
20225                 && (emittedExpression.kind !== 204 /* NewExpression */ || emittedExpression.arguments)) {
20226                 // TODO(rbuckton): Verify whether this assertion holds.
20227                 return expression;
20228             }
20229             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
20230             return ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
20231         }
20232         function parenthesizeOperandOfPostfixUnary(operand) {
20233             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
20234             return ts.isLeftHandSideExpression(operand) ? operand : ts.setTextRange(factory.createParenthesizedExpression(operand), operand);
20235         }
20236         function parenthesizeOperandOfPrefixUnary(operand) {
20237             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
20238             return ts.isUnaryExpression(operand) ? operand : ts.setTextRange(factory.createParenthesizedExpression(operand), operand);
20239         }
20240         function parenthesizeExpressionsOfCommaDelimitedList(elements) {
20241             var result = ts.sameMap(elements, parenthesizeExpressionForDisallowedComma);
20242             return ts.setTextRange(factory.createNodeArray(result, elements.hasTrailingComma), elements);
20243         }
20244         function parenthesizeExpressionForDisallowedComma(expression) {
20245             var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
20246             var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
20247             var commaPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, 27 /* CommaToken */);
20248             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
20249             return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
20250         }
20251         function parenthesizeExpressionOfExpressionStatement(expression) {
20252             var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
20253             if (ts.isCallExpression(emittedExpression)) {
20254                 var callee = emittedExpression.expression;
20255                 var kind = ts.skipPartiallyEmittedExpressions(callee).kind;
20256                 if (kind === 208 /* FunctionExpression */ || kind === 209 /* ArrowFunction */) {
20257                     // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
20258                     var updated = factory.updateCallExpression(emittedExpression, ts.setTextRange(factory.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, emittedExpression.arguments);
20259                     return factory.restoreOuterExpressions(expression, updated, 8 /* PartiallyEmittedExpressions */);
20260                 }
20261             }
20262             var leftmostExpressionKind = ts.getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind;
20263             if (leftmostExpressionKind === 200 /* ObjectLiteralExpression */ || leftmostExpressionKind === 208 /* FunctionExpression */) {
20264                 // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
20265                 return ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
20266             }
20267             return expression;
20268         }
20269         function parenthesizeConciseBodyOfArrowFunction(body) {
20270             if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 200 /* ObjectLiteralExpression */)) {
20271                 // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
20272                 return ts.setTextRange(factory.createParenthesizedExpression(body), body);
20273             }
20274             return body;
20275         }
20276         function parenthesizeMemberOfConditionalType(member) {
20277             return member.kind === 184 /* ConditionalType */ ? factory.createParenthesizedType(member) : member;
20278         }
20279         function parenthesizeMemberOfElementType(member) {
20280             switch (member.kind) {
20281                 case 182 /* UnionType */:
20282                 case 183 /* IntersectionType */:
20283                 case 174 /* FunctionType */:
20284                 case 175 /* ConstructorType */:
20285                     return factory.createParenthesizedType(member);
20286             }
20287             return parenthesizeMemberOfConditionalType(member);
20288         }
20289         function parenthesizeElementTypeOfArrayType(member) {
20290             switch (member.kind) {
20291                 case 176 /* TypeQuery */:
20292                 case 188 /* TypeOperator */:
20293                 case 185 /* InferType */:
20294                     return factory.createParenthesizedType(member);
20295             }
20296             return parenthesizeMemberOfElementType(member);
20297         }
20298         function parenthesizeConstituentTypesOfUnionOrIntersectionType(members) {
20299             return factory.createNodeArray(ts.sameMap(members, parenthesizeMemberOfElementType));
20300         }
20301         function parenthesizeOrdinalTypeArgument(node, i) {
20302             return i === 0 && ts.isFunctionOrConstructorTypeNode(node) && node.typeParameters ? factory.createParenthesizedType(node) : node;
20303         }
20304         function parenthesizeTypeArguments(typeArguments) {
20305             if (ts.some(typeArguments)) {
20306                 return factory.createNodeArray(ts.sameMap(typeArguments, parenthesizeOrdinalTypeArgument));
20307             }
20308         }
20309     }
20310     ts.createParenthesizerRules = createParenthesizerRules;
20311     ts.nullParenthesizerRules = {
20312         parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; },
20313         parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; },
20314         parenthesizeExpressionOfComputedPropertyName: ts.identity,
20315         parenthesizeConditionOfConditionalExpression: ts.identity,
20316         parenthesizeBranchOfConditionalExpression: ts.identity,
20317         parenthesizeExpressionOfExportDefault: ts.identity,
20318         parenthesizeExpressionOfNew: function (expression) { return ts.cast(expression, ts.isLeftHandSideExpression); },
20319         parenthesizeLeftSideOfAccess: function (expression) { return ts.cast(expression, ts.isLeftHandSideExpression); },
20320         parenthesizeOperandOfPostfixUnary: function (operand) { return ts.cast(operand, ts.isLeftHandSideExpression); },
20321         parenthesizeOperandOfPrefixUnary: function (operand) { return ts.cast(operand, ts.isUnaryExpression); },
20322         parenthesizeExpressionsOfCommaDelimitedList: function (nodes) { return ts.cast(nodes, ts.isNodeArray); },
20323         parenthesizeExpressionForDisallowedComma: ts.identity,
20324         parenthesizeExpressionOfExpressionStatement: ts.identity,
20325         parenthesizeConciseBodyOfArrowFunction: ts.identity,
20326         parenthesizeMemberOfConditionalType: ts.identity,
20327         parenthesizeMemberOfElementType: ts.identity,
20328         parenthesizeElementTypeOfArrayType: ts.identity,
20329         parenthesizeConstituentTypesOfUnionOrIntersectionType: function (nodes) { return ts.cast(nodes, ts.isNodeArray); },
20330         parenthesizeTypeArguments: function (nodes) { return nodes && ts.cast(nodes, ts.isNodeArray); },
20331     };
20332 })(ts || (ts = {}));
20333 /* @internal */
20334 var ts;
20335 (function (ts) {
20336     function createNodeConverters(factory) {
20337         return {
20338             convertToFunctionBlock: convertToFunctionBlock,
20339             convertToFunctionExpression: convertToFunctionExpression,
20340             convertToArrayAssignmentElement: convertToArrayAssignmentElement,
20341             convertToObjectAssignmentElement: convertToObjectAssignmentElement,
20342             convertToAssignmentPattern: convertToAssignmentPattern,
20343             convertToObjectAssignmentPattern: convertToObjectAssignmentPattern,
20344             convertToArrayAssignmentPattern: convertToArrayAssignmentPattern,
20345             convertToAssignmentElementTarget: convertToAssignmentElementTarget,
20346         };
20347         function convertToFunctionBlock(node, multiLine) {
20348             if (ts.isBlock(node))
20349                 return node;
20350             var returnStatement = factory.createReturnStatement(node);
20351             ts.setTextRange(returnStatement, node);
20352             var body = factory.createBlock([returnStatement], multiLine);
20353             ts.setTextRange(body, node);
20354             return body;
20355         }
20356         function convertToFunctionExpression(node) {
20357             if (!node.body)
20358                 return ts.Debug.fail("Cannot convert a FunctionDeclaration without a body");
20359             var updated = factory.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
20360             ts.setOriginalNode(updated, node);
20361             ts.setTextRange(updated, node);
20362             if (ts.getStartsOnNewLine(node)) {
20363                 ts.setStartsOnNewLine(updated, /*newLine*/ true);
20364             }
20365             return updated;
20366         }
20367         function convertToArrayAssignmentElement(element) {
20368             if (ts.isBindingElement(element)) {
20369                 if (element.dotDotDotToken) {
20370                     ts.Debug.assertNode(element.name, ts.isIdentifier);
20371                     return ts.setOriginalNode(ts.setTextRange(factory.createSpreadElement(element.name), element), element);
20372                 }
20373                 var expression = convertToAssignmentElementTarget(element.name);
20374                 return element.initializer
20375                     ? ts.setOriginalNode(ts.setTextRange(factory.createAssignment(expression, element.initializer), element), element)
20376                     : expression;
20377             }
20378             return ts.cast(element, ts.isExpression);
20379         }
20380         function convertToObjectAssignmentElement(element) {
20381             if (ts.isBindingElement(element)) {
20382                 if (element.dotDotDotToken) {
20383                     ts.Debug.assertNode(element.name, ts.isIdentifier);
20384                     return ts.setOriginalNode(ts.setTextRange(factory.createSpreadAssignment(element.name), element), element);
20385                 }
20386                 if (element.propertyName) {
20387                     var expression = convertToAssignmentElementTarget(element.name);
20388                     return ts.setOriginalNode(ts.setTextRange(factory.createPropertyAssignment(element.propertyName, element.initializer ? factory.createAssignment(expression, element.initializer) : expression), element), element);
20389                 }
20390                 ts.Debug.assertNode(element.name, ts.isIdentifier);
20391                 return ts.setOriginalNode(ts.setTextRange(factory.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
20392             }
20393             return ts.cast(element, ts.isObjectLiteralElementLike);
20394         }
20395         function convertToAssignmentPattern(node) {
20396             switch (node.kind) {
20397                 case 197 /* ArrayBindingPattern */:
20398                 case 199 /* ArrayLiteralExpression */:
20399                     return convertToArrayAssignmentPattern(node);
20400                 case 196 /* ObjectBindingPattern */:
20401                 case 200 /* ObjectLiteralExpression */:
20402                     return convertToObjectAssignmentPattern(node);
20403             }
20404         }
20405         function convertToObjectAssignmentPattern(node) {
20406             if (ts.isObjectBindingPattern(node)) {
20407                 return ts.setOriginalNode(ts.setTextRange(factory.createObjectLiteralExpression(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
20408             }
20409             return ts.cast(node, ts.isObjectLiteralExpression);
20410         }
20411         function convertToArrayAssignmentPattern(node) {
20412             if (ts.isArrayBindingPattern(node)) {
20413                 return ts.setOriginalNode(ts.setTextRange(factory.createArrayLiteralExpression(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
20414             }
20415             return ts.cast(node, ts.isArrayLiteralExpression);
20416         }
20417         function convertToAssignmentElementTarget(node) {
20418             if (ts.isBindingPattern(node)) {
20419                 return convertToAssignmentPattern(node);
20420             }
20421             return ts.cast(node, ts.isExpression);
20422         }
20423     }
20424     ts.createNodeConverters = createNodeConverters;
20425     ts.nullNodeConverters = {
20426         convertToFunctionBlock: ts.notImplemented,
20427         convertToFunctionExpression: ts.notImplemented,
20428         convertToArrayAssignmentElement: ts.notImplemented,
20429         convertToObjectAssignmentElement: ts.notImplemented,
20430         convertToAssignmentPattern: ts.notImplemented,
20431         convertToObjectAssignmentPattern: ts.notImplemented,
20432         convertToArrayAssignmentPattern: ts.notImplemented,
20433         convertToAssignmentElementTarget: ts.notImplemented,
20434     };
20435 })(ts || (ts = {}));
20436 var ts;
20437 (function (ts) {
20438     var nextAutoGenerateId = 0;
20439     /* @internal */
20440     var NodeFactoryFlags;
20441     (function (NodeFactoryFlags) {
20442         NodeFactoryFlags[NodeFactoryFlags["None"] = 0] = "None";
20443         // Disables the parenthesizer rules for the factory.
20444         NodeFactoryFlags[NodeFactoryFlags["NoParenthesizerRules"] = 1] = "NoParenthesizerRules";
20445         // Disables the node converters for the factory.
20446         NodeFactoryFlags[NodeFactoryFlags["NoNodeConverters"] = 2] = "NoNodeConverters";
20447         // Ensures new `PropertyAccessExpression` nodes are created with the `NoIndentation` emit flag set.
20448         NodeFactoryFlags[NodeFactoryFlags["NoIndentationOnFreshPropertyAccess"] = 4] = "NoIndentationOnFreshPropertyAccess";
20449         // Do not set an `original` pointer when updating a node.
20450         NodeFactoryFlags[NodeFactoryFlags["NoOriginalNode"] = 8] = "NoOriginalNode";
20451     })(NodeFactoryFlags = ts.NodeFactoryFlags || (ts.NodeFactoryFlags = {}));
20452     /**
20453      * Creates a `NodeFactory` that can be used to create and update a syntax tree.
20454      * @param flags Flags that control factory behavior.
20455      * @param baseFactory A `BaseNodeFactory` used to create the base `Node` objects.
20456      */
20457     /* @internal */
20458     function createNodeFactory(flags, baseFactory) {
20459         var update = flags & 8 /* NoOriginalNode */ ? updateWithoutOriginal : updateWithOriginal;
20460         // Lazily load the parenthesizer, node converters, and some factory methods until they are used.
20461         var parenthesizerRules = ts.memoize(function () { return flags & 1 /* NoParenthesizerRules */ ? ts.nullParenthesizerRules : ts.createParenthesizerRules(factory); });
20462         var converters = ts.memoize(function () { return flags & 2 /* NoNodeConverters */ ? ts.nullNodeConverters : ts.createNodeConverters(factory); });
20463         // lazy initializaton of common operator factories
20464         var getBinaryCreateFunction = ts.memoizeOne(function (operator) { return function (left, right) { return createBinaryExpression(left, operator, right); }; });
20465         var getPrefixUnaryCreateFunction = ts.memoizeOne(function (operator) { return function (operand) { return createPrefixUnaryExpression(operator, operand); }; });
20466         var getPostfixUnaryCreateFunction = ts.memoizeOne(function (operator) { return function (operand) { return createPostfixUnaryExpression(operand, operator); }; });
20467         var getJSDocPrimaryTypeCreateFunction = ts.memoizeOne(function (kind) { return function () { return createJSDocPrimaryTypeWorker(kind); }; });
20468         var getJSDocUnaryTypeCreateFunction = ts.memoizeOne(function (kind) { return function (type) { return createJSDocUnaryTypeWorker(kind, type); }; });
20469         var getJSDocUnaryTypeUpdateFunction = ts.memoizeOne(function (kind) { return function (node, type) { return updateJSDocUnaryTypeWorker(kind, node, type); }; });
20470         var getJSDocSimpleTagCreateFunction = ts.memoizeOne(function (kind) { return function (tagName, comment) { return createJSDocSimpleTagWorker(kind, tagName, comment); }; });
20471         var getJSDocSimpleTagUpdateFunction = ts.memoizeOne(function (kind) { return function (node, tagName, comment) { return updateJSDocSimpleTagWorker(kind, node, tagName, comment); }; });
20472         var getJSDocTypeLikeTagCreateFunction = ts.memoizeOne(function (kind) { return function (tagName, typeExpression, comment) { return createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment); }; });
20473         var getJSDocTypeLikeTagUpdateFunction = ts.memoizeOne(function (kind) { return function (node, tagName, typeExpression, comment) { return updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment); }; });
20474         var factory = {
20475             get parenthesizer() { return parenthesizerRules(); },
20476             get converters() { return converters(); },
20477             createNodeArray: createNodeArray,
20478             createNumericLiteral: createNumericLiteral,
20479             createBigIntLiteral: createBigIntLiteral,
20480             createStringLiteral: createStringLiteral,
20481             createStringLiteralFromNode: createStringLiteralFromNode,
20482             createRegularExpressionLiteral: createRegularExpressionLiteral,
20483             createLiteralLikeNode: createLiteralLikeNode,
20484             createIdentifier: createIdentifier,
20485             updateIdentifier: updateIdentifier,
20486             createTempVariable: createTempVariable,
20487             createLoopVariable: createLoopVariable,
20488             createUniqueName: createUniqueName,
20489             getGeneratedNameForNode: getGeneratedNameForNode,
20490             createPrivateIdentifier: createPrivateIdentifier,
20491             createToken: createToken,
20492             createSuper: createSuper,
20493             createThis: createThis,
20494             createNull: createNull,
20495             createTrue: createTrue,
20496             createFalse: createFalse,
20497             createModifier: createModifier,
20498             createModifiersFromModifierFlags: createModifiersFromModifierFlags,
20499             createQualifiedName: createQualifiedName,
20500             updateQualifiedName: updateQualifiedName,
20501             createComputedPropertyName: createComputedPropertyName,
20502             updateComputedPropertyName: updateComputedPropertyName,
20503             createTypeParameterDeclaration: createTypeParameterDeclaration,
20504             updateTypeParameterDeclaration: updateTypeParameterDeclaration,
20505             createParameterDeclaration: createParameterDeclaration,
20506             updateParameterDeclaration: updateParameterDeclaration,
20507             createDecorator: createDecorator,
20508             updateDecorator: updateDecorator,
20509             createPropertySignature: createPropertySignature,
20510             updatePropertySignature: updatePropertySignature,
20511             createPropertyDeclaration: createPropertyDeclaration,
20512             updatePropertyDeclaration: updatePropertyDeclaration,
20513             createMethodSignature: createMethodSignature,
20514             updateMethodSignature: updateMethodSignature,
20515             createMethodDeclaration: createMethodDeclaration,
20516             updateMethodDeclaration: updateMethodDeclaration,
20517             createConstructorDeclaration: createConstructorDeclaration,
20518             updateConstructorDeclaration: updateConstructorDeclaration,
20519             createGetAccessorDeclaration: createGetAccessorDeclaration,
20520             updateGetAccessorDeclaration: updateGetAccessorDeclaration,
20521             createSetAccessorDeclaration: createSetAccessorDeclaration,
20522             updateSetAccessorDeclaration: updateSetAccessorDeclaration,
20523             createCallSignature: createCallSignature,
20524             updateCallSignature: updateCallSignature,
20525             createConstructSignature: createConstructSignature,
20526             updateConstructSignature: updateConstructSignature,
20527             createIndexSignature: createIndexSignature,
20528             updateIndexSignature: updateIndexSignature,
20529             createTemplateLiteralTypeSpan: createTemplateLiteralTypeSpan,
20530             updateTemplateLiteralTypeSpan: updateTemplateLiteralTypeSpan,
20531             createKeywordTypeNode: createKeywordTypeNode,
20532             createTypePredicateNode: createTypePredicateNode,
20533             updateTypePredicateNode: updateTypePredicateNode,
20534             createTypeReferenceNode: createTypeReferenceNode,
20535             updateTypeReferenceNode: updateTypeReferenceNode,
20536             createFunctionTypeNode: createFunctionTypeNode,
20537             updateFunctionTypeNode: updateFunctionTypeNode,
20538             createConstructorTypeNode: createConstructorTypeNode,
20539             updateConstructorTypeNode: updateConstructorTypeNode,
20540             createTypeQueryNode: createTypeQueryNode,
20541             updateTypeQueryNode: updateTypeQueryNode,
20542             createTypeLiteralNode: createTypeLiteralNode,
20543             updateTypeLiteralNode: updateTypeLiteralNode,
20544             createArrayTypeNode: createArrayTypeNode,
20545             updateArrayTypeNode: updateArrayTypeNode,
20546             createTupleTypeNode: createTupleTypeNode,
20547             updateTupleTypeNode: updateTupleTypeNode,
20548             createNamedTupleMember: createNamedTupleMember,
20549             updateNamedTupleMember: updateNamedTupleMember,
20550             createOptionalTypeNode: createOptionalTypeNode,
20551             updateOptionalTypeNode: updateOptionalTypeNode,
20552             createRestTypeNode: createRestTypeNode,
20553             updateRestTypeNode: updateRestTypeNode,
20554             createUnionTypeNode: createUnionTypeNode,
20555             updateUnionTypeNode: updateUnionTypeNode,
20556             createIntersectionTypeNode: createIntersectionTypeNode,
20557             updateIntersectionTypeNode: updateIntersectionTypeNode,
20558             createConditionalTypeNode: createConditionalTypeNode,
20559             updateConditionalTypeNode: updateConditionalTypeNode,
20560             createInferTypeNode: createInferTypeNode,
20561             updateInferTypeNode: updateInferTypeNode,
20562             createImportTypeNode: createImportTypeNode,
20563             updateImportTypeNode: updateImportTypeNode,
20564             createParenthesizedType: createParenthesizedType,
20565             updateParenthesizedType: updateParenthesizedType,
20566             createThisTypeNode: createThisTypeNode,
20567             createTypeOperatorNode: createTypeOperatorNode,
20568             updateTypeOperatorNode: updateTypeOperatorNode,
20569             createIndexedAccessTypeNode: createIndexedAccessTypeNode,
20570             updateIndexedAccessTypeNode: updateIndexedAccessTypeNode,
20571             createMappedTypeNode: createMappedTypeNode,
20572             updateMappedTypeNode: updateMappedTypeNode,
20573             createLiteralTypeNode: createLiteralTypeNode,
20574             updateLiteralTypeNode: updateLiteralTypeNode,
20575             createTemplateLiteralType: createTemplateLiteralType,
20576             updateTemplateLiteralType: updateTemplateLiteralType,
20577             createObjectBindingPattern: createObjectBindingPattern,
20578             updateObjectBindingPattern: updateObjectBindingPattern,
20579             createArrayBindingPattern: createArrayBindingPattern,
20580             updateArrayBindingPattern: updateArrayBindingPattern,
20581             createBindingElement: createBindingElement,
20582             updateBindingElement: updateBindingElement,
20583             createArrayLiteralExpression: createArrayLiteralExpression,
20584             updateArrayLiteralExpression: updateArrayLiteralExpression,
20585             createObjectLiteralExpression: createObjectLiteralExpression,
20586             updateObjectLiteralExpression: updateObjectLiteralExpression,
20587             createPropertyAccessExpression: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ?
20588                 function (expression, name) { return ts.setEmitFlags(createPropertyAccessExpression(expression, name), 131072 /* NoIndentation */); } :
20589                 createPropertyAccessExpression,
20590             updatePropertyAccessExpression: updatePropertyAccessExpression,
20591             createPropertyAccessChain: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ?
20592                 function (expression, questionDotToken, name) { return ts.setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), 131072 /* NoIndentation */); } :
20593                 createPropertyAccessChain,
20594             updatePropertyAccessChain: updatePropertyAccessChain,
20595             createElementAccessExpression: createElementAccessExpression,
20596             updateElementAccessExpression: updateElementAccessExpression,
20597             createElementAccessChain: createElementAccessChain,
20598             updateElementAccessChain: updateElementAccessChain,
20599             createCallExpression: createCallExpression,
20600             updateCallExpression: updateCallExpression,
20601             createCallChain: createCallChain,
20602             updateCallChain: updateCallChain,
20603             createNewExpression: createNewExpression,
20604             updateNewExpression: updateNewExpression,
20605             createTaggedTemplateExpression: createTaggedTemplateExpression,
20606             updateTaggedTemplateExpression: updateTaggedTemplateExpression,
20607             createTypeAssertion: createTypeAssertion,
20608             updateTypeAssertion: updateTypeAssertion,
20609             createParenthesizedExpression: createParenthesizedExpression,
20610             updateParenthesizedExpression: updateParenthesizedExpression,
20611             createFunctionExpression: createFunctionExpression,
20612             updateFunctionExpression: updateFunctionExpression,
20613             createArrowFunction: createArrowFunction,
20614             updateArrowFunction: updateArrowFunction,
20615             createDeleteExpression: createDeleteExpression,
20616             updateDeleteExpression: updateDeleteExpression,
20617             createTypeOfExpression: createTypeOfExpression,
20618             updateTypeOfExpression: updateTypeOfExpression,
20619             createVoidExpression: createVoidExpression,
20620             updateVoidExpression: updateVoidExpression,
20621             createAwaitExpression: createAwaitExpression,
20622             updateAwaitExpression: updateAwaitExpression,
20623             createPrefixUnaryExpression: createPrefixUnaryExpression,
20624             updatePrefixUnaryExpression: updatePrefixUnaryExpression,
20625             createPostfixUnaryExpression: createPostfixUnaryExpression,
20626             updatePostfixUnaryExpression: updatePostfixUnaryExpression,
20627             createBinaryExpression: createBinaryExpression,
20628             updateBinaryExpression: updateBinaryExpression,
20629             createConditionalExpression: createConditionalExpression,
20630             updateConditionalExpression: updateConditionalExpression,
20631             createTemplateExpression: createTemplateExpression,
20632             updateTemplateExpression: updateTemplateExpression,
20633             createTemplateHead: createTemplateHead,
20634             createTemplateMiddle: createTemplateMiddle,
20635             createTemplateTail: createTemplateTail,
20636             createNoSubstitutionTemplateLiteral: createNoSubstitutionTemplateLiteral,
20637             createTemplateLiteralLikeNode: createTemplateLiteralLikeNode,
20638             createYieldExpression: createYieldExpression,
20639             updateYieldExpression: updateYieldExpression,
20640             createSpreadElement: createSpreadElement,
20641             updateSpreadElement: updateSpreadElement,
20642             createClassExpression: createClassExpression,
20643             updateClassExpression: updateClassExpression,
20644             createOmittedExpression: createOmittedExpression,
20645             createExpressionWithTypeArguments: createExpressionWithTypeArguments,
20646             updateExpressionWithTypeArguments: updateExpressionWithTypeArguments,
20647             createAsExpression: createAsExpression,
20648             updateAsExpression: updateAsExpression,
20649             createNonNullExpression: createNonNullExpression,
20650             updateNonNullExpression: updateNonNullExpression,
20651             createNonNullChain: createNonNullChain,
20652             updateNonNullChain: updateNonNullChain,
20653             createMetaProperty: createMetaProperty,
20654             updateMetaProperty: updateMetaProperty,
20655             createTemplateSpan: createTemplateSpan,
20656             updateTemplateSpan: updateTemplateSpan,
20657             createSemicolonClassElement: createSemicolonClassElement,
20658             createBlock: createBlock,
20659             updateBlock: updateBlock,
20660             createVariableStatement: createVariableStatement,
20661             updateVariableStatement: updateVariableStatement,
20662             createEmptyStatement: createEmptyStatement,
20663             createExpressionStatement: createExpressionStatement,
20664             updateExpressionStatement: updateExpressionStatement,
20665             createIfStatement: createIfStatement,
20666             updateIfStatement: updateIfStatement,
20667             createDoStatement: createDoStatement,
20668             updateDoStatement: updateDoStatement,
20669             createWhileStatement: createWhileStatement,
20670             updateWhileStatement: updateWhileStatement,
20671             createForStatement: createForStatement,
20672             updateForStatement: updateForStatement,
20673             createForInStatement: createForInStatement,
20674             updateForInStatement: updateForInStatement,
20675             createForOfStatement: createForOfStatement,
20676             updateForOfStatement: updateForOfStatement,
20677             createContinueStatement: createContinueStatement,
20678             updateContinueStatement: updateContinueStatement,
20679             createBreakStatement: createBreakStatement,
20680             updateBreakStatement: updateBreakStatement,
20681             createReturnStatement: createReturnStatement,
20682             updateReturnStatement: updateReturnStatement,
20683             createWithStatement: createWithStatement,
20684             updateWithStatement: updateWithStatement,
20685             createSwitchStatement: createSwitchStatement,
20686             updateSwitchStatement: updateSwitchStatement,
20687             createLabeledStatement: createLabeledStatement,
20688             updateLabeledStatement: updateLabeledStatement,
20689             createThrowStatement: createThrowStatement,
20690             updateThrowStatement: updateThrowStatement,
20691             createTryStatement: createTryStatement,
20692             updateTryStatement: updateTryStatement,
20693             createDebuggerStatement: createDebuggerStatement,
20694             createVariableDeclaration: createVariableDeclaration,
20695             updateVariableDeclaration: updateVariableDeclaration,
20696             createVariableDeclarationList: createVariableDeclarationList,
20697             updateVariableDeclarationList: updateVariableDeclarationList,
20698             createFunctionDeclaration: createFunctionDeclaration,
20699             updateFunctionDeclaration: updateFunctionDeclaration,
20700             createClassDeclaration: createClassDeclaration,
20701             updateClassDeclaration: updateClassDeclaration,
20702             createInterfaceDeclaration: createInterfaceDeclaration,
20703             updateInterfaceDeclaration: updateInterfaceDeclaration,
20704             createTypeAliasDeclaration: createTypeAliasDeclaration,
20705             updateTypeAliasDeclaration: updateTypeAliasDeclaration,
20706             createEnumDeclaration: createEnumDeclaration,
20707             updateEnumDeclaration: updateEnumDeclaration,
20708             createModuleDeclaration: createModuleDeclaration,
20709             updateModuleDeclaration: updateModuleDeclaration,
20710             createModuleBlock: createModuleBlock,
20711             updateModuleBlock: updateModuleBlock,
20712             createCaseBlock: createCaseBlock,
20713             updateCaseBlock: updateCaseBlock,
20714             createNamespaceExportDeclaration: createNamespaceExportDeclaration,
20715             updateNamespaceExportDeclaration: updateNamespaceExportDeclaration,
20716             createImportEqualsDeclaration: createImportEqualsDeclaration,
20717             updateImportEqualsDeclaration: updateImportEqualsDeclaration,
20718             createImportDeclaration: createImportDeclaration,
20719             updateImportDeclaration: updateImportDeclaration,
20720             createImportClause: createImportClause,
20721             updateImportClause: updateImportClause,
20722             createNamespaceImport: createNamespaceImport,
20723             updateNamespaceImport: updateNamespaceImport,
20724             createNamespaceExport: createNamespaceExport,
20725             updateNamespaceExport: updateNamespaceExport,
20726             createNamedImports: createNamedImports,
20727             updateNamedImports: updateNamedImports,
20728             createImportSpecifier: createImportSpecifier,
20729             updateImportSpecifier: updateImportSpecifier,
20730             createExportAssignment: createExportAssignment,
20731             updateExportAssignment: updateExportAssignment,
20732             createExportDeclaration: createExportDeclaration,
20733             updateExportDeclaration: updateExportDeclaration,
20734             createNamedExports: createNamedExports,
20735             updateNamedExports: updateNamedExports,
20736             createExportSpecifier: createExportSpecifier,
20737             updateExportSpecifier: updateExportSpecifier,
20738             createMissingDeclaration: createMissingDeclaration,
20739             createExternalModuleReference: createExternalModuleReference,
20740             updateExternalModuleReference: updateExternalModuleReference,
20741             // lazily load factory members for JSDoc types with similar structure
20742             get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(303 /* JSDocAllType */); },
20743             get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(304 /* JSDocUnknownType */); },
20744             get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(306 /* JSDocNonNullableType */); },
20745             get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(306 /* JSDocNonNullableType */); },
20746             get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(305 /* JSDocNullableType */); },
20747             get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(305 /* JSDocNullableType */); },
20748             get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(307 /* JSDocOptionalType */); },
20749             get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(307 /* JSDocOptionalType */); },
20750             get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(309 /* JSDocVariadicType */); },
20751             get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(309 /* JSDocVariadicType */); },
20752             get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(310 /* JSDocNamepathType */); },
20753             get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(310 /* JSDocNamepathType */); },
20754             createJSDocFunctionType: createJSDocFunctionType,
20755             updateJSDocFunctionType: updateJSDocFunctionType,
20756             createJSDocTypeLiteral: createJSDocTypeLiteral,
20757             updateJSDocTypeLiteral: updateJSDocTypeLiteral,
20758             createJSDocTypeExpression: createJSDocTypeExpression,
20759             updateJSDocTypeExpression: updateJSDocTypeExpression,
20760             createJSDocSignature: createJSDocSignature,
20761             updateJSDocSignature: updateJSDocSignature,
20762             createJSDocTemplateTag: createJSDocTemplateTag,
20763             updateJSDocTemplateTag: updateJSDocTemplateTag,
20764             createJSDocTypedefTag: createJSDocTypedefTag,
20765             updateJSDocTypedefTag: updateJSDocTypedefTag,
20766             createJSDocParameterTag: createJSDocParameterTag,
20767             updateJSDocParameterTag: updateJSDocParameterTag,
20768             createJSDocPropertyTag: createJSDocPropertyTag,
20769             updateJSDocPropertyTag: updateJSDocPropertyTag,
20770             createJSDocCallbackTag: createJSDocCallbackTag,
20771             updateJSDocCallbackTag: updateJSDocCallbackTag,
20772             createJSDocAugmentsTag: createJSDocAugmentsTag,
20773             updateJSDocAugmentsTag: updateJSDocAugmentsTag,
20774             createJSDocImplementsTag: createJSDocImplementsTag,
20775             updateJSDocImplementsTag: updateJSDocImplementsTag,
20776             createJSDocSeeTag: createJSDocSeeTag,
20777             updateJSDocSeeTag: updateJSDocSeeTag,
20778             createJSDocNameReference: createJSDocNameReference,
20779             updateJSDocNameReference: updateJSDocNameReference,
20780             // lazily load factory members for JSDoc tags with similar structure
20781             get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(329 /* JSDocTypeTag */); },
20782             get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(329 /* JSDocTypeTag */); },
20783             get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(327 /* JSDocReturnTag */); },
20784             get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(327 /* JSDocReturnTag */); },
20785             get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(328 /* JSDocThisTag */); },
20786             get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(328 /* JSDocThisTag */); },
20787             get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(325 /* JSDocEnumTag */); },
20788             get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(325 /* JSDocEnumTag */); },
20789             get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(317 /* JSDocAuthorTag */); },
20790             get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(317 /* JSDocAuthorTag */); },
20791             get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(319 /* JSDocClassTag */); },
20792             get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(319 /* JSDocClassTag */); },
20793             get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(320 /* JSDocPublicTag */); },
20794             get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(320 /* JSDocPublicTag */); },
20795             get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(321 /* JSDocPrivateTag */); },
20796             get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(321 /* JSDocPrivateTag */); },
20797             get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(322 /* JSDocProtectedTag */); },
20798             get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(322 /* JSDocProtectedTag */); },
20799             get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(323 /* JSDocReadonlyTag */); },
20800             get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(323 /* JSDocReadonlyTag */); },
20801             get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(318 /* JSDocDeprecatedTag */); },
20802             get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(318 /* JSDocDeprecatedTag */); },
20803             createJSDocUnknownTag: createJSDocUnknownTag,
20804             updateJSDocUnknownTag: updateJSDocUnknownTag,
20805             createJSDocComment: createJSDocComment,
20806             updateJSDocComment: updateJSDocComment,
20807             createJsxElement: createJsxElement,
20808             updateJsxElement: updateJsxElement,
20809             createJsxSelfClosingElement: createJsxSelfClosingElement,
20810             updateJsxSelfClosingElement: updateJsxSelfClosingElement,
20811             createJsxOpeningElement: createJsxOpeningElement,
20812             updateJsxOpeningElement: updateJsxOpeningElement,
20813             createJsxClosingElement: createJsxClosingElement,
20814             updateJsxClosingElement: updateJsxClosingElement,
20815             createJsxFragment: createJsxFragment,
20816             createJsxText: createJsxText,
20817             updateJsxText: updateJsxText,
20818             createJsxOpeningFragment: createJsxOpeningFragment,
20819             createJsxJsxClosingFragment: createJsxJsxClosingFragment,
20820             updateJsxFragment: updateJsxFragment,
20821             createJsxAttribute: createJsxAttribute,
20822             updateJsxAttribute: updateJsxAttribute,
20823             createJsxAttributes: createJsxAttributes,
20824             updateJsxAttributes: updateJsxAttributes,
20825             createJsxSpreadAttribute: createJsxSpreadAttribute,
20826             updateJsxSpreadAttribute: updateJsxSpreadAttribute,
20827             createJsxExpression: createJsxExpression,
20828             updateJsxExpression: updateJsxExpression,
20829             createCaseClause: createCaseClause,
20830             updateCaseClause: updateCaseClause,
20831             createDefaultClause: createDefaultClause,
20832             updateDefaultClause: updateDefaultClause,
20833             createHeritageClause: createHeritageClause,
20834             updateHeritageClause: updateHeritageClause,
20835             createCatchClause: createCatchClause,
20836             updateCatchClause: updateCatchClause,
20837             createPropertyAssignment: createPropertyAssignment,
20838             updatePropertyAssignment: updatePropertyAssignment,
20839             createShorthandPropertyAssignment: createShorthandPropertyAssignment,
20840             updateShorthandPropertyAssignment: updateShorthandPropertyAssignment,
20841             createSpreadAssignment: createSpreadAssignment,
20842             updateSpreadAssignment: updateSpreadAssignment,
20843             createEnumMember: createEnumMember,
20844             updateEnumMember: updateEnumMember,
20845             createSourceFile: createSourceFile,
20846             updateSourceFile: updateSourceFile,
20847             createBundle: createBundle,
20848             updateBundle: updateBundle,
20849             createUnparsedSource: createUnparsedSource,
20850             createUnparsedPrologue: createUnparsedPrologue,
20851             createUnparsedPrepend: createUnparsedPrepend,
20852             createUnparsedTextLike: createUnparsedTextLike,
20853             createUnparsedSyntheticReference: createUnparsedSyntheticReference,
20854             createInputFiles: createInputFiles,
20855             createSyntheticExpression: createSyntheticExpression,
20856             createSyntaxList: createSyntaxList,
20857             createNotEmittedStatement: createNotEmittedStatement,
20858             createPartiallyEmittedExpression: createPartiallyEmittedExpression,
20859             updatePartiallyEmittedExpression: updatePartiallyEmittedExpression,
20860             createCommaListExpression: createCommaListExpression,
20861             updateCommaListExpression: updateCommaListExpression,
20862             createEndOfDeclarationMarker: createEndOfDeclarationMarker,
20863             createMergeDeclarationMarker: createMergeDeclarationMarker,
20864             createSyntheticReferenceExpression: createSyntheticReferenceExpression,
20865             updateSyntheticReferenceExpression: updateSyntheticReferenceExpression,
20866             cloneNode: cloneNode,
20867             // Lazily load factory methods for common operator factories and utilities
20868             get createComma() { return getBinaryCreateFunction(27 /* CommaToken */); },
20869             get createAssignment() { return getBinaryCreateFunction(62 /* EqualsToken */); },
20870             get createLogicalOr() { return getBinaryCreateFunction(56 /* BarBarToken */); },
20871             get createLogicalAnd() { return getBinaryCreateFunction(55 /* AmpersandAmpersandToken */); },
20872             get createBitwiseOr() { return getBinaryCreateFunction(51 /* BarToken */); },
20873             get createBitwiseXor() { return getBinaryCreateFunction(52 /* CaretToken */); },
20874             get createBitwiseAnd() { return getBinaryCreateFunction(50 /* AmpersandToken */); },
20875             get createStrictEquality() { return getBinaryCreateFunction(36 /* EqualsEqualsEqualsToken */); },
20876             get createStrictInequality() { return getBinaryCreateFunction(37 /* ExclamationEqualsEqualsToken */); },
20877             get createEquality() { return getBinaryCreateFunction(34 /* EqualsEqualsToken */); },
20878             get createInequality() { return getBinaryCreateFunction(35 /* ExclamationEqualsToken */); },
20879             get createLessThan() { return getBinaryCreateFunction(29 /* LessThanToken */); },
20880             get createLessThanEquals() { return getBinaryCreateFunction(32 /* LessThanEqualsToken */); },
20881             get createGreaterThan() { return getBinaryCreateFunction(31 /* GreaterThanToken */); },
20882             get createGreaterThanEquals() { return getBinaryCreateFunction(33 /* GreaterThanEqualsToken */); },
20883             get createLeftShift() { return getBinaryCreateFunction(47 /* LessThanLessThanToken */); },
20884             get createRightShift() { return getBinaryCreateFunction(48 /* GreaterThanGreaterThanToken */); },
20885             get createUnsignedRightShift() { return getBinaryCreateFunction(49 /* GreaterThanGreaterThanGreaterThanToken */); },
20886             get createAdd() { return getBinaryCreateFunction(39 /* PlusToken */); },
20887             get createSubtract() { return getBinaryCreateFunction(40 /* MinusToken */); },
20888             get createMultiply() { return getBinaryCreateFunction(41 /* AsteriskToken */); },
20889             get createDivide() { return getBinaryCreateFunction(43 /* SlashToken */); },
20890             get createModulo() { return getBinaryCreateFunction(44 /* PercentToken */); },
20891             get createExponent() { return getBinaryCreateFunction(42 /* AsteriskAsteriskToken */); },
20892             get createPrefixPlus() { return getPrefixUnaryCreateFunction(39 /* PlusToken */); },
20893             get createPrefixMinus() { return getPrefixUnaryCreateFunction(40 /* MinusToken */); },
20894             get createPrefixIncrement() { return getPrefixUnaryCreateFunction(45 /* PlusPlusToken */); },
20895             get createPrefixDecrement() { return getPrefixUnaryCreateFunction(46 /* MinusMinusToken */); },
20896             get createBitwiseNot() { return getPrefixUnaryCreateFunction(54 /* TildeToken */); },
20897             get createLogicalNot() { return getPrefixUnaryCreateFunction(53 /* ExclamationToken */); },
20898             get createPostfixIncrement() { return getPostfixUnaryCreateFunction(45 /* PlusPlusToken */); },
20899             get createPostfixDecrement() { return getPostfixUnaryCreateFunction(46 /* MinusMinusToken */); },
20900             // Compound nodes
20901             createImmediatelyInvokedFunctionExpression: createImmediatelyInvokedFunctionExpression,
20902             createImmediatelyInvokedArrowFunction: createImmediatelyInvokedArrowFunction,
20903             createVoidZero: createVoidZero,
20904             createExportDefault: createExportDefault,
20905             createExternalModuleExport: createExternalModuleExport,
20906             createTypeCheck: createTypeCheck,
20907             createMethodCall: createMethodCall,
20908             createGlobalMethodCall: createGlobalMethodCall,
20909             createFunctionBindCall: createFunctionBindCall,
20910             createFunctionCallCall: createFunctionCallCall,
20911             createFunctionApplyCall: createFunctionApplyCall,
20912             createArraySliceCall: createArraySliceCall,
20913             createArrayConcatCall: createArrayConcatCall,
20914             createObjectDefinePropertyCall: createObjectDefinePropertyCall,
20915             createPropertyDescriptor: createPropertyDescriptor,
20916             createCallBinding: createCallBinding,
20917             // Utilities
20918             inlineExpressions: inlineExpressions,
20919             getInternalName: getInternalName,
20920             getLocalName: getLocalName,
20921             getExportName: getExportName,
20922             getDeclarationName: getDeclarationName,
20923             getNamespaceMemberName: getNamespaceMemberName,
20924             getExternalModuleOrNamespaceExportName: getExternalModuleOrNamespaceExportName,
20925             restoreOuterExpressions: restoreOuterExpressions,
20926             restoreEnclosingLabel: restoreEnclosingLabel,
20927             createUseStrictPrologue: createUseStrictPrologue,
20928             copyPrologue: copyPrologue,
20929             copyStandardPrologue: copyStandardPrologue,
20930             copyCustomPrologue: copyCustomPrologue,
20931             ensureUseStrict: ensureUseStrict,
20932             liftToBlock: liftToBlock,
20933             mergeLexicalEnvironment: mergeLexicalEnvironment,
20934             updateModifiers: updateModifiers,
20935         };
20936         return factory;
20937         // @api
20938         function createNodeArray(elements, hasTrailingComma) {
20939             if (elements === undefined || elements === ts.emptyArray) {
20940                 elements = [];
20941             }
20942             else if (ts.isNodeArray(elements)) {
20943                 // Ensure the transform flags have been aggregated for this NodeArray
20944                 if (elements.transformFlags === undefined) {
20945                     aggregateChildrenFlags(elements);
20946                 }
20947                 ts.Debug.attachNodeArrayDebugInfo(elements);
20948                 return elements;
20949             }
20950             // Since the element list of a node array is typically created by starting with an empty array and
20951             // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
20952             // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
20953             var length = elements.length;
20954             var array = (length >= 1 && length <= 4 ? elements.slice() : elements);
20955             ts.setTextRangePosEnd(array, -1, -1);
20956             array.hasTrailingComma = !!hasTrailingComma;
20957             aggregateChildrenFlags(array);
20958             ts.Debug.attachNodeArrayDebugInfo(array);
20959             return array;
20960         }
20961         function createBaseNode(kind) {
20962             return baseFactory.createBaseNode(kind);
20963         }
20964         function createBaseDeclaration(kind, decorators, modifiers) {
20965             var node = createBaseNode(kind);
20966             node.decorators = asNodeArray(decorators);
20967             node.modifiers = asNodeArray(modifiers);
20968             node.transformFlags |=
20969                 propagateChildrenFlags(node.decorators) |
20970                     propagateChildrenFlags(node.modifiers);
20971             // NOTE: The following properties are commonly set by the binder and are added here to
20972             // ensure declarations have a stable shape.
20973             node.symbol = undefined; // initialized by binder
20974             node.localSymbol = undefined; // initialized by binder
20975             node.locals = undefined; // initialized by binder
20976             node.nextContainer = undefined; // initialized by binder
20977             return node;
20978         }
20979         function createBaseNamedDeclaration(kind, decorators, modifiers, name) {
20980             var node = createBaseDeclaration(kind, decorators, modifiers);
20981             name = asName(name);
20982             node.name = name;
20983             // The PropertyName of a member is allowed to be `await`.
20984             // We don't need to exclude `await` for type signatures since types
20985             // don't propagate child flags.
20986             if (name) {
20987                 switch (node.kind) {
20988                     case 165 /* MethodDeclaration */:
20989                     case 167 /* GetAccessor */:
20990                     case 168 /* SetAccessor */:
20991                     case 163 /* PropertyDeclaration */:
20992                     case 288 /* PropertyAssignment */:
20993                         if (ts.isIdentifier(name)) {
20994                             node.transformFlags |= propagateIdentifierNameFlags(name);
20995                             break;
20996                         }
20997                     // fall through
20998                     default:
20999                         node.transformFlags |= propagateChildFlags(name);
21000                         break;
21001                 }
21002             }
21003             return node;
21004         }
21005         function createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters) {
21006             var node = createBaseNamedDeclaration(kind, decorators, modifiers, name);
21007             node.typeParameters = asNodeArray(typeParameters);
21008             node.transformFlags |= propagateChildrenFlags(node.typeParameters);
21009             if (typeParameters)
21010                 node.transformFlags |= 1 /* ContainsTypeScript */;
21011             return node;
21012         }
21013         function createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type) {
21014             var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters);
21015             node.parameters = createNodeArray(parameters);
21016             node.type = type;
21017             node.transformFlags |=
21018                 propagateChildrenFlags(node.parameters) |
21019                     propagateChildFlags(node.type);
21020             if (type)
21021                 node.transformFlags |= 1 /* ContainsTypeScript */;
21022             return node;
21023         }
21024         function updateBaseSignatureDeclaration(updated, original) {
21025             // copy children used only for error reporting
21026             if (original.typeArguments)
21027                 updated.typeArguments = original.typeArguments;
21028             return update(updated, original);
21029         }
21030         function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) {
21031             var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type);
21032             node.body = body;
21033             node.transformFlags |= propagateChildFlags(node.body) & ~8388608 /* ContainsPossibleTopLevelAwait */;
21034             if (!body)
21035                 node.transformFlags |= 1 /* ContainsTypeScript */;
21036             return node;
21037         }
21038         function updateBaseFunctionLikeDeclaration(updated, original) {
21039             // copy children used only for error reporting
21040             if (original.exclamationToken)
21041                 updated.exclamationToken = original.exclamationToken;
21042             if (original.typeArguments)
21043                 updated.typeArguments = original.typeArguments;
21044             return updateBaseSignatureDeclaration(updated, original);
21045         }
21046         function createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses) {
21047             var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters);
21048             node.heritageClauses = asNodeArray(heritageClauses);
21049             node.transformFlags |= propagateChildrenFlags(node.heritageClauses);
21050             return node;
21051         }
21052         function createBaseClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses, members) {
21053             var node = createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses);
21054             node.members = createNodeArray(members);
21055             node.transformFlags |= propagateChildrenFlags(node.members);
21056             return node;
21057         }
21058         function createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer) {
21059             var node = createBaseNamedDeclaration(kind, decorators, modifiers, name);
21060             node.initializer = initializer;
21061             node.transformFlags |= propagateChildFlags(node.initializer);
21062             return node;
21063         }
21064         function createBaseVariableLikeDeclaration(kind, decorators, modifiers, name, type, initializer) {
21065             var node = createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer);
21066             node.type = type;
21067             node.transformFlags |= propagateChildFlags(type);
21068             if (type)
21069                 node.transformFlags |= 1 /* ContainsTypeScript */;
21070             return node;
21071         }
21072         //
21073         // Literals
21074         //
21075         function createBaseLiteral(kind, text) {
21076             var node = createBaseToken(kind);
21077             node.text = text;
21078             return node;
21079         }
21080         // @api
21081         function createNumericLiteral(value, numericLiteralFlags) {
21082             if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
21083             var node = createBaseLiteral(8 /* NumericLiteral */, typeof value === "number" ? value + "" : value);
21084             node.numericLiteralFlags = numericLiteralFlags;
21085             if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */)
21086                 node.transformFlags |= 256 /* ContainsES2015 */;
21087             return node;
21088         }
21089         // @api
21090         function createBigIntLiteral(value) {
21091             var node = createBaseLiteral(9 /* BigIntLiteral */, typeof value === "string" ? value : ts.pseudoBigIntToString(value) + "n");
21092             node.transformFlags |= 4 /* ContainsESNext */;
21093             return node;
21094         }
21095         function createBaseStringLiteral(text, isSingleQuote) {
21096             var node = createBaseLiteral(10 /* StringLiteral */, text);
21097             node.singleQuote = isSingleQuote;
21098             return node;
21099         }
21100         // @api
21101         function createStringLiteral(text, isSingleQuote, hasExtendedUnicodeEscape) {
21102             var node = createBaseStringLiteral(text, isSingleQuote);
21103             node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape;
21104             if (hasExtendedUnicodeEscape)
21105                 node.transformFlags |= 256 /* ContainsES2015 */;
21106             return node;
21107         }
21108         // @api
21109         function createStringLiteralFromNode(sourceNode) {
21110             var node = createBaseStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode), /*isSingleQuote*/ undefined);
21111             node.textSourceNode = sourceNode;
21112             return node;
21113         }
21114         // @api
21115         function createRegularExpressionLiteral(text) {
21116             var node = createBaseLiteral(13 /* RegularExpressionLiteral */, text);
21117             return node;
21118         }
21119         // @api
21120         function createLiteralLikeNode(kind, text) {
21121             switch (kind) {
21122                 case 8 /* NumericLiteral */: return createNumericLiteral(text, /*numericLiteralFlags*/ 0);
21123                 case 9 /* BigIntLiteral */: return createBigIntLiteral(text);
21124                 case 10 /* StringLiteral */: return createStringLiteral(text, /*isSingleQuote*/ undefined);
21125                 case 11 /* JsxText */: return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ false);
21126                 case 12 /* JsxTextAllWhiteSpaces */: return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ true);
21127                 case 13 /* RegularExpressionLiteral */: return createRegularExpressionLiteral(text);
21128                 case 14 /* NoSubstitutionTemplateLiteral */: return createTemplateLiteralLikeNode(kind, text, /*rawText*/ undefined, /*templateFlags*/ 0);
21129             }
21130         }
21131         //
21132         // Identifiers
21133         //
21134         function createBaseIdentifier(text, originalKeywordKind) {
21135             if (originalKeywordKind === undefined && text) {
21136                 originalKeywordKind = ts.stringToToken(text);
21137             }
21138             if (originalKeywordKind === 78 /* Identifier */) {
21139                 originalKeywordKind = undefined;
21140             }
21141             var node = baseFactory.createBaseIdentifierNode(78 /* Identifier */);
21142             node.originalKeywordKind = originalKeywordKind;
21143             node.escapedText = ts.escapeLeadingUnderscores(text);
21144             return node;
21145         }
21146         function createBaseGeneratedIdentifier(text, autoGenerateFlags) {
21147             var node = createBaseIdentifier(text, /*originalKeywordKind*/ undefined);
21148             node.autoGenerateFlags = autoGenerateFlags;
21149             node.autoGenerateId = nextAutoGenerateId;
21150             nextAutoGenerateId++;
21151             return node;
21152         }
21153         // @api
21154         function createIdentifier(text, typeArguments, originalKeywordKind) {
21155             var node = createBaseIdentifier(text, originalKeywordKind);
21156             if (typeArguments) {
21157                 // NOTE: we do not use `setChildren` here because typeArguments in an identifier do not contribute to transformations
21158                 node.typeArguments = createNodeArray(typeArguments);
21159             }
21160             if (node.originalKeywordKind === 130 /* AwaitKeyword */) {
21161                 node.transformFlags |= 8388608 /* ContainsPossibleTopLevelAwait */;
21162             }
21163             return node;
21164         }
21165         // @api
21166         function updateIdentifier(node, typeArguments) {
21167             return node.typeArguments !== typeArguments
21168                 ? update(createIdentifier(ts.idText(node), typeArguments), node)
21169                 : node;
21170         }
21171         // @api
21172         function createTempVariable(recordTempVariable, reservedInNestedScopes) {
21173             var flags = 1 /* Auto */;
21174             if (reservedInNestedScopes)
21175                 flags |= 8 /* ReservedInNestedScopes */;
21176             var name = createBaseGeneratedIdentifier("", flags);
21177             if (recordTempVariable) {
21178                 recordTempVariable(name);
21179             }
21180             return name;
21181         }
21182         /** Create a unique temporary variable for use in a loop. */
21183         // @api
21184         function createLoopVariable() {
21185             return createBaseGeneratedIdentifier("", 2 /* Loop */);
21186         }
21187         /** Create a unique name based on the supplied text. */
21188         // @api
21189         function createUniqueName(text, flags) {
21190             if (flags === void 0) { flags = 0 /* None */; }
21191             ts.Debug.assert(!(flags & 7 /* KindMask */), "Argument out of range: flags");
21192             ts.Debug.assert((flags & (16 /* Optimistic */ | 32 /* FileLevel */)) !== 32 /* FileLevel */, "GeneratedIdentifierFlags.FileLevel cannot be set without also setting GeneratedIdentifierFlags.Optimistic");
21193             return createBaseGeneratedIdentifier(text, 3 /* Unique */ | flags);
21194         }
21195         /** Create a unique name generated for a node. */
21196         // @api
21197         function getGeneratedNameForNode(node, flags) {
21198             if (flags === void 0) { flags = 0; }
21199             ts.Debug.assert(!(flags & 7 /* KindMask */), "Argument out of range: flags");
21200             var name = createBaseGeneratedIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "", 4 /* Node */ | flags);
21201             name.original = node;
21202             return name;
21203         }
21204         // @api
21205         function createPrivateIdentifier(text) {
21206             if (!ts.startsWith(text, "#"))
21207                 ts.Debug.fail("First character of private identifier must be #: " + text);
21208             var node = baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */);
21209             node.escapedText = ts.escapeLeadingUnderscores(text);
21210             node.transformFlags |= 4194304 /* ContainsClassFields */;
21211             return node;
21212         }
21213         //
21214         // Punctuation
21215         //
21216         function createBaseToken(kind) {
21217             return baseFactory.createBaseTokenNode(kind);
21218         }
21219         function createToken(token) {
21220             ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 156 /* LastToken */, "Invalid token");
21221             ts.Debug.assert(token <= 14 /* FirstTemplateToken */ || token >= 17 /* LastTemplateToken */, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals.");
21222             ts.Debug.assert(token <= 8 /* FirstLiteralToken */ || token >= 14 /* LastLiteralToken */, "Invalid token. Use 'createLiteralLikeNode' to create literals.");
21223             ts.Debug.assert(token !== 78 /* Identifier */, "Invalid token. Use 'createIdentifier' to create identifiers");
21224             var node = createBaseToken(token);
21225             var transformFlags = 0 /* None */;
21226             switch (token) {
21227                 case 129 /* AsyncKeyword */:
21228                     // 'async' modifier is ES2017 (async functions) or ES2018 (async generators)
21229                     transformFlags =
21230                         64 /* ContainsES2017 */ |
21231                             32 /* ContainsES2018 */;
21232                     break;
21233                 case 122 /* PublicKeyword */:
21234                 case 120 /* PrivateKeyword */:
21235                 case 121 /* ProtectedKeyword */:
21236                 case 142 /* ReadonlyKeyword */:
21237                 case 125 /* AbstractKeyword */:
21238                 case 133 /* DeclareKeyword */:
21239                 case 84 /* ConstKeyword */:
21240                 case 128 /* AnyKeyword */:
21241                 case 144 /* NumberKeyword */:
21242                 case 155 /* BigIntKeyword */:
21243                 case 141 /* NeverKeyword */:
21244                 case 145 /* ObjectKeyword */:
21245                 case 147 /* StringKeyword */:
21246                 case 131 /* BooleanKeyword */:
21247                 case 148 /* SymbolKeyword */:
21248                 case 113 /* VoidKeyword */:
21249                 case 152 /* UnknownKeyword */:
21250                 case 150 /* UndefinedKeyword */: // `undefined` is an Identifier in the expression case.
21251                     transformFlags = 1 /* ContainsTypeScript */;
21252                     break;
21253                 case 123 /* StaticKeyword */:
21254                 case 105 /* SuperKeyword */:
21255                     transformFlags = 256 /* ContainsES2015 */;
21256                     break;
21257                 case 107 /* ThisKeyword */:
21258                     // 'this' indicates a lexical 'this'
21259                     transformFlags = 4096 /* ContainsLexicalThis */;
21260                     break;
21261             }
21262             if (transformFlags) {
21263                 node.transformFlags |= transformFlags;
21264             }
21265             return node;
21266         }
21267         //
21268         // Reserved words
21269         //
21270         // @api
21271         function createSuper() {
21272             return createToken(105 /* SuperKeyword */);
21273         }
21274         // @api
21275         function createThis() {
21276             return createToken(107 /* ThisKeyword */);
21277         }
21278         // @api
21279         function createNull() {
21280             return createToken(103 /* NullKeyword */);
21281         }
21282         // @api
21283         function createTrue() {
21284             return createToken(109 /* TrueKeyword */);
21285         }
21286         // @api
21287         function createFalse() {
21288             return createToken(94 /* FalseKeyword */);
21289         }
21290         //
21291         // Modifiers
21292         //
21293         // @api
21294         function createModifier(kind) {
21295             return createToken(kind);
21296         }
21297         // @api
21298         function createModifiersFromModifierFlags(flags) {
21299             var result = [];
21300             if (flags & 1 /* Export */) {
21301                 result.push(createModifier(92 /* ExportKeyword */));
21302             }
21303             if (flags & 2 /* Ambient */) {
21304                 result.push(createModifier(133 /* DeclareKeyword */));
21305             }
21306             if (flags & 512 /* Default */) {
21307                 result.push(createModifier(87 /* DefaultKeyword */));
21308             }
21309             if (flags & 2048 /* Const */) {
21310                 result.push(createModifier(84 /* ConstKeyword */));
21311             }
21312             if (flags & 4 /* Public */) {
21313                 result.push(createModifier(122 /* PublicKeyword */));
21314             }
21315             if (flags & 8 /* Private */) {
21316                 result.push(createModifier(120 /* PrivateKeyword */));
21317             }
21318             if (flags & 16 /* Protected */) {
21319                 result.push(createModifier(121 /* ProtectedKeyword */));
21320             }
21321             if (flags & 128 /* Abstract */) {
21322                 result.push(createModifier(125 /* AbstractKeyword */));
21323             }
21324             if (flags & 32 /* Static */) {
21325                 result.push(createModifier(123 /* StaticKeyword */));
21326             }
21327             if (flags & 64 /* Readonly */) {
21328                 result.push(createModifier(142 /* ReadonlyKeyword */));
21329             }
21330             if (flags & 256 /* Async */) {
21331                 result.push(createModifier(129 /* AsyncKeyword */));
21332             }
21333             return result;
21334         }
21335         //
21336         // Names
21337         //
21338         // @api
21339         function createQualifiedName(left, right) {
21340             var node = createBaseNode(157 /* QualifiedName */);
21341             node.left = left;
21342             node.right = asName(right);
21343             node.transformFlags |=
21344                 propagateChildFlags(node.left) |
21345                     propagateIdentifierNameFlags(node.right);
21346             return node;
21347         }
21348         // @api
21349         function updateQualifiedName(node, left, right) {
21350             return node.left !== left
21351                 || node.right !== right
21352                 ? update(createQualifiedName(left, right), node)
21353                 : node;
21354         }
21355         // @api
21356         function createComputedPropertyName(expression) {
21357             var node = createBaseNode(158 /* ComputedPropertyName */);
21358             node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression);
21359             node.transformFlags |=
21360                 propagateChildFlags(node.expression) |
21361                     256 /* ContainsES2015 */ |
21362                     32768 /* ContainsComputedPropertyName */;
21363             return node;
21364         }
21365         // @api
21366         function updateComputedPropertyName(node, expression) {
21367             return node.expression !== expression
21368                 ? update(createComputedPropertyName(expression), node)
21369                 : node;
21370         }
21371         //
21372         // Signature elements
21373         //
21374         // @api
21375         function createTypeParameterDeclaration(name, constraint, defaultType) {
21376             var node = createBaseNamedDeclaration(159 /* TypeParameter */, 
21377             /*decorators*/ undefined, 
21378             /*modifiers*/ undefined, name);
21379             node.constraint = constraint;
21380             node.default = defaultType;
21381             node.transformFlags = 1 /* ContainsTypeScript */;
21382             return node;
21383         }
21384         // @api
21385         function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
21386             return node.name !== name
21387                 || node.constraint !== constraint
21388                 || node.default !== defaultType
21389                 ? update(createTypeParameterDeclaration(name, constraint, defaultType), node)
21390                 : node;
21391         }
21392         // @api
21393         function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
21394             var node = createBaseVariableLikeDeclaration(160 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer));
21395             node.dotDotDotToken = dotDotDotToken;
21396             node.questionToken = questionToken;
21397             if (ts.isThisIdentifier(node.name)) {
21398                 node.transformFlags = 1 /* ContainsTypeScript */;
21399             }
21400             else {
21401                 node.transformFlags |=
21402                     propagateChildFlags(node.dotDotDotToken) |
21403                         propagateChildFlags(node.questionToken);
21404                 if (questionToken)
21405                     node.transformFlags |= 1 /* ContainsTypeScript */;
21406                 if (ts.modifiersToFlags(node.modifiers) & 92 /* ParameterPropertyModifier */)
21407                     node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
21408                 if (initializer || dotDotDotToken)
21409                     node.transformFlags |= 256 /* ContainsES2015 */;
21410             }
21411             return node;
21412         }
21413         // @api
21414         function updateParameterDeclaration(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
21415             return node.decorators !== decorators
21416                 || node.modifiers !== modifiers
21417                 || node.dotDotDotToken !== dotDotDotToken
21418                 || node.name !== name
21419                 || node.questionToken !== questionToken
21420                 || node.type !== type
21421                 || node.initializer !== initializer
21422                 ? update(createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node)
21423                 : node;
21424         }
21425         // @api
21426         function createDecorator(expression) {
21427             var node = createBaseNode(161 /* Decorator */);
21428             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21429             node.transformFlags |=
21430                 propagateChildFlags(node.expression) |
21431                     1 /* ContainsTypeScript */ |
21432                     2048 /* ContainsTypeScriptClassSyntax */;
21433             return node;
21434         }
21435         // @api
21436         function updateDecorator(node, expression) {
21437             return node.expression !== expression
21438                 ? update(createDecorator(expression), node)
21439                 : node;
21440         }
21441         //
21442         // Type Elements
21443         //
21444         // @api
21445         function createPropertySignature(modifiers, name, questionToken, type) {
21446             var node = createBaseNamedDeclaration(162 /* PropertySignature */, 
21447             /*decorators*/ undefined, modifiers, name);
21448             node.type = type;
21449             node.questionToken = questionToken;
21450             node.transformFlags = 1 /* ContainsTypeScript */;
21451             return node;
21452         }
21453         // @api
21454         function updatePropertySignature(node, modifiers, name, questionToken, type) {
21455             return node.modifiers !== modifiers
21456                 || node.name !== name
21457                 || node.questionToken !== questionToken
21458                 || node.type !== type
21459                 ? update(createPropertySignature(modifiers, name, questionToken, type), node)
21460                 : node;
21461         }
21462         // @api
21463         function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
21464             var node = createBaseVariableLikeDeclaration(163 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer);
21465             node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
21466             node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
21467             node.transformFlags |=
21468                 propagateChildFlags(node.questionToken) |
21469                     propagateChildFlags(node.exclamationToken) |
21470                     4194304 /* ContainsClassFields */;
21471             if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) {
21472                 node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
21473             }
21474             if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
21475                 node.transformFlags |= 1 /* ContainsTypeScript */;
21476             }
21477             return node;
21478         }
21479         // @api
21480         function updatePropertyDeclaration(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
21481             return node.decorators !== decorators
21482                 || node.modifiers !== modifiers
21483                 || node.name !== name
21484                 || node.questionToken !== (questionOrExclamationToken !== undefined && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
21485                 || node.exclamationToken !== (questionOrExclamationToken !== undefined && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
21486                 || node.type !== type
21487                 || node.initializer !== initializer
21488                 ? update(createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
21489                 : node;
21490         }
21491         // @api
21492         function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) {
21493             var node = createBaseSignatureDeclaration(164 /* MethodSignature */, 
21494             /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type);
21495             node.questionToken = questionToken;
21496             node.transformFlags = 1 /* ContainsTypeScript */;
21497             return node;
21498         }
21499         // @api
21500         function updateMethodSignature(node, modifiers, name, questionToken, typeParameters, parameters, type) {
21501             return node.modifiers !== modifiers
21502                 || node.name !== name
21503                 || node.questionToken !== questionToken
21504                 || node.typeParameters !== typeParameters
21505                 || node.parameters !== parameters
21506                 || node.type !== type
21507                 ? updateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node)
21508                 : node;
21509         }
21510         // @api
21511         function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
21512             var node = createBaseFunctionLikeDeclaration(165 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body);
21513             node.asteriskToken = asteriskToken;
21514             node.questionToken = questionToken;
21515             node.transformFlags |=
21516                 propagateChildFlags(node.asteriskToken) |
21517                     propagateChildFlags(node.questionToken) |
21518                     256 /* ContainsES2015 */;
21519             if (questionToken) {
21520                 node.transformFlags |= 1 /* ContainsTypeScript */;
21521             }
21522             if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
21523                 if (asteriskToken) {
21524                     node.transformFlags |= 32 /* ContainsES2018 */;
21525                 }
21526                 else {
21527                     node.transformFlags |= 64 /* ContainsES2017 */;
21528                 }
21529             }
21530             else if (asteriskToken) {
21531                 node.transformFlags |= 512 /* ContainsGenerator */;
21532             }
21533             return node;
21534         }
21535         // @api
21536         function updateMethodDeclaration(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
21537             return node.decorators !== decorators
21538                 || node.modifiers !== modifiers
21539                 || node.asteriskToken !== asteriskToken
21540                 || node.name !== name
21541                 || node.questionToken !== questionToken
21542                 || node.typeParameters !== typeParameters
21543                 || node.parameters !== parameters
21544                 || node.type !== type
21545                 || node.body !== body
21546                 ? updateBaseFunctionLikeDeclaration(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
21547                 : node;
21548         }
21549         // @api
21550         function createConstructorDeclaration(decorators, modifiers, parameters, body) {
21551             var node = createBaseFunctionLikeDeclaration(166 /* Constructor */, decorators, modifiers, 
21552             /*name*/ undefined, 
21553             /*typeParameters*/ undefined, parameters, 
21554             /*type*/ undefined, body);
21555             node.transformFlags |= 256 /* ContainsES2015 */;
21556             return node;
21557         }
21558         // @api
21559         function updateConstructorDeclaration(node, decorators, modifiers, parameters, body) {
21560             return node.decorators !== decorators
21561                 || node.modifiers !== modifiers
21562                 || node.parameters !== parameters
21563                 || node.body !== body
21564                 ? updateBaseFunctionLikeDeclaration(createConstructorDeclaration(decorators, modifiers, parameters, body), node)
21565                 : node;
21566         }
21567         // @api
21568         function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) {
21569             return createBaseFunctionLikeDeclaration(167 /* GetAccessor */, decorators, modifiers, name, 
21570             /*typeParameters*/ undefined, parameters, type, body);
21571         }
21572         // @api
21573         function updateGetAccessorDeclaration(node, decorators, modifiers, name, parameters, type, body) {
21574             return node.decorators !== decorators
21575                 || node.modifiers !== modifiers
21576                 || node.name !== name
21577                 || node.parameters !== parameters
21578                 || node.type !== type
21579                 || node.body !== body
21580                 ? updateBaseFunctionLikeDeclaration(createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body), node)
21581                 : node;
21582         }
21583         // @api
21584         function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) {
21585             return createBaseFunctionLikeDeclaration(168 /* SetAccessor */, decorators, modifiers, name, 
21586             /*typeParameters*/ undefined, parameters, 
21587             /*type*/ undefined, body);
21588         }
21589         // @api
21590         function updateSetAccessorDeclaration(node, decorators, modifiers, name, parameters, body) {
21591             return node.decorators !== decorators
21592                 || node.modifiers !== modifiers
21593                 || node.name !== name
21594                 || node.parameters !== parameters
21595                 || node.body !== body
21596                 ? updateBaseFunctionLikeDeclaration(createSetAccessorDeclaration(decorators, modifiers, name, parameters, body), node)
21597                 : node;
21598         }
21599         // @api
21600         function createCallSignature(typeParameters, parameters, type) {
21601             var node = createBaseSignatureDeclaration(169 /* CallSignature */, 
21602             /*decorators*/ undefined, 
21603             /*modifiers*/ undefined, 
21604             /*name*/ undefined, typeParameters, parameters, type);
21605             node.transformFlags = 1 /* ContainsTypeScript */;
21606             return node;
21607         }
21608         // @api
21609         function updateCallSignature(node, typeParameters, parameters, type) {
21610             return node.typeParameters !== typeParameters
21611                 || node.parameters !== parameters
21612                 || node.type !== type
21613                 ? updateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node)
21614                 : node;
21615         }
21616         // @api
21617         function createConstructSignature(typeParameters, parameters, type) {
21618             var node = createBaseSignatureDeclaration(170 /* ConstructSignature */, 
21619             /*decorators*/ undefined, 
21620             /*modifiers*/ undefined, 
21621             /*name*/ undefined, typeParameters, parameters, type);
21622             node.transformFlags = 1 /* ContainsTypeScript */;
21623             return node;
21624         }
21625         // @api
21626         function updateConstructSignature(node, typeParameters, parameters, type) {
21627             return node.typeParameters !== typeParameters
21628                 || node.parameters !== parameters
21629                 || node.type !== type
21630                 ? updateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node)
21631                 : node;
21632         }
21633         // @api
21634         function createIndexSignature(decorators, modifiers, parameters, type) {
21635             var node = createBaseSignatureDeclaration(171 /* IndexSignature */, decorators, modifiers, 
21636             /*name*/ undefined, 
21637             /*typeParameters*/ undefined, parameters, type);
21638             node.transformFlags = 1 /* ContainsTypeScript */;
21639             return node;
21640         }
21641         // @api
21642         function updateIndexSignature(node, decorators, modifiers, parameters, type) {
21643             return node.parameters !== parameters
21644                 || node.type !== type
21645                 || node.decorators !== decorators
21646                 || node.modifiers !== modifiers
21647                 ? updateBaseSignatureDeclaration(createIndexSignature(decorators, modifiers, parameters, type), node)
21648                 : node;
21649         }
21650         // @api
21651         function createTemplateLiteralTypeSpan(type, literal) {
21652             var node = createBaseNode(194 /* TemplateLiteralTypeSpan */);
21653             node.type = type;
21654             node.literal = literal;
21655             node.transformFlags = 1 /* ContainsTypeScript */;
21656             return node;
21657         }
21658         // @api
21659         function updateTemplateLiteralTypeSpan(node, type, literal) {
21660             return node.type !== type
21661                 || node.literal !== literal
21662                 ? update(createTemplateLiteralTypeSpan(type, literal), node)
21663                 : node;
21664         }
21665         //
21666         // Types
21667         //
21668         // @api
21669         function createKeywordTypeNode(kind) {
21670             return createToken(kind);
21671         }
21672         // @api
21673         function createTypePredicateNode(assertsModifier, parameterName, type) {
21674             var node = createBaseNode(172 /* TypePredicate */);
21675             node.assertsModifier = assertsModifier;
21676             node.parameterName = asName(parameterName);
21677             node.type = type;
21678             node.transformFlags = 1 /* ContainsTypeScript */;
21679             return node;
21680         }
21681         // @api
21682         function updateTypePredicateNode(node, assertsModifier, parameterName, type) {
21683             return node.assertsModifier !== assertsModifier
21684                 || node.parameterName !== parameterName
21685                 || node.type !== type
21686                 ? update(createTypePredicateNode(assertsModifier, parameterName, type), node)
21687                 : node;
21688         }
21689         // @api
21690         function createTypeReferenceNode(typeName, typeArguments) {
21691             var node = createBaseNode(173 /* TypeReference */);
21692             node.typeName = asName(typeName);
21693             node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments));
21694             node.transformFlags = 1 /* ContainsTypeScript */;
21695             return node;
21696         }
21697         // @api
21698         function updateTypeReferenceNode(node, typeName, typeArguments) {
21699             return node.typeName !== typeName
21700                 || node.typeArguments !== typeArguments
21701                 ? update(createTypeReferenceNode(typeName, typeArguments), node)
21702                 : node;
21703         }
21704         // @api
21705         function createFunctionTypeNode(typeParameters, parameters, type) {
21706             var node = createBaseSignatureDeclaration(174 /* FunctionType */, 
21707             /*decorators*/ undefined, 
21708             /*modifiers*/ undefined, 
21709             /*name*/ undefined, typeParameters, parameters, type);
21710             node.transformFlags = 1 /* ContainsTypeScript */;
21711             return node;
21712         }
21713         // @api
21714         function updateFunctionTypeNode(node, typeParameters, parameters, type) {
21715             return node.typeParameters !== typeParameters
21716                 || node.parameters !== parameters
21717                 || node.type !== type
21718                 ? updateBaseSignatureDeclaration(createFunctionTypeNode(typeParameters, parameters, type), node)
21719                 : node;
21720         }
21721         // @api
21722         function createConstructorTypeNode() {
21723             var args = [];
21724             for (var _i = 0; _i < arguments.length; _i++) {
21725                 args[_i] = arguments[_i];
21726             }
21727             return args.length === 4 ? createConstructorTypeNode1.apply(void 0, args) :
21728                 args.length === 3 ? createConstructorTypeNode2.apply(void 0, args) :
21729                     ts.Debug.fail("Incorrect number of arguments specified.");
21730         }
21731         function createConstructorTypeNode1(modifiers, typeParameters, parameters, type) {
21732             var node = createBaseSignatureDeclaration(175 /* ConstructorType */, 
21733             /*decorators*/ undefined, modifiers, 
21734             /*name*/ undefined, typeParameters, parameters, type);
21735             node.transformFlags = 1 /* ContainsTypeScript */;
21736             return node;
21737         }
21738         /** @deprecated */
21739         function createConstructorTypeNode2(typeParameters, parameters, type) {
21740             return createConstructorTypeNode1(/*modifiers*/ undefined, typeParameters, parameters, type);
21741         }
21742         // @api
21743         function updateConstructorTypeNode() {
21744             var args = [];
21745             for (var _i = 0; _i < arguments.length; _i++) {
21746                 args[_i] = arguments[_i];
21747             }
21748             return args.length === 5 ? updateConstructorTypeNode1.apply(void 0, args) :
21749                 args.length === 4 ? updateConstructorTypeNode2.apply(void 0, args) :
21750                     ts.Debug.fail("Incorrect number of arguments specified.");
21751         }
21752         function updateConstructorTypeNode1(node, modifiers, typeParameters, parameters, type) {
21753             return node.modifiers !== modifiers
21754                 || node.typeParameters !== typeParameters
21755                 || node.parameters !== parameters
21756                 || node.type !== type
21757                 ? updateBaseSignatureDeclaration(createConstructorTypeNode(modifiers, typeParameters, parameters, type), node)
21758                 : node;
21759         }
21760         /** @deprecated */
21761         function updateConstructorTypeNode2(node, typeParameters, parameters, type) {
21762             return updateConstructorTypeNode1(node, node.modifiers, typeParameters, parameters, type);
21763         }
21764         // @api
21765         function createTypeQueryNode(exprName) {
21766             var node = createBaseNode(176 /* TypeQuery */);
21767             node.exprName = exprName;
21768             node.transformFlags = 1 /* ContainsTypeScript */;
21769             return node;
21770         }
21771         // @api
21772         function updateTypeQueryNode(node, exprName) {
21773             return node.exprName !== exprName
21774                 ? update(createTypeQueryNode(exprName), node)
21775                 : node;
21776         }
21777         // @api
21778         function createTypeLiteralNode(members) {
21779             var node = createBaseNode(177 /* TypeLiteral */);
21780             node.members = createNodeArray(members);
21781             node.transformFlags = 1 /* ContainsTypeScript */;
21782             return node;
21783         }
21784         // @api
21785         function updateTypeLiteralNode(node, members) {
21786             return node.members !== members
21787                 ? update(createTypeLiteralNode(members), node)
21788                 : node;
21789         }
21790         // @api
21791         function createArrayTypeNode(elementType) {
21792             var node = createBaseNode(178 /* ArrayType */);
21793             node.elementType = parenthesizerRules().parenthesizeElementTypeOfArrayType(elementType);
21794             node.transformFlags = 1 /* ContainsTypeScript */;
21795             return node;
21796         }
21797         // @api
21798         function updateArrayTypeNode(node, elementType) {
21799             return node.elementType !== elementType
21800                 ? update(createArrayTypeNode(elementType), node)
21801                 : node;
21802         }
21803         // @api
21804         function createTupleTypeNode(elements) {
21805             var node = createBaseNode(179 /* TupleType */);
21806             node.elements = createNodeArray(elements);
21807             node.transformFlags = 1 /* ContainsTypeScript */;
21808             return node;
21809         }
21810         // @api
21811         function updateTupleTypeNode(node, elements) {
21812             return node.elements !== elements
21813                 ? update(createTupleTypeNode(elements), node)
21814                 : node;
21815         }
21816         // @api
21817         function createNamedTupleMember(dotDotDotToken, name, questionToken, type) {
21818             var node = createBaseNode(192 /* NamedTupleMember */);
21819             node.dotDotDotToken = dotDotDotToken;
21820             node.name = name;
21821             node.questionToken = questionToken;
21822             node.type = type;
21823             node.transformFlags = 1 /* ContainsTypeScript */;
21824             return node;
21825         }
21826         // @api
21827         function updateNamedTupleMember(node, dotDotDotToken, name, questionToken, type) {
21828             return node.dotDotDotToken !== dotDotDotToken
21829                 || node.name !== name
21830                 || node.questionToken !== questionToken
21831                 || node.type !== type
21832                 ? update(createNamedTupleMember(dotDotDotToken, name, questionToken, type), node)
21833                 : node;
21834         }
21835         // @api
21836         function createOptionalTypeNode(type) {
21837             var node = createBaseNode(180 /* OptionalType */);
21838             node.type = parenthesizerRules().parenthesizeElementTypeOfArrayType(type);
21839             node.transformFlags = 1 /* ContainsTypeScript */;
21840             return node;
21841         }
21842         // @api
21843         function updateOptionalTypeNode(node, type) {
21844             return node.type !== type
21845                 ? update(createOptionalTypeNode(type), node)
21846                 : node;
21847         }
21848         // @api
21849         function createRestTypeNode(type) {
21850             var node = createBaseNode(181 /* RestType */);
21851             node.type = type;
21852             node.transformFlags = 1 /* ContainsTypeScript */;
21853             return node;
21854         }
21855         // @api
21856         function updateRestTypeNode(node, type) {
21857             return node.type !== type
21858                 ? update(createRestTypeNode(type), node)
21859                 : node;
21860         }
21861         function createUnionOrIntersectionTypeNode(kind, types) {
21862             var node = createBaseNode(kind);
21863             node.types = parenthesizerRules().parenthesizeConstituentTypesOfUnionOrIntersectionType(types);
21864             node.transformFlags = 1 /* ContainsTypeScript */;
21865             return node;
21866         }
21867         function updateUnionOrIntersectionTypeNode(node, types) {
21868             return node.types !== types
21869                 ? update(createUnionOrIntersectionTypeNode(node.kind, types), node)
21870                 : node;
21871         }
21872         // @api
21873         function createUnionTypeNode(types) {
21874             return createUnionOrIntersectionTypeNode(182 /* UnionType */, types);
21875         }
21876         // @api
21877         function updateUnionTypeNode(node, types) {
21878             return updateUnionOrIntersectionTypeNode(node, types);
21879         }
21880         // @api
21881         function createIntersectionTypeNode(types) {
21882             return createUnionOrIntersectionTypeNode(183 /* IntersectionType */, types);
21883         }
21884         // @api
21885         function updateIntersectionTypeNode(node, types) {
21886             return updateUnionOrIntersectionTypeNode(node, types);
21887         }
21888         // @api
21889         function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
21890             var node = createBaseNode(184 /* ConditionalType */);
21891             node.checkType = parenthesizerRules().parenthesizeMemberOfConditionalType(checkType);
21892             node.extendsType = parenthesizerRules().parenthesizeMemberOfConditionalType(extendsType);
21893             node.trueType = trueType;
21894             node.falseType = falseType;
21895             node.transformFlags = 1 /* ContainsTypeScript */;
21896             return node;
21897         }
21898         // @api
21899         function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
21900             return node.checkType !== checkType
21901                 || node.extendsType !== extendsType
21902                 || node.trueType !== trueType
21903                 || node.falseType !== falseType
21904                 ? update(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
21905                 : node;
21906         }
21907         // @api
21908         function createInferTypeNode(typeParameter) {
21909             var node = createBaseNode(185 /* InferType */);
21910             node.typeParameter = typeParameter;
21911             node.transformFlags = 1 /* ContainsTypeScript */;
21912             return node;
21913         }
21914         // @api
21915         function updateInferTypeNode(node, typeParameter) {
21916             return node.typeParameter !== typeParameter
21917                 ? update(createInferTypeNode(typeParameter), node)
21918                 : node;
21919         }
21920         // @api
21921         function createTemplateLiteralType(head, templateSpans) {
21922             var node = createBaseNode(193 /* TemplateLiteralType */);
21923             node.head = head;
21924             node.templateSpans = createNodeArray(templateSpans);
21925             node.transformFlags = 1 /* ContainsTypeScript */;
21926             return node;
21927         }
21928         // @api
21929         function updateTemplateLiteralType(node, head, templateSpans) {
21930             return node.head !== head
21931                 || node.templateSpans !== templateSpans
21932                 ? update(createTemplateLiteralType(head, templateSpans), node)
21933                 : node;
21934         }
21935         // @api
21936         function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) {
21937             if (isTypeOf === void 0) { isTypeOf = false; }
21938             var node = createBaseNode(195 /* ImportType */);
21939             node.argument = argument;
21940             node.qualifier = qualifier;
21941             node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
21942             node.isTypeOf = isTypeOf;
21943             node.transformFlags = 1 /* ContainsTypeScript */;
21944             return node;
21945         }
21946         // @api
21947         function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) {
21948             if (isTypeOf === void 0) { isTypeOf = node.isTypeOf; }
21949             return node.argument !== argument
21950                 || node.qualifier !== qualifier
21951                 || node.typeArguments !== typeArguments
21952                 || node.isTypeOf !== isTypeOf
21953                 ? update(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node)
21954                 : node;
21955         }
21956         // @api
21957         function createParenthesizedType(type) {
21958             var node = createBaseNode(186 /* ParenthesizedType */);
21959             node.type = type;
21960             node.transformFlags = 1 /* ContainsTypeScript */;
21961             return node;
21962         }
21963         // @api
21964         function updateParenthesizedType(node, type) {
21965             return node.type !== type
21966                 ? update(createParenthesizedType(type), node)
21967                 : node;
21968         }
21969         // @api
21970         function createThisTypeNode() {
21971             var node = createBaseNode(187 /* ThisType */);
21972             node.transformFlags = 1 /* ContainsTypeScript */;
21973             return node;
21974         }
21975         // @api
21976         function createTypeOperatorNode(operator, type) {
21977             var node = createBaseNode(188 /* TypeOperator */);
21978             node.operator = operator;
21979             node.type = parenthesizerRules().parenthesizeMemberOfElementType(type);
21980             node.transformFlags = 1 /* ContainsTypeScript */;
21981             return node;
21982         }
21983         // @api
21984         function updateTypeOperatorNode(node, type) {
21985             return node.type !== type
21986                 ? update(createTypeOperatorNode(node.operator, type), node)
21987                 : node;
21988         }
21989         // @api
21990         function createIndexedAccessTypeNode(objectType, indexType) {
21991             var node = createBaseNode(189 /* IndexedAccessType */);
21992             node.objectType = parenthesizerRules().parenthesizeMemberOfElementType(objectType);
21993             node.indexType = indexType;
21994             node.transformFlags = 1 /* ContainsTypeScript */;
21995             return node;
21996         }
21997         // @api
21998         function updateIndexedAccessTypeNode(node, objectType, indexType) {
21999             return node.objectType !== objectType
22000                 || node.indexType !== indexType
22001                 ? update(createIndexedAccessTypeNode(objectType, indexType), node)
22002                 : node;
22003         }
22004         // @api
22005         function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type) {
22006             var node = createBaseNode(190 /* MappedType */);
22007             node.readonlyToken = readonlyToken;
22008             node.typeParameter = typeParameter;
22009             node.nameType = nameType;
22010             node.questionToken = questionToken;
22011             node.type = type;
22012             node.transformFlags = 1 /* ContainsTypeScript */;
22013             return node;
22014         }
22015         // @api
22016         function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type) {
22017             return node.readonlyToken !== readonlyToken
22018                 || node.typeParameter !== typeParameter
22019                 || node.nameType !== nameType
22020                 || node.questionToken !== questionToken
22021                 || node.type !== type
22022                 ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), node)
22023                 : node;
22024         }
22025         // @api
22026         function createLiteralTypeNode(literal) {
22027             var node = createBaseNode(191 /* LiteralType */);
22028             node.literal = literal;
22029             node.transformFlags = 1 /* ContainsTypeScript */;
22030             return node;
22031         }
22032         // @api
22033         function updateLiteralTypeNode(node, literal) {
22034             return node.literal !== literal
22035                 ? update(createLiteralTypeNode(literal), node)
22036                 : node;
22037         }
22038         //
22039         // Binding Patterns
22040         //
22041         // @api
22042         function createObjectBindingPattern(elements) {
22043             var node = createBaseNode(196 /* ObjectBindingPattern */);
22044             node.elements = createNodeArray(elements);
22045             node.transformFlags |=
22046                 propagateChildrenFlags(node.elements) |
22047                     256 /* ContainsES2015 */ |
22048                     131072 /* ContainsBindingPattern */;
22049             if (node.transformFlags & 8192 /* ContainsRestOrSpread */) {
22050                 node.transformFlags |=
22051                     32 /* ContainsES2018 */ |
22052                         16384 /* ContainsObjectRestOrSpread */;
22053             }
22054             return node;
22055         }
22056         // @api
22057         function updateObjectBindingPattern(node, elements) {
22058             return node.elements !== elements
22059                 ? update(createObjectBindingPattern(elements), node)
22060                 : node;
22061         }
22062         // @api
22063         function createArrayBindingPattern(elements) {
22064             var node = createBaseNode(197 /* ArrayBindingPattern */);
22065             node.elements = createNodeArray(elements);
22066             node.transformFlags |=
22067                 propagateChildrenFlags(node.elements) |
22068                     256 /* ContainsES2015 */ |
22069                     131072 /* ContainsBindingPattern */;
22070             return node;
22071         }
22072         // @api
22073         function updateArrayBindingPattern(node, elements) {
22074             return node.elements !== elements
22075                 ? update(createArrayBindingPattern(elements), node)
22076                 : node;
22077         }
22078         // @api
22079         function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
22080             var node = createBaseBindingLikeDeclaration(198 /* BindingElement */, 
22081             /*decorators*/ undefined, 
22082             /*modifiers*/ undefined, name, initializer);
22083             node.propertyName = asName(propertyName);
22084             node.dotDotDotToken = dotDotDotToken;
22085             node.transformFlags |=
22086                 propagateChildFlags(node.dotDotDotToken) |
22087                     256 /* ContainsES2015 */;
22088             if (node.propertyName) {
22089                 node.transformFlags |= ts.isIdentifier(node.propertyName) ?
22090                     propagateIdentifierNameFlags(node.propertyName) :
22091                     propagateChildFlags(node.propertyName);
22092             }
22093             if (dotDotDotToken)
22094                 node.transformFlags |= 8192 /* ContainsRestOrSpread */;
22095             return node;
22096         }
22097         // @api
22098         function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
22099             return node.propertyName !== propertyName
22100                 || node.dotDotDotToken !== dotDotDotToken
22101                 || node.name !== name
22102                 || node.initializer !== initializer
22103                 ? update(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
22104                 : node;
22105         }
22106         //
22107         // Expression
22108         //
22109         function createBaseExpression(kind) {
22110             var node = createBaseNode(kind);
22111             // the following properties are commonly set by the checker/binder
22112             return node;
22113         }
22114         // @api
22115         function createArrayLiteralExpression(elements, multiLine) {
22116             var node = createBaseExpression(199 /* ArrayLiteralExpression */);
22117             node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(elements));
22118             node.multiLine = multiLine;
22119             node.transformFlags |= propagateChildrenFlags(node.elements);
22120             return node;
22121         }
22122         // @api
22123         function updateArrayLiteralExpression(node, elements) {
22124             return node.elements !== elements
22125                 ? update(createArrayLiteralExpression(elements, node.multiLine), node)
22126                 : node;
22127         }
22128         // @api
22129         function createObjectLiteralExpression(properties, multiLine) {
22130             var node = createBaseExpression(200 /* ObjectLiteralExpression */);
22131             node.properties = createNodeArray(properties);
22132             node.multiLine = multiLine;
22133             node.transformFlags |= propagateChildrenFlags(node.properties);
22134             return node;
22135         }
22136         // @api
22137         function updateObjectLiteralExpression(node, properties) {
22138             return node.properties !== properties
22139                 ? update(createObjectLiteralExpression(properties, node.multiLine), node)
22140                 : node;
22141         }
22142         // @api
22143         function createPropertyAccessExpression(expression, name) {
22144             var node = createBaseExpression(201 /* PropertyAccessExpression */);
22145             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22146             node.name = asName(name);
22147             node.transformFlags =
22148                 propagateChildFlags(node.expression) |
22149                     (ts.isIdentifier(node.name) ?
22150                         propagateIdentifierNameFlags(node.name) :
22151                         propagateChildFlags(node.name));
22152             if (ts.isSuperKeyword(expression)) {
22153                 // super method calls require a lexical 'this'
22154                 // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators
22155                 node.transformFlags |=
22156                     64 /* ContainsES2017 */ |
22157                         32 /* ContainsES2018 */;
22158             }
22159             return node;
22160         }
22161         // @api
22162         function updatePropertyAccessExpression(node, expression, name) {
22163             if (ts.isPropertyAccessChain(node)) {
22164                 return updatePropertyAccessChain(node, expression, node.questionDotToken, ts.cast(name, ts.isIdentifier));
22165             }
22166             return node.expression !== expression
22167                 || node.name !== name
22168                 ? update(createPropertyAccessExpression(expression, name), node)
22169                 : node;
22170         }
22171         // @api
22172         function createPropertyAccessChain(expression, questionDotToken, name) {
22173             var node = createBaseExpression(201 /* PropertyAccessExpression */);
22174             node.flags |= 32 /* OptionalChain */;
22175             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22176             node.questionDotToken = questionDotToken;
22177             node.name = asName(name);
22178             node.transformFlags |=
22179                 8 /* ContainsES2020 */ |
22180                     propagateChildFlags(node.expression) |
22181                     propagateChildFlags(node.questionDotToken) |
22182                     (ts.isIdentifier(node.name) ?
22183                         propagateIdentifierNameFlags(node.name) :
22184                         propagateChildFlags(node.name));
22185             return node;
22186         }
22187         // @api
22188         function updatePropertyAccessChain(node, expression, questionDotToken, name) {
22189             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead.");
22190             // Because we are updating an existing PropertyAccessChain we want to inherit its emitFlags
22191             // instead of using the default from createPropertyAccess
22192             return node.expression !== expression
22193                 || node.questionDotToken !== questionDotToken
22194                 || node.name !== name
22195                 ? update(createPropertyAccessChain(expression, questionDotToken, name), node)
22196                 : node;
22197         }
22198         // @api
22199         function createElementAccessExpression(expression, index) {
22200             var node = createBaseExpression(202 /* ElementAccessExpression */);
22201             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22202             node.argumentExpression = asExpression(index);
22203             node.transformFlags |=
22204                 propagateChildFlags(node.expression) |
22205                     propagateChildFlags(node.argumentExpression);
22206             if (ts.isSuperKeyword(expression)) {
22207                 // super method calls require a lexical 'this'
22208                 // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators
22209                 node.transformFlags |=
22210                     64 /* ContainsES2017 */ |
22211                         32 /* ContainsES2018 */;
22212             }
22213             return node;
22214         }
22215         // @api
22216         function updateElementAccessExpression(node, expression, argumentExpression) {
22217             if (ts.isElementAccessChain(node)) {
22218                 return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression);
22219             }
22220             return node.expression !== expression
22221                 || node.argumentExpression !== argumentExpression
22222                 ? update(createElementAccessExpression(expression, argumentExpression), node)
22223                 : node;
22224         }
22225         // @api
22226         function createElementAccessChain(expression, questionDotToken, index) {
22227             var node = createBaseExpression(202 /* ElementAccessExpression */);
22228             node.flags |= 32 /* OptionalChain */;
22229             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22230             node.questionDotToken = questionDotToken;
22231             node.argumentExpression = asExpression(index);
22232             node.transformFlags |=
22233                 propagateChildFlags(node.expression) |
22234                     propagateChildFlags(node.questionDotToken) |
22235                     propagateChildFlags(node.argumentExpression) |
22236                     8 /* ContainsES2020 */;
22237             return node;
22238         }
22239         // @api
22240         function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) {
22241             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead.");
22242             // Because we are updating an existing ElementAccessChain we want to inherit its emitFlags
22243             // instead of using the default from createElementAccess
22244             return node.expression !== expression
22245                 || node.questionDotToken !== questionDotToken
22246                 || node.argumentExpression !== argumentExpression
22247                 ? update(createElementAccessChain(expression, questionDotToken, argumentExpression), node)
22248                 : node;
22249         }
22250         // @api
22251         function createCallExpression(expression, typeArguments, argumentsArray) {
22252             var node = createBaseExpression(203 /* CallExpression */);
22253             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22254             node.typeArguments = asNodeArray(typeArguments);
22255             node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray));
22256             node.transformFlags |=
22257                 propagateChildFlags(node.expression) |
22258                     propagateChildrenFlags(node.typeArguments) |
22259                     propagateChildrenFlags(node.arguments);
22260             if (node.typeArguments) {
22261                 node.transformFlags |= 1 /* ContainsTypeScript */;
22262             }
22263             if (ts.isImportKeyword(node.expression)) {
22264                 node.transformFlags |= 2097152 /* ContainsDynamicImport */;
22265             }
22266             else if (ts.isSuperProperty(node.expression)) {
22267                 node.transformFlags |= 4096 /* ContainsLexicalThis */;
22268             }
22269             return node;
22270         }
22271         // @api
22272         function updateCallExpression(node, expression, typeArguments, argumentsArray) {
22273             if (ts.isCallChain(node)) {
22274                 return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray);
22275             }
22276             return node.expression !== expression
22277                 || node.typeArguments !== typeArguments
22278                 || node.arguments !== argumentsArray
22279                 ? update(createCallExpression(expression, typeArguments, argumentsArray), node)
22280                 : node;
22281         }
22282         // @api
22283         function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) {
22284             var node = createBaseExpression(203 /* CallExpression */);
22285             node.flags |= 32 /* OptionalChain */;
22286             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22287             node.questionDotToken = questionDotToken;
22288             node.typeArguments = asNodeArray(typeArguments);
22289             node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray));
22290             node.transformFlags |=
22291                 propagateChildFlags(node.expression) |
22292                     propagateChildFlags(node.questionDotToken) |
22293                     propagateChildrenFlags(node.typeArguments) |
22294                     propagateChildrenFlags(node.arguments) |
22295                     8 /* ContainsES2020 */;
22296             if (node.typeArguments) {
22297                 node.transformFlags |= 1 /* ContainsTypeScript */;
22298             }
22299             if (ts.isSuperProperty(node.expression)) {
22300                 node.transformFlags |= 4096 /* ContainsLexicalThis */;
22301             }
22302             return node;
22303         }
22304         // @api
22305         function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) {
22306             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a CallExpression using updateCallChain. Use updateCall instead.");
22307             return node.expression !== expression
22308                 || node.questionDotToken !== questionDotToken
22309                 || node.typeArguments !== typeArguments
22310                 || node.arguments !== argumentsArray
22311                 ? update(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node)
22312                 : node;
22313         }
22314         // @api
22315         function createNewExpression(expression, typeArguments, argumentsArray) {
22316             var node = createBaseExpression(204 /* NewExpression */);
22317             node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression);
22318             node.typeArguments = asNodeArray(typeArguments);
22319             node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : undefined;
22320             node.transformFlags |=
22321                 propagateChildFlags(node.expression) |
22322                     propagateChildrenFlags(node.typeArguments) |
22323                     propagateChildrenFlags(node.arguments) |
22324                     8 /* ContainsES2020 */;
22325             if (node.typeArguments) {
22326                 node.transformFlags |= 1 /* ContainsTypeScript */;
22327             }
22328             return node;
22329         }
22330         // @api
22331         function updateNewExpression(node, expression, typeArguments, argumentsArray) {
22332             return node.expression !== expression
22333                 || node.typeArguments !== typeArguments
22334                 || node.arguments !== argumentsArray
22335                 ? update(createNewExpression(expression, typeArguments, argumentsArray), node)
22336                 : node;
22337         }
22338         // @api
22339         function createTaggedTemplateExpression(tag, typeArguments, template) {
22340             var node = createBaseExpression(205 /* TaggedTemplateExpression */);
22341             node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag);
22342             node.typeArguments = asNodeArray(typeArguments);
22343             node.template = template;
22344             node.transformFlags |=
22345                 propagateChildFlags(node.tag) |
22346                     propagateChildrenFlags(node.typeArguments) |
22347                     propagateChildFlags(node.template) |
22348                     256 /* ContainsES2015 */;
22349             if (node.typeArguments) {
22350                 node.transformFlags |= 1 /* ContainsTypeScript */;
22351             }
22352             if (ts.hasInvalidEscape(node.template)) {
22353                 node.transformFlags |= 32 /* ContainsES2018 */;
22354             }
22355             return node;
22356         }
22357         // @api
22358         function updateTaggedTemplateExpression(node, tag, typeArguments, template) {
22359             return node.tag !== tag
22360                 || node.typeArguments !== typeArguments
22361                 || node.template !== template
22362                 ? update(createTaggedTemplateExpression(tag, typeArguments, template), node)
22363                 : node;
22364         }
22365         // @api
22366         function createTypeAssertion(type, expression) {
22367             var node = createBaseExpression(206 /* TypeAssertionExpression */);
22368             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
22369             node.type = type;
22370             node.transformFlags |=
22371                 propagateChildFlags(node.expression) |
22372                     propagateChildFlags(node.type) |
22373                     1 /* ContainsTypeScript */;
22374             return node;
22375         }
22376         // @api
22377         function updateTypeAssertion(node, type, expression) {
22378             return node.type !== type
22379                 || node.expression !== expression
22380                 ? update(createTypeAssertion(type, expression), node)
22381                 : node;
22382         }
22383         // @api
22384         function createParenthesizedExpression(expression) {
22385             var node = createBaseExpression(207 /* ParenthesizedExpression */);
22386             node.expression = expression;
22387             node.transformFlags = propagateChildFlags(node.expression);
22388             return node;
22389         }
22390         // @api
22391         function updateParenthesizedExpression(node, expression) {
22392             return node.expression !== expression
22393                 ? update(createParenthesizedExpression(expression), node)
22394                 : node;
22395         }
22396         // @api
22397         function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
22398             var node = createBaseFunctionLikeDeclaration(208 /* FunctionExpression */, 
22399             /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body);
22400             node.asteriskToken = asteriskToken;
22401             node.transformFlags |= propagateChildFlags(node.asteriskToken);
22402             if (node.typeParameters) {
22403                 node.transformFlags |= 1 /* ContainsTypeScript */;
22404             }
22405             if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
22406                 if (node.asteriskToken) {
22407                     node.transformFlags |= 32 /* ContainsES2018 */;
22408                 }
22409                 else {
22410                     node.transformFlags |= 64 /* ContainsES2017 */;
22411                 }
22412             }
22413             else if (node.asteriskToken) {
22414                 node.transformFlags |= 512 /* ContainsGenerator */;
22415             }
22416             return node;
22417         }
22418         // @api
22419         function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
22420             return node.name !== name
22421                 || node.modifiers !== modifiers
22422                 || node.asteriskToken !== asteriskToken
22423                 || node.typeParameters !== typeParameters
22424                 || node.parameters !== parameters
22425                 || node.type !== type
22426                 || node.body !== body
22427                 ? updateBaseFunctionLikeDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
22428                 : node;
22429         }
22430         // @api
22431         function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
22432             var node = createBaseFunctionLikeDeclaration(209 /* ArrowFunction */, 
22433             /*decorators*/ undefined, modifiers, 
22434             /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body));
22435             node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* EqualsGreaterThanToken */);
22436             node.transformFlags |=
22437                 propagateChildFlags(node.equalsGreaterThanToken) |
22438                     256 /* ContainsES2015 */;
22439             if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
22440                 node.transformFlags |= 64 /* ContainsES2017 */;
22441             }
22442             return node;
22443         }
22444         // @api
22445         function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
22446             return node.modifiers !== modifiers
22447                 || node.typeParameters !== typeParameters
22448                 || node.parameters !== parameters
22449                 || node.type !== type
22450                 || node.equalsGreaterThanToken !== equalsGreaterThanToken
22451                 || node.body !== body
22452                 ? updateBaseFunctionLikeDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node)
22453                 : node;
22454         }
22455         // @api
22456         function createDeleteExpression(expression) {
22457             var node = createBaseExpression(210 /* DeleteExpression */);
22458             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
22459             node.transformFlags |= propagateChildFlags(node.expression);
22460             return node;
22461         }
22462         // @api
22463         function updateDeleteExpression(node, expression) {
22464             return node.expression !== expression
22465                 ? update(createDeleteExpression(expression), node)
22466                 : node;
22467         }
22468         // @api
22469         function createTypeOfExpression(expression) {
22470             var node = createBaseExpression(211 /* TypeOfExpression */);
22471             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
22472             node.transformFlags |= propagateChildFlags(node.expression);
22473             return node;
22474         }
22475         // @api
22476         function updateTypeOfExpression(node, expression) {
22477             return node.expression !== expression
22478                 ? update(createTypeOfExpression(expression), node)
22479                 : node;
22480         }
22481         // @api
22482         function createVoidExpression(expression) {
22483             var node = createBaseExpression(212 /* VoidExpression */);
22484             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
22485             node.transformFlags |= propagateChildFlags(node.expression);
22486             return node;
22487         }
22488         // @api
22489         function updateVoidExpression(node, expression) {
22490             return node.expression !== expression
22491                 ? update(createVoidExpression(expression), node)
22492                 : node;
22493         }
22494         // @api
22495         function createAwaitExpression(expression) {
22496             var node = createBaseExpression(213 /* AwaitExpression */);
22497             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
22498             node.transformFlags |=
22499                 propagateChildFlags(node.expression) |
22500                     64 /* ContainsES2017 */ |
22501                     32 /* ContainsES2018 */ |
22502                     524288 /* ContainsAwait */;
22503             return node;
22504         }
22505         // @api
22506         function updateAwaitExpression(node, expression) {
22507             return node.expression !== expression
22508                 ? update(createAwaitExpression(expression), node)
22509                 : node;
22510         }
22511         // @api
22512         function createPrefixUnaryExpression(operator, operand) {
22513             var node = createBaseExpression(214 /* PrefixUnaryExpression */);
22514             node.operator = operator;
22515             node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand);
22516             node.transformFlags |= propagateChildFlags(node.operand);
22517             return node;
22518         }
22519         // @api
22520         function updatePrefixUnaryExpression(node, operand) {
22521             return node.operand !== operand
22522                 ? update(createPrefixUnaryExpression(node.operator, operand), node)
22523                 : node;
22524         }
22525         // @api
22526         function createPostfixUnaryExpression(operand, operator) {
22527             var node = createBaseExpression(215 /* PostfixUnaryExpression */);
22528             node.operator = operator;
22529             node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand);
22530             node.transformFlags = propagateChildFlags(node.operand);
22531             return node;
22532         }
22533         // @api
22534         function updatePostfixUnaryExpression(node, operand) {
22535             return node.operand !== operand
22536                 ? update(createPostfixUnaryExpression(operand, node.operator), node)
22537                 : node;
22538         }
22539         // @api
22540         function createBinaryExpression(left, operator, right) {
22541             var node = createBaseExpression(216 /* BinaryExpression */);
22542             var operatorToken = asToken(operator);
22543             var operatorKind = operatorToken.kind;
22544             node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left);
22545             node.operatorToken = operatorToken;
22546             node.right = parenthesizerRules().parenthesizeRightSideOfBinary(operatorKind, node.left, right);
22547             node.transformFlags |=
22548                 propagateChildFlags(node.left) |
22549                     propagateChildFlags(node.operatorToken) |
22550                     propagateChildFlags(node.right);
22551             if (operatorKind === 60 /* QuestionQuestionToken */) {
22552                 node.transformFlags |= 8 /* ContainsES2020 */;
22553             }
22554             else if (operatorKind === 62 /* EqualsToken */) {
22555                 if (ts.isObjectLiteralExpression(node.left)) {
22556                     node.transformFlags |=
22557                         256 /* ContainsES2015 */ |
22558                             32 /* ContainsES2018 */ |
22559                             1024 /* ContainsDestructuringAssignment */ |
22560                             propagateAssignmentPatternFlags(node.left);
22561                 }
22562                 else if (ts.isArrayLiteralExpression(node.left)) {
22563                     node.transformFlags |=
22564                         256 /* ContainsES2015 */ |
22565                             1024 /* ContainsDestructuringAssignment */ |
22566                             propagateAssignmentPatternFlags(node.left);
22567                 }
22568             }
22569             else if (operatorKind === 42 /* AsteriskAsteriskToken */ || operatorKind === 66 /* AsteriskAsteriskEqualsToken */) {
22570                 node.transformFlags |= 128 /* ContainsES2016 */;
22571             }
22572             else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) {
22573                 node.transformFlags |= 4 /* ContainsESNext */;
22574             }
22575             return node;
22576         }
22577         function propagateAssignmentPatternFlags(node) {
22578             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */)
22579                 return 16384 /* ContainsObjectRestOrSpread */;
22580             if (node.transformFlags & 32 /* ContainsES2018 */) {
22581                 // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c'
22582                 // will not be correctly interpreted by the ES2018 transformer
22583                 for (var _i = 0, _a = ts.getElementsOfBindingOrAssignmentPattern(node); _i < _a.length; _i++) {
22584                     var element = _a[_i];
22585                     var target = ts.getTargetOfBindingOrAssignmentElement(element);
22586                     if (target && ts.isAssignmentPattern(target)) {
22587                         if (target.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
22588                             return 16384 /* ContainsObjectRestOrSpread */;
22589                         }
22590                         if (target.transformFlags & 32 /* ContainsES2018 */) {
22591                             var flags_1 = propagateAssignmentPatternFlags(target);
22592                             if (flags_1)
22593                                 return flags_1;
22594                         }
22595                     }
22596                 }
22597             }
22598             return 0 /* None */;
22599         }
22600         // @api
22601         function updateBinaryExpression(node, left, operator, right) {
22602             return node.left !== left
22603                 || node.operatorToken !== operator
22604                 || node.right !== right
22605                 ? update(createBinaryExpression(left, operator, right), node)
22606                 : node;
22607         }
22608         // @api
22609         function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) {
22610             var node = createBaseExpression(217 /* ConditionalExpression */);
22611             node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition);
22612             node.questionToken = questionToken !== null && questionToken !== void 0 ? questionToken : createToken(57 /* QuestionToken */);
22613             node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue);
22614             node.colonToken = colonToken !== null && colonToken !== void 0 ? colonToken : createToken(58 /* ColonToken */);
22615             node.whenFalse = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenFalse);
22616             node.transformFlags |=
22617                 propagateChildFlags(node.condition) |
22618                     propagateChildFlags(node.questionToken) |
22619                     propagateChildFlags(node.whenTrue) |
22620                     propagateChildFlags(node.colonToken) |
22621                     propagateChildFlags(node.whenFalse);
22622             return node;
22623         }
22624         // @api
22625         function updateConditionalExpression(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
22626             return node.condition !== condition
22627                 || node.questionToken !== questionToken
22628                 || node.whenTrue !== whenTrue
22629                 || node.colonToken !== colonToken
22630                 || node.whenFalse !== whenFalse
22631                 ? update(createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse), node)
22632                 : node;
22633         }
22634         // @api
22635         function createTemplateExpression(head, templateSpans) {
22636             var node = createBaseExpression(218 /* TemplateExpression */);
22637             node.head = head;
22638             node.templateSpans = createNodeArray(templateSpans);
22639             node.transformFlags |=
22640                 propagateChildFlags(node.head) |
22641                     propagateChildrenFlags(node.templateSpans) |
22642                     256 /* ContainsES2015 */;
22643             return node;
22644         }
22645         // @api
22646         function updateTemplateExpression(node, head, templateSpans) {
22647             return node.head !== head
22648                 || node.templateSpans !== templateSpans
22649                 ? update(createTemplateExpression(head, templateSpans), node)
22650                 : node;
22651         }
22652         function createTemplateLiteralLikeNodeChecked(kind, text, rawText, templateFlags) {
22653             if (templateFlags === void 0) { templateFlags = 0 /* None */; }
22654             ts.Debug.assert(!(templateFlags & ~2048 /* TemplateLiteralLikeFlags */), "Unsupported template flags.");
22655             // NOTE: without the assignment to `undefined`, we don't narrow the initial type of `cooked`.
22656             // eslint-disable-next-line no-undef-init
22657             var cooked = undefined;
22658             if (rawText !== undefined && rawText !== text) {
22659                 cooked = getCookedText(kind, rawText);
22660                 if (typeof cooked === "object") {
22661                     return ts.Debug.fail("Invalid raw text");
22662                 }
22663             }
22664             if (text === undefined) {
22665                 if (cooked === undefined) {
22666                     return ts.Debug.fail("Arguments 'text' and 'rawText' may not both be undefined.");
22667                 }
22668                 text = cooked;
22669             }
22670             else if (cooked !== undefined) {
22671                 ts.Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.");
22672             }
22673             return createTemplateLiteralLikeNode(kind, text, rawText, templateFlags);
22674         }
22675         // @api
22676         function createTemplateLiteralLikeNode(kind, text, rawText, templateFlags) {
22677             var node = createBaseToken(kind);
22678             node.text = text;
22679             node.rawText = rawText;
22680             node.templateFlags = templateFlags & 2048 /* TemplateLiteralLikeFlags */;
22681             node.transformFlags |= 256 /* ContainsES2015 */;
22682             if (node.templateFlags) {
22683                 node.transformFlags |= 32 /* ContainsES2018 */;
22684             }
22685             return node;
22686         }
22687         // @api
22688         function createTemplateHead(text, rawText, templateFlags) {
22689             return createTemplateLiteralLikeNodeChecked(15 /* TemplateHead */, text, rawText, templateFlags);
22690         }
22691         // @api
22692         function createTemplateMiddle(text, rawText, templateFlags) {
22693             return createTemplateLiteralLikeNodeChecked(16 /* TemplateMiddle */, text, rawText, templateFlags);
22694         }
22695         // @api
22696         function createTemplateTail(text, rawText, templateFlags) {
22697             return createTemplateLiteralLikeNodeChecked(17 /* TemplateTail */, text, rawText, templateFlags);
22698         }
22699         // @api
22700         function createNoSubstitutionTemplateLiteral(text, rawText, templateFlags) {
22701             return createTemplateLiteralLikeNodeChecked(14 /* NoSubstitutionTemplateLiteral */, text, rawText, templateFlags);
22702         }
22703         // @api
22704         function createYieldExpression(asteriskToken, expression) {
22705             ts.Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression.");
22706             var node = createBaseExpression(219 /* YieldExpression */);
22707             node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
22708             node.asteriskToken = asteriskToken;
22709             node.transformFlags |=
22710                 propagateChildFlags(node.expression) |
22711                     propagateChildFlags(node.asteriskToken) |
22712                     256 /* ContainsES2015 */ |
22713                     32 /* ContainsES2018 */ |
22714                     262144 /* ContainsYield */;
22715             return node;
22716         }
22717         // @api
22718         function updateYieldExpression(node, asteriskToken, expression) {
22719             return node.expression !== expression
22720                 || node.asteriskToken !== asteriskToken
22721                 ? update(createYieldExpression(asteriskToken, expression), node)
22722                 : node;
22723         }
22724         // @api
22725         function createSpreadElement(expression) {
22726             var node = createBaseExpression(220 /* SpreadElement */);
22727             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
22728             node.transformFlags |=
22729                 propagateChildFlags(node.expression) |
22730                     256 /* ContainsES2015 */ |
22731                     8192 /* ContainsRestOrSpread */;
22732             return node;
22733         }
22734         // @api
22735         function updateSpreadElement(node, expression) {
22736             return node.expression !== expression
22737                 ? update(createSpreadElement(expression), node)
22738                 : node;
22739         }
22740         // @api
22741         function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) {
22742             var node = createBaseClassLikeDeclaration(221 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members);
22743             node.transformFlags |= 256 /* ContainsES2015 */;
22744             return node;
22745         }
22746         // @api
22747         function updateClassExpression(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
22748             return node.decorators !== decorators
22749                 || node.modifiers !== modifiers
22750                 || node.name !== name
22751                 || node.typeParameters !== typeParameters
22752                 || node.heritageClauses !== heritageClauses
22753                 || node.members !== members
22754                 ? update(createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
22755                 : node;
22756         }
22757         // @api
22758         function createOmittedExpression() {
22759             return createBaseExpression(222 /* OmittedExpression */);
22760         }
22761         // @api
22762         function createExpressionWithTypeArguments(expression, typeArguments) {
22763             var node = createBaseNode(223 /* ExpressionWithTypeArguments */);
22764             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22765             node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
22766             node.transformFlags |=
22767                 propagateChildFlags(node.expression) |
22768                     propagateChildrenFlags(node.typeArguments) |
22769                     256 /* ContainsES2015 */;
22770             return node;
22771         }
22772         // @api
22773         function updateExpressionWithTypeArguments(node, expression, typeArguments) {
22774             return node.expression !== expression
22775                 || node.typeArguments !== typeArguments
22776                 ? update(createExpressionWithTypeArguments(expression, typeArguments), node)
22777                 : node;
22778         }
22779         // @api
22780         function createAsExpression(expression, type) {
22781             var node = createBaseExpression(224 /* AsExpression */);
22782             node.expression = expression;
22783             node.type = type;
22784             node.transformFlags |=
22785                 propagateChildFlags(node.expression) |
22786                     propagateChildFlags(node.type) |
22787                     1 /* ContainsTypeScript */;
22788             return node;
22789         }
22790         // @api
22791         function updateAsExpression(node, expression, type) {
22792             return node.expression !== expression
22793                 || node.type !== type
22794                 ? update(createAsExpression(expression, type), node)
22795                 : node;
22796         }
22797         // @api
22798         function createNonNullExpression(expression) {
22799             var node = createBaseExpression(225 /* NonNullExpression */);
22800             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22801             node.transformFlags |=
22802                 propagateChildFlags(node.expression) |
22803                     1 /* ContainsTypeScript */;
22804             return node;
22805         }
22806         // @api
22807         function updateNonNullExpression(node, expression) {
22808             if (ts.isNonNullChain(node)) {
22809                 return updateNonNullChain(node, expression);
22810             }
22811             return node.expression !== expression
22812                 ? update(createNonNullExpression(expression), node)
22813                 : node;
22814         }
22815         // @api
22816         function createNonNullChain(expression) {
22817             var node = createBaseExpression(225 /* NonNullExpression */);
22818             node.flags |= 32 /* OptionalChain */;
22819             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22820             node.transformFlags |=
22821                 propagateChildFlags(node.expression) |
22822                     1 /* ContainsTypeScript */;
22823             return node;
22824         }
22825         // @api
22826         function updateNonNullChain(node, expression) {
22827             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead.");
22828             return node.expression !== expression
22829                 ? update(createNonNullChain(expression), node)
22830                 : node;
22831         }
22832         // @api
22833         function createMetaProperty(keywordToken, name) {
22834             var node = createBaseExpression(226 /* MetaProperty */);
22835             node.keywordToken = keywordToken;
22836             node.name = name;
22837             node.transformFlags |= propagateChildFlags(node.name);
22838             switch (keywordToken) {
22839                 case 102 /* NewKeyword */:
22840                     node.transformFlags |= 256 /* ContainsES2015 */;
22841                     break;
22842                 case 99 /* ImportKeyword */:
22843                     node.transformFlags |= 4 /* ContainsESNext */;
22844                     break;
22845                 default:
22846                     return ts.Debug.assertNever(keywordToken);
22847             }
22848             return node;
22849         }
22850         // @api
22851         function updateMetaProperty(node, name) {
22852             return node.name !== name
22853                 ? update(createMetaProperty(node.keywordToken, name), node)
22854                 : node;
22855         }
22856         //
22857         // Misc
22858         //
22859         // @api
22860         function createTemplateSpan(expression, literal) {
22861             var node = createBaseNode(228 /* TemplateSpan */);
22862             node.expression = expression;
22863             node.literal = literal;
22864             node.transformFlags |=
22865                 propagateChildFlags(node.expression) |
22866                     propagateChildFlags(node.literal) |
22867                     256 /* ContainsES2015 */;
22868             return node;
22869         }
22870         // @api
22871         function updateTemplateSpan(node, expression, literal) {
22872             return node.expression !== expression
22873                 || node.literal !== literal
22874                 ? update(createTemplateSpan(expression, literal), node)
22875                 : node;
22876         }
22877         // @api
22878         function createSemicolonClassElement() {
22879             var node = createBaseNode(229 /* SemicolonClassElement */);
22880             node.transformFlags |= 256 /* ContainsES2015 */;
22881             return node;
22882         }
22883         //
22884         // Element
22885         //
22886         // @api
22887         function createBlock(statements, multiLine) {
22888             var node = createBaseNode(230 /* Block */);
22889             node.statements = createNodeArray(statements);
22890             node.multiLine = multiLine;
22891             node.transformFlags |= propagateChildrenFlags(node.statements);
22892             return node;
22893         }
22894         // @api
22895         function updateBlock(node, statements) {
22896             return node.statements !== statements
22897                 ? update(createBlock(statements, node.multiLine), node)
22898                 : node;
22899         }
22900         // @api
22901         function createVariableStatement(modifiers, declarationList) {
22902             var node = createBaseDeclaration(232 /* VariableStatement */, /*decorators*/ undefined, modifiers);
22903             node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
22904             node.transformFlags |=
22905                 propagateChildFlags(node.declarationList);
22906             if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
22907                 node.transformFlags = 1 /* ContainsTypeScript */;
22908             }
22909             return node;
22910         }
22911         // @api
22912         function updateVariableStatement(node, modifiers, declarationList) {
22913             return node.modifiers !== modifiers
22914                 || node.declarationList !== declarationList
22915                 ? update(createVariableStatement(modifiers, declarationList), node)
22916                 : node;
22917         }
22918         // @api
22919         function createEmptyStatement() {
22920             return createBaseNode(231 /* EmptyStatement */);
22921         }
22922         // @api
22923         function createExpressionStatement(expression) {
22924             var node = createBaseNode(233 /* ExpressionStatement */);
22925             node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression);
22926             node.transformFlags |= propagateChildFlags(node.expression);
22927             return node;
22928         }
22929         // @api
22930         function updateExpressionStatement(node, expression) {
22931             return node.expression !== expression
22932                 ? update(createExpressionStatement(expression), node)
22933                 : node;
22934         }
22935         // @api
22936         function createIfStatement(expression, thenStatement, elseStatement) {
22937             var node = createBaseNode(234 /* IfStatement */);
22938             node.expression = expression;
22939             node.thenStatement = asEmbeddedStatement(thenStatement);
22940             node.elseStatement = asEmbeddedStatement(elseStatement);
22941             node.transformFlags |=
22942                 propagateChildFlags(node.expression) |
22943                     propagateChildFlags(node.thenStatement) |
22944                     propagateChildFlags(node.elseStatement);
22945             return node;
22946         }
22947         // @api
22948         function updateIfStatement(node, expression, thenStatement, elseStatement) {
22949             return node.expression !== expression
22950                 || node.thenStatement !== thenStatement
22951                 || node.elseStatement !== elseStatement
22952                 ? update(createIfStatement(expression, thenStatement, elseStatement), node)
22953                 : node;
22954         }
22955         // @api
22956         function createDoStatement(statement, expression) {
22957             var node = createBaseNode(235 /* DoStatement */);
22958             node.statement = asEmbeddedStatement(statement);
22959             node.expression = expression;
22960             node.transformFlags |=
22961                 propagateChildFlags(node.statement) |
22962                     propagateChildFlags(node.expression);
22963             return node;
22964         }
22965         // @api
22966         function updateDoStatement(node, statement, expression) {
22967             return node.statement !== statement
22968                 || node.expression !== expression
22969                 ? update(createDoStatement(statement, expression), node)
22970                 : node;
22971         }
22972         // @api
22973         function createWhileStatement(expression, statement) {
22974             var node = createBaseNode(236 /* WhileStatement */);
22975             node.expression = expression;
22976             node.statement = asEmbeddedStatement(statement);
22977             node.transformFlags |=
22978                 propagateChildFlags(node.expression) |
22979                     propagateChildFlags(node.statement);
22980             return node;
22981         }
22982         // @api
22983         function updateWhileStatement(node, expression, statement) {
22984             return node.expression !== expression
22985                 || node.statement !== statement
22986                 ? update(createWhileStatement(expression, statement), node)
22987                 : node;
22988         }
22989         // @api
22990         function createForStatement(initializer, condition, incrementor, statement) {
22991             var node = createBaseNode(237 /* ForStatement */);
22992             node.initializer = initializer;
22993             node.condition = condition;
22994             node.incrementor = incrementor;
22995             node.statement = asEmbeddedStatement(statement);
22996             node.transformFlags |=
22997                 propagateChildFlags(node.initializer) |
22998                     propagateChildFlags(node.condition) |
22999                     propagateChildFlags(node.incrementor) |
23000                     propagateChildFlags(node.statement);
23001             return node;
23002         }
23003         // @api
23004         function updateForStatement(node, initializer, condition, incrementor, statement) {
23005             return node.initializer !== initializer
23006                 || node.condition !== condition
23007                 || node.incrementor !== incrementor
23008                 || node.statement !== statement
23009                 ? update(createForStatement(initializer, condition, incrementor, statement), node)
23010                 : node;
23011         }
23012         // @api
23013         function createForInStatement(initializer, expression, statement) {
23014             var node = createBaseNode(238 /* ForInStatement */);
23015             node.initializer = initializer;
23016             node.expression = expression;
23017             node.statement = asEmbeddedStatement(statement);
23018             node.transformFlags |=
23019                 propagateChildFlags(node.initializer) |
23020                     propagateChildFlags(node.expression) |
23021                     propagateChildFlags(node.statement);
23022             return node;
23023         }
23024         // @api
23025         function updateForInStatement(node, initializer, expression, statement) {
23026             return node.initializer !== initializer
23027                 || node.expression !== expression
23028                 || node.statement !== statement
23029                 ? update(createForInStatement(initializer, expression, statement), node)
23030                 : node;
23031         }
23032         // @api
23033         function createForOfStatement(awaitModifier, initializer, expression, statement) {
23034             var node = createBaseNode(239 /* ForOfStatement */);
23035             node.awaitModifier = awaitModifier;
23036             node.initializer = initializer;
23037             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
23038             node.statement = asEmbeddedStatement(statement);
23039             node.transformFlags |=
23040                 propagateChildFlags(node.awaitModifier) |
23041                     propagateChildFlags(node.initializer) |
23042                     propagateChildFlags(node.expression) |
23043                     propagateChildFlags(node.statement) |
23044                     256 /* ContainsES2015 */;
23045             if (awaitModifier)
23046                 node.transformFlags |= 32 /* ContainsES2018 */;
23047             return node;
23048         }
23049         // @api
23050         function updateForOfStatement(node, awaitModifier, initializer, expression, statement) {
23051             return node.awaitModifier !== awaitModifier
23052                 || node.initializer !== initializer
23053                 || node.expression !== expression
23054                 || node.statement !== statement
23055                 ? update(createForOfStatement(awaitModifier, initializer, expression, statement), node)
23056                 : node;
23057         }
23058         // @api
23059         function createContinueStatement(label) {
23060             var node = createBaseNode(240 /* ContinueStatement */);
23061             node.label = asName(label);
23062             node.transformFlags |=
23063                 propagateChildFlags(node.label) |
23064                     1048576 /* ContainsHoistedDeclarationOrCompletion */;
23065             return node;
23066         }
23067         // @api
23068         function updateContinueStatement(node, label) {
23069             return node.label !== label
23070                 ? update(createContinueStatement(label), node)
23071                 : node;
23072         }
23073         // @api
23074         function createBreakStatement(label) {
23075             var node = createBaseNode(241 /* BreakStatement */);
23076             node.label = asName(label);
23077             node.transformFlags |=
23078                 propagateChildFlags(node.label) |
23079                     1048576 /* ContainsHoistedDeclarationOrCompletion */;
23080             return node;
23081         }
23082         // @api
23083         function updateBreakStatement(node, label) {
23084             return node.label !== label
23085                 ? update(createBreakStatement(label), node)
23086                 : node;
23087         }
23088         // @api
23089         function createReturnStatement(expression) {
23090             var node = createBaseNode(242 /* ReturnStatement */);
23091             node.expression = expression;
23092             // return in an ES2018 async generator must be awaited
23093             node.transformFlags |=
23094                 propagateChildFlags(node.expression) |
23095                     32 /* ContainsES2018 */ |
23096                     1048576 /* ContainsHoistedDeclarationOrCompletion */;
23097             return node;
23098         }
23099         // @api
23100         function updateReturnStatement(node, expression) {
23101             return node.expression !== expression
23102                 ? update(createReturnStatement(expression), node)
23103                 : node;
23104         }
23105         // @api
23106         function createWithStatement(expression, statement) {
23107             var node = createBaseNode(243 /* WithStatement */);
23108             node.expression = expression;
23109             node.statement = asEmbeddedStatement(statement);
23110             node.transformFlags |=
23111                 propagateChildFlags(node.expression) |
23112                     propagateChildFlags(node.statement);
23113             return node;
23114         }
23115         // @api
23116         function updateWithStatement(node, expression, statement) {
23117             return node.expression !== expression
23118                 || node.statement !== statement
23119                 ? update(createWithStatement(expression, statement), node)
23120                 : node;
23121         }
23122         // @api
23123         function createSwitchStatement(expression, caseBlock) {
23124             var node = createBaseNode(244 /* SwitchStatement */);
23125             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
23126             node.caseBlock = caseBlock;
23127             node.transformFlags |=
23128                 propagateChildFlags(node.expression) |
23129                     propagateChildFlags(node.caseBlock);
23130             return node;
23131         }
23132         // @api
23133         function updateSwitchStatement(node, expression, caseBlock) {
23134             return node.expression !== expression
23135                 || node.caseBlock !== caseBlock
23136                 ? update(createSwitchStatement(expression, caseBlock), node)
23137                 : node;
23138         }
23139         // @api
23140         function createLabeledStatement(label, statement) {
23141             var node = createBaseNode(245 /* LabeledStatement */);
23142             node.label = asName(label);
23143             node.statement = asEmbeddedStatement(statement);
23144             node.transformFlags |=
23145                 propagateChildFlags(node.label) |
23146                     propagateChildFlags(node.statement);
23147             return node;
23148         }
23149         // @api
23150         function updateLabeledStatement(node, label, statement) {
23151             return node.label !== label
23152                 || node.statement !== statement
23153                 ? update(createLabeledStatement(label, statement), node)
23154                 : node;
23155         }
23156         // @api
23157         function createThrowStatement(expression) {
23158             var node = createBaseNode(246 /* ThrowStatement */);
23159             node.expression = expression;
23160             node.transformFlags |= propagateChildFlags(node.expression);
23161             return node;
23162         }
23163         // @api
23164         function updateThrowStatement(node, expression) {
23165             return node.expression !== expression
23166                 ? update(createThrowStatement(expression), node)
23167                 : node;
23168         }
23169         // @api
23170         function createTryStatement(tryBlock, catchClause, finallyBlock) {
23171             var node = createBaseNode(247 /* TryStatement */);
23172             node.tryBlock = tryBlock;
23173             node.catchClause = catchClause;
23174             node.finallyBlock = finallyBlock;
23175             node.transformFlags |=
23176                 propagateChildFlags(node.tryBlock) |
23177                     propagateChildFlags(node.catchClause) |
23178                     propagateChildFlags(node.finallyBlock);
23179             return node;
23180         }
23181         // @api
23182         function updateTryStatement(node, tryBlock, catchClause, finallyBlock) {
23183             return node.tryBlock !== tryBlock
23184                 || node.catchClause !== catchClause
23185                 || node.finallyBlock !== finallyBlock
23186                 ? update(createTryStatement(tryBlock, catchClause, finallyBlock), node)
23187                 : node;
23188         }
23189         // @api
23190         function createDebuggerStatement() {
23191             return createBaseNode(248 /* DebuggerStatement */);
23192         }
23193         // @api
23194         function createVariableDeclaration(name, exclamationToken, type, initializer) {
23195             var node = createBaseVariableLikeDeclaration(249 /* VariableDeclaration */, 
23196             /*decorators*/ undefined, 
23197             /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer));
23198             node.exclamationToken = exclamationToken;
23199             node.transformFlags |= propagateChildFlags(node.exclamationToken);
23200             if (exclamationToken) {
23201                 node.transformFlags |= 1 /* ContainsTypeScript */;
23202             }
23203             return node;
23204         }
23205         // @api
23206         function updateVariableDeclaration(node, name, exclamationToken, type, initializer) {
23207             return node.name !== name
23208                 || node.type !== type
23209                 || node.exclamationToken !== exclamationToken
23210                 || node.initializer !== initializer
23211                 ? update(createVariableDeclaration(name, exclamationToken, type, initializer), node)
23212                 : node;
23213         }
23214         // @api
23215         function createVariableDeclarationList(declarations, flags) {
23216             if (flags === void 0) { flags = 0 /* None */; }
23217             var node = createBaseNode(250 /* VariableDeclarationList */);
23218             node.flags |= flags & 3 /* BlockScoped */;
23219             node.declarations = createNodeArray(declarations);
23220             node.transformFlags |=
23221                 propagateChildrenFlags(node.declarations) |
23222                     1048576 /* ContainsHoistedDeclarationOrCompletion */;
23223             if (flags & 3 /* BlockScoped */) {
23224                 node.transformFlags |=
23225                     256 /* ContainsES2015 */ |
23226                         65536 /* ContainsBlockScopedBinding */;
23227             }
23228             return node;
23229         }
23230         // @api
23231         function updateVariableDeclarationList(node, declarations) {
23232             return node.declarations !== declarations
23233                 ? update(createVariableDeclarationList(declarations, node.flags), node)
23234                 : node;
23235         }
23236         // @api
23237         function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
23238             var node = createBaseFunctionLikeDeclaration(251 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body);
23239             node.asteriskToken = asteriskToken;
23240             if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
23241                 node.transformFlags = 1 /* ContainsTypeScript */;
23242             }
23243             else {
23244                 node.transformFlags |=
23245                     propagateChildFlags(node.asteriskToken) |
23246                         1048576 /* ContainsHoistedDeclarationOrCompletion */;
23247                 if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
23248                     if (node.asteriskToken) {
23249                         node.transformFlags |= 32 /* ContainsES2018 */;
23250                     }
23251                     else {
23252                         node.transformFlags |= 64 /* ContainsES2017 */;
23253                     }
23254                 }
23255                 else if (node.asteriskToken) {
23256                     node.transformFlags |= 512 /* ContainsGenerator */;
23257                 }
23258             }
23259             return node;
23260         }
23261         // @api
23262         function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
23263             return node.decorators !== decorators
23264                 || node.modifiers !== modifiers
23265                 || node.asteriskToken !== asteriskToken
23266                 || node.name !== name
23267                 || node.typeParameters !== typeParameters
23268                 || node.parameters !== parameters
23269                 || node.type !== type
23270                 || node.body !== body
23271                 ? updateBaseFunctionLikeDeclaration(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
23272                 : node;
23273         }
23274         // @api
23275         function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
23276             var node = createBaseClassLikeDeclaration(252 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members);
23277             if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
23278                 node.transformFlags = 1 /* ContainsTypeScript */;
23279             }
23280             else {
23281                 node.transformFlags |= 256 /* ContainsES2015 */;
23282                 if (node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */) {
23283                     node.transformFlags |= 1 /* ContainsTypeScript */;
23284                 }
23285             }
23286             return node;
23287         }
23288         // @api
23289         function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
23290             return node.decorators !== decorators
23291                 || node.modifiers !== modifiers
23292                 || node.name !== name
23293                 || node.typeParameters !== typeParameters
23294                 || node.heritageClauses !== heritageClauses
23295                 || node.members !== members
23296                 ? update(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
23297                 : node;
23298         }
23299         // @api
23300         function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
23301             var node = createBaseInterfaceOrClassLikeDeclaration(253 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses);
23302             node.members = createNodeArray(members);
23303             node.transformFlags = 1 /* ContainsTypeScript */;
23304             return node;
23305         }
23306         // @api
23307         function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
23308             return node.decorators !== decorators
23309                 || node.modifiers !== modifiers
23310                 || node.name !== name
23311                 || node.typeParameters !== typeParameters
23312                 || node.heritageClauses !== heritageClauses
23313                 || node.members !== members
23314                 ? update(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
23315                 : node;
23316         }
23317         // @api
23318         function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) {
23319             var node = createBaseGenericNamedDeclaration(254 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters);
23320             node.type = type;
23321             node.transformFlags = 1 /* ContainsTypeScript */;
23322             return node;
23323         }
23324         // @api
23325         function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) {
23326             return node.decorators !== decorators
23327                 || node.modifiers !== modifiers
23328                 || node.name !== name
23329                 || node.typeParameters !== typeParameters
23330                 || node.type !== type
23331                 ? update(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
23332                 : node;
23333         }
23334         // @api
23335         function createEnumDeclaration(decorators, modifiers, name, members) {
23336             var node = createBaseNamedDeclaration(255 /* EnumDeclaration */, decorators, modifiers, name);
23337             node.members = createNodeArray(members);
23338             node.transformFlags |=
23339                 propagateChildrenFlags(node.members) |
23340                     1 /* ContainsTypeScript */;
23341             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await`
23342             return node;
23343         }
23344         // @api
23345         function updateEnumDeclaration(node, decorators, modifiers, name, members) {
23346             return node.decorators !== decorators
23347                 || node.modifiers !== modifiers
23348                 || node.name !== name
23349                 || node.members !== members
23350                 ? update(createEnumDeclaration(decorators, modifiers, name, members), node)
23351                 : node;
23352         }
23353         // @api
23354         function createModuleDeclaration(decorators, modifiers, name, body, flags) {
23355             if (flags === void 0) { flags = 0 /* None */; }
23356             var node = createBaseDeclaration(256 /* ModuleDeclaration */, decorators, modifiers);
23357             node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */);
23358             node.name = name;
23359             node.body = body;
23360             if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
23361                 node.transformFlags = 1 /* ContainsTypeScript */;
23362             }
23363             else {
23364                 node.transformFlags |=
23365                     propagateChildFlags(node.name) |
23366                         propagateChildFlags(node.body) |
23367                         1 /* ContainsTypeScript */;
23368             }
23369             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`.
23370             return node;
23371         }
23372         // @api
23373         function updateModuleDeclaration(node, decorators, modifiers, name, body) {
23374             return node.decorators !== decorators
23375                 || node.modifiers !== modifiers
23376                 || node.name !== name
23377                 || node.body !== body
23378                 ? update(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
23379                 : node;
23380         }
23381         // @api
23382         function createModuleBlock(statements) {
23383             var node = createBaseNode(257 /* ModuleBlock */);
23384             node.statements = createNodeArray(statements);
23385             node.transformFlags |= propagateChildrenFlags(node.statements);
23386             return node;
23387         }
23388         // @api
23389         function updateModuleBlock(node, statements) {
23390             return node.statements !== statements
23391                 ? update(createModuleBlock(statements), node)
23392                 : node;
23393         }
23394         // @api
23395         function createCaseBlock(clauses) {
23396             var node = createBaseNode(258 /* CaseBlock */);
23397             node.clauses = createNodeArray(clauses);
23398             node.transformFlags |= propagateChildrenFlags(node.clauses);
23399             return node;
23400         }
23401         // @api
23402         function updateCaseBlock(node, clauses) {
23403             return node.clauses !== clauses
23404                 ? update(createCaseBlock(clauses), node)
23405                 : node;
23406         }
23407         // @api
23408         function createNamespaceExportDeclaration(name) {
23409             var node = createBaseNamedDeclaration(259 /* NamespaceExportDeclaration */, 
23410             /*decorators*/ undefined, 
23411             /*modifiers*/ undefined, name);
23412             node.transformFlags = 1 /* ContainsTypeScript */;
23413             return node;
23414         }
23415         // @api
23416         function updateNamespaceExportDeclaration(node, name) {
23417             return node.name !== name
23418                 ? update(createNamespaceExportDeclaration(name), node)
23419                 : node;
23420         }
23421         // @api
23422         function createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference) {
23423             var node = createBaseNamedDeclaration(260 /* ImportEqualsDeclaration */, decorators, modifiers, name);
23424             node.isTypeOnly = isTypeOnly;
23425             node.moduleReference = moduleReference;
23426             node.transformFlags |= propagateChildFlags(node.moduleReference);
23427             if (!ts.isExternalModuleReference(node.moduleReference))
23428                 node.transformFlags |= 1 /* ContainsTypeScript */;
23429             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context
23430             return node;
23431         }
23432         // @api
23433         function updateImportEqualsDeclaration(node, decorators, modifiers, isTypeOnly, name, moduleReference) {
23434             return node.decorators !== decorators
23435                 || node.modifiers !== modifiers
23436                 || node.isTypeOnly !== isTypeOnly
23437                 || node.name !== name
23438                 || node.moduleReference !== moduleReference
23439                 ? update(createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, name, moduleReference), node)
23440                 : node;
23441         }
23442         // @api
23443         function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) {
23444             var node = createBaseDeclaration(261 /* ImportDeclaration */, decorators, modifiers);
23445             node.importClause = importClause;
23446             node.moduleSpecifier = moduleSpecifier;
23447             node.transformFlags |=
23448                 propagateChildFlags(node.importClause) |
23449                     propagateChildFlags(node.moduleSpecifier);
23450             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23451             return node;
23452         }
23453         // @api
23454         function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) {
23455             return node.decorators !== decorators
23456                 || node.modifiers !== modifiers
23457                 || node.importClause !== importClause
23458                 || node.moduleSpecifier !== moduleSpecifier
23459                 ? update(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
23460                 : node;
23461         }
23462         // @api
23463         function createImportClause(isTypeOnly, name, namedBindings) {
23464             var node = createBaseNode(262 /* ImportClause */);
23465             node.isTypeOnly = isTypeOnly;
23466             node.name = name;
23467             node.namedBindings = namedBindings;
23468             node.transformFlags |=
23469                 propagateChildFlags(node.name) |
23470                     propagateChildFlags(node.namedBindings);
23471             if (isTypeOnly) {
23472                 node.transformFlags |= 1 /* ContainsTypeScript */;
23473             }
23474             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23475             return node;
23476         }
23477         // @api
23478         function updateImportClause(node, isTypeOnly, name, namedBindings) {
23479             return node.isTypeOnly !== isTypeOnly
23480                 || node.name !== name
23481                 || node.namedBindings !== namedBindings
23482                 ? update(createImportClause(isTypeOnly, name, namedBindings), node)
23483                 : node;
23484         }
23485         // @api
23486         function createNamespaceImport(name) {
23487             var node = createBaseNode(263 /* NamespaceImport */);
23488             node.name = name;
23489             node.transformFlags |= propagateChildFlags(node.name);
23490             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23491             return node;
23492         }
23493         // @api
23494         function updateNamespaceImport(node, name) {
23495             return node.name !== name
23496                 ? update(createNamespaceImport(name), node)
23497                 : node;
23498         }
23499         // @api
23500         function createNamespaceExport(name) {
23501             var node = createBaseNode(269 /* NamespaceExport */);
23502             node.name = name;
23503             node.transformFlags |=
23504                 propagateChildFlags(node.name) |
23505                     4 /* ContainsESNext */;
23506             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23507             return node;
23508         }
23509         // @api
23510         function updateNamespaceExport(node, name) {
23511             return node.name !== name
23512                 ? update(createNamespaceExport(name), node)
23513                 : node;
23514         }
23515         // @api
23516         function createNamedImports(elements) {
23517             var node = createBaseNode(264 /* NamedImports */);
23518             node.elements = createNodeArray(elements);
23519             node.transformFlags |= propagateChildrenFlags(node.elements);
23520             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23521             return node;
23522         }
23523         // @api
23524         function updateNamedImports(node, elements) {
23525             return node.elements !== elements
23526                 ? update(createNamedImports(elements), node)
23527                 : node;
23528         }
23529         // @api
23530         function createImportSpecifier(propertyName, name) {
23531             var node = createBaseNode(265 /* ImportSpecifier */);
23532             node.propertyName = propertyName;
23533             node.name = name;
23534             node.transformFlags |=
23535                 propagateChildFlags(node.propertyName) |
23536                     propagateChildFlags(node.name);
23537             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23538             return node;
23539         }
23540         // @api
23541         function updateImportSpecifier(node, propertyName, name) {
23542             return node.propertyName !== propertyName
23543                 || node.name !== name
23544                 ? update(createImportSpecifier(propertyName, name), node)
23545                 : node;
23546         }
23547         // @api
23548         function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
23549             var node = createBaseDeclaration(266 /* ExportAssignment */, decorators, modifiers);
23550             node.isExportEquals = isExportEquals;
23551             node.expression = isExportEquals
23552                 ? parenthesizerRules().parenthesizeRightSideOfBinary(62 /* EqualsToken */, /*leftSide*/ undefined, expression)
23553                 : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression);
23554             node.transformFlags |= propagateChildFlags(node.expression);
23555             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23556             return node;
23557         }
23558         // @api
23559         function updateExportAssignment(node, decorators, modifiers, expression) {
23560             return node.decorators !== decorators
23561                 || node.modifiers !== modifiers
23562                 || node.expression !== expression
23563                 ? update(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
23564                 : node;
23565         }
23566         // @api
23567         function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier) {
23568             var node = createBaseDeclaration(267 /* ExportDeclaration */, decorators, modifiers);
23569             node.isTypeOnly = isTypeOnly;
23570             node.exportClause = exportClause;
23571             node.moduleSpecifier = moduleSpecifier;
23572             node.transformFlags |=
23573                 propagateChildFlags(node.exportClause) |
23574                     propagateChildFlags(node.moduleSpecifier);
23575             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23576             return node;
23577         }
23578         // @api
23579         function updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier) {
23580             return node.decorators !== decorators
23581                 || node.modifiers !== modifiers
23582                 || node.isTypeOnly !== isTypeOnly
23583                 || node.exportClause !== exportClause
23584                 || node.moduleSpecifier !== moduleSpecifier
23585                 ? update(createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier), node)
23586                 : node;
23587         }
23588         // @api
23589         function createNamedExports(elements) {
23590             var node = createBaseNode(268 /* NamedExports */);
23591             node.elements = createNodeArray(elements);
23592             node.transformFlags |= propagateChildrenFlags(node.elements);
23593             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23594             return node;
23595         }
23596         // @api
23597         function updateNamedExports(node, elements) {
23598             return node.elements !== elements
23599                 ? update(createNamedExports(elements), node)
23600                 : node;
23601         }
23602         // @api
23603         function createExportSpecifier(propertyName, name) {
23604             var node = createBaseNode(270 /* ExportSpecifier */);
23605             node.propertyName = asName(propertyName);
23606             node.name = asName(name);
23607             node.transformFlags |=
23608                 propagateChildFlags(node.propertyName) |
23609                     propagateChildFlags(node.name);
23610             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23611             return node;
23612         }
23613         // @api
23614         function updateExportSpecifier(node, propertyName, name) {
23615             return node.propertyName !== propertyName
23616                 || node.name !== name
23617                 ? update(createExportSpecifier(propertyName, name), node)
23618                 : node;
23619         }
23620         // @api
23621         function createMissingDeclaration() {
23622             var node = createBaseDeclaration(271 /* MissingDeclaration */, 
23623             /*decorators*/ undefined, 
23624             /*modifiers*/ undefined);
23625             return node;
23626         }
23627         //
23628         // Module references
23629         //
23630         // @api
23631         function createExternalModuleReference(expression) {
23632             var node = createBaseNode(272 /* ExternalModuleReference */);
23633             node.expression = expression;
23634             node.transformFlags |= propagateChildFlags(node.expression);
23635             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23636             return node;
23637         }
23638         // @api
23639         function updateExternalModuleReference(node, expression) {
23640             return node.expression !== expression
23641                 ? update(createExternalModuleReference(expression), node)
23642                 : node;
23643         }
23644         //
23645         // JSDoc
23646         //
23647         // @api
23648         // createJSDocAllType
23649         // createJSDocUnknownType
23650         function createJSDocPrimaryTypeWorker(kind) {
23651             return createBaseNode(kind);
23652         }
23653         // @api
23654         // createJSDocNonNullableType
23655         // createJSDocNullableType
23656         // createJSDocOptionalType
23657         // createJSDocVariadicType
23658         // createJSDocNamepathType
23659         function createJSDocUnaryTypeWorker(kind, type) {
23660             var node = createBaseNode(kind);
23661             node.type = type;
23662             return node;
23663         }
23664         // @api
23665         // updateJSDocNonNullableType
23666         // updateJSDocNullableType
23667         // updateJSDocOptionalType
23668         // updateJSDocVariadicType
23669         // updateJSDocNamepathType
23670         function updateJSDocUnaryTypeWorker(kind, node, type) {
23671             return node.type !== type
23672                 ? update(createJSDocUnaryTypeWorker(kind, type), node)
23673                 : node;
23674         }
23675         // @api
23676         function createJSDocFunctionType(parameters, type) {
23677             var node = createBaseSignatureDeclaration(308 /* JSDocFunctionType */, 
23678             /*decorators*/ undefined, 
23679             /*modifiers*/ undefined, 
23680             /*name*/ undefined, 
23681             /*typeParameters*/ undefined, parameters, type);
23682             return node;
23683         }
23684         // @api
23685         function updateJSDocFunctionType(node, parameters, type) {
23686             return node.parameters !== parameters
23687                 || node.type !== type
23688                 ? update(createJSDocFunctionType(parameters, type), node)
23689                 : node;
23690         }
23691         // @api
23692         function createJSDocTypeLiteral(propertyTags, isArrayType) {
23693             if (isArrayType === void 0) { isArrayType = false; }
23694             var node = createBaseNode(312 /* JSDocTypeLiteral */);
23695             node.jsDocPropertyTags = asNodeArray(propertyTags);
23696             node.isArrayType = isArrayType;
23697             return node;
23698         }
23699         // @api
23700         function updateJSDocTypeLiteral(node, propertyTags, isArrayType) {
23701             return node.jsDocPropertyTags !== propertyTags
23702                 || node.isArrayType !== isArrayType
23703                 ? update(createJSDocTypeLiteral(propertyTags, isArrayType), node)
23704                 : node;
23705         }
23706         // @api
23707         function createJSDocTypeExpression(type) {
23708             var node = createBaseNode(301 /* JSDocTypeExpression */);
23709             node.type = type;
23710             return node;
23711         }
23712         // @api
23713         function updateJSDocTypeExpression(node, type) {
23714             return node.type !== type
23715                 ? update(createJSDocTypeExpression(type), node)
23716                 : node;
23717         }
23718         // @api
23719         function createJSDocSignature(typeParameters, parameters, type) {
23720             var node = createBaseNode(313 /* JSDocSignature */);
23721             node.typeParameters = asNodeArray(typeParameters);
23722             node.parameters = createNodeArray(parameters);
23723             node.type = type;
23724             return node;
23725         }
23726         // @api
23727         function updateJSDocSignature(node, typeParameters, parameters, type) {
23728             return node.typeParameters !== typeParameters
23729                 || node.parameters !== parameters
23730                 || node.type !== type
23731                 ? update(createJSDocSignature(typeParameters, parameters, type), node)
23732                 : node;
23733         }
23734         function getDefaultTagName(node) {
23735             var defaultTagName = getDefaultTagNameForKind(node.kind);
23736             return node.tagName.escapedText === ts.escapeLeadingUnderscores(defaultTagName)
23737                 ? node.tagName
23738                 : createIdentifier(defaultTagName);
23739         }
23740         // @api
23741         function createBaseJSDocTag(kind, tagName, comment) {
23742             var node = createBaseNode(kind);
23743             node.tagName = tagName;
23744             node.comment = comment;
23745             return node;
23746         }
23747         // @api
23748         function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) {
23749             var node = createBaseJSDocTag(330 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment);
23750             node.constraint = constraint;
23751             node.typeParameters = createNodeArray(typeParameters);
23752             return node;
23753         }
23754         // @api
23755         function updateJSDocTemplateTag(node, tagName, constraint, typeParameters, comment) {
23756             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23757             return node.tagName !== tagName
23758                 || node.constraint !== constraint
23759                 || node.typeParameters !== typeParameters
23760                 || node.comment !== comment
23761                 ? update(createJSDocTemplateTag(tagName, constraint, typeParameters, comment), node)
23762                 : node;
23763         }
23764         // @api
23765         function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) {
23766             var node = createBaseJSDocTag(331 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment);
23767             node.typeExpression = typeExpression;
23768             node.fullName = fullName;
23769             node.name = ts.getJSDocTypeAliasName(fullName);
23770             return node;
23771         }
23772         // @api
23773         function updateJSDocTypedefTag(node, tagName, typeExpression, fullName, comment) {
23774             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23775             return node.tagName !== tagName
23776                 || node.typeExpression !== typeExpression
23777                 || node.fullName !== fullName
23778                 || node.comment !== comment
23779                 ? update(createJSDocTypedefTag(tagName, typeExpression, fullName, comment), node)
23780                 : node;
23781         }
23782         // @api
23783         function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
23784             var node = createBaseJSDocTag(326 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment);
23785             node.typeExpression = typeExpression;
23786             node.name = name;
23787             node.isNameFirst = !!isNameFirst;
23788             node.isBracketed = isBracketed;
23789             return node;
23790         }
23791         // @api
23792         function updateJSDocParameterTag(node, tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
23793             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23794             return node.tagName !== tagName
23795                 || node.name !== name
23796                 || node.isBracketed !== isBracketed
23797                 || node.typeExpression !== typeExpression
23798                 || node.isNameFirst !== isNameFirst
23799                 || node.comment !== comment
23800                 ? update(createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node)
23801                 : node;
23802         }
23803         // @api
23804         function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
23805             var node = createBaseJSDocTag(333 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment);
23806             node.typeExpression = typeExpression;
23807             node.name = name;
23808             node.isNameFirst = !!isNameFirst;
23809             node.isBracketed = isBracketed;
23810             return node;
23811         }
23812         // @api
23813         function updateJSDocPropertyTag(node, tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
23814             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23815             return node.tagName !== tagName
23816                 || node.name !== name
23817                 || node.isBracketed !== isBracketed
23818                 || node.typeExpression !== typeExpression
23819                 || node.isNameFirst !== isNameFirst
23820                 || node.comment !== comment
23821                 ? update(createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node)
23822                 : node;
23823         }
23824         // @api
23825         function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) {
23826             var node = createBaseJSDocTag(324 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment);
23827             node.typeExpression = typeExpression;
23828             node.fullName = fullName;
23829             node.name = ts.getJSDocTypeAliasName(fullName);
23830             return node;
23831         }
23832         // @api
23833         function updateJSDocCallbackTag(node, tagName, typeExpression, fullName, comment) {
23834             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23835             return node.tagName !== tagName
23836                 || node.typeExpression !== typeExpression
23837                 || node.fullName !== fullName
23838                 || node.comment !== comment
23839                 ? update(createJSDocCallbackTag(tagName, typeExpression, fullName, comment), node)
23840                 : node;
23841         }
23842         // @api
23843         function createJSDocAugmentsTag(tagName, className, comment) {
23844             var node = createBaseJSDocTag(315 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment);
23845             node.class = className;
23846             return node;
23847         }
23848         // @api
23849         function updateJSDocAugmentsTag(node, tagName, className, comment) {
23850             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23851             return node.tagName !== tagName
23852                 || node.class !== className
23853                 || node.comment !== comment
23854                 ? update(createJSDocAugmentsTag(tagName, className, comment), node)
23855                 : node;
23856         }
23857         // @api
23858         function createJSDocImplementsTag(tagName, className, comment) {
23859             var node = createBaseJSDocTag(316 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment);
23860             node.class = className;
23861             return node;
23862         }
23863         // @api
23864         function createJSDocSeeTag(tagName, name, comment) {
23865             var node = createBaseJSDocTag(332 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment);
23866             node.name = name;
23867             return node;
23868         }
23869         // @api
23870         function updateJSDocSeeTag(node, tagName, name, comment) {
23871             return node.tagName !== tagName
23872                 || node.name !== name
23873                 || node.comment !== comment
23874                 ? update(createJSDocSeeTag(tagName, name, comment), node)
23875                 : node;
23876         }
23877         // @api
23878         function createJSDocNameReference(name) {
23879             var node = createBaseNode(302 /* JSDocNameReference */);
23880             node.name = name;
23881             return node;
23882         }
23883         // @api
23884         function updateJSDocNameReference(node, name) {
23885             return node.name !== name
23886                 ? update(createJSDocNameReference(name), node)
23887                 : node;
23888         }
23889         // @api
23890         function updateJSDocImplementsTag(node, tagName, className, comment) {
23891             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23892             return node.tagName !== tagName
23893                 || node.class !== className
23894                 || node.comment !== comment
23895                 ? update(createJSDocImplementsTag(tagName, className, comment), node)
23896                 : node;
23897         }
23898         // @api
23899         // createJSDocAuthorTag
23900         // createJSDocClassTag
23901         // createJSDocPublicTag
23902         // createJSDocPrivateTag
23903         // createJSDocProtectedTag
23904         // createJSDocReadonlyTag
23905         // createJSDocDeprecatedTag
23906         function createJSDocSimpleTagWorker(kind, tagName, comment) {
23907             var node = createBaseJSDocTag(kind, tagName !== null && tagName !== void 0 ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment);
23908             return node;
23909         }
23910         // @api
23911         // updateJSDocAuthorTag
23912         // updateJSDocClassTag
23913         // updateJSDocPublicTag
23914         // updateJSDocPrivateTag
23915         // updateJSDocProtectedTag
23916         // updateJSDocReadonlyTag
23917         // updateJSDocDeprecatedTag
23918         function updateJSDocSimpleTagWorker(kind, node, tagName, comment) {
23919             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23920             return node.tagName !== tagName
23921                 || node.comment !== comment
23922                 ? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) :
23923                 node;
23924         }
23925         // @api
23926         // createJSDocTypeTag
23927         // createJSDocReturnTag
23928         // createJSDocThisTag
23929         // createJSDocEnumTag
23930         function createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment) {
23931             var node = createBaseJSDocTag(kind, tagName !== null && tagName !== void 0 ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment);
23932             node.typeExpression = typeExpression;
23933             return node;
23934         }
23935         // @api
23936         // updateJSDocTypeTag
23937         // updateJSDocReturnTag
23938         // updateJSDocThisTag
23939         // updateJSDocEnumTag
23940         function updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment) {
23941             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23942             return node.tagName !== tagName
23943                 || node.typeExpression !== typeExpression
23944                 || node.comment !== comment
23945                 ? update(createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment), node)
23946                 : node;
23947         }
23948         // @api
23949         function createJSDocUnknownTag(tagName, comment) {
23950             var node = createBaseJSDocTag(314 /* JSDocTag */, tagName, comment);
23951             return node;
23952         }
23953         // @api
23954         function updateJSDocUnknownTag(node, tagName, comment) {
23955             return node.tagName !== tagName
23956                 || node.comment !== comment
23957                 ? update(createJSDocUnknownTag(tagName, comment), node)
23958                 : node;
23959         }
23960         // @api
23961         function createJSDocComment(comment, tags) {
23962             var node = createBaseNode(311 /* JSDocComment */);
23963             node.comment = comment;
23964             node.tags = asNodeArray(tags);
23965             return node;
23966         }
23967         // @api
23968         function updateJSDocComment(node, comment, tags) {
23969             return node.comment !== comment
23970                 || node.tags !== tags
23971                 ? update(createJSDocComment(comment, tags), node)
23972                 : node;
23973         }
23974         //
23975         // JSX
23976         //
23977         // @api
23978         function createJsxElement(openingElement, children, closingElement) {
23979             var node = createBaseNode(273 /* JsxElement */);
23980             node.openingElement = openingElement;
23981             node.children = createNodeArray(children);
23982             node.closingElement = closingElement;
23983             node.transformFlags |=
23984                 propagateChildFlags(node.openingElement) |
23985                     propagateChildrenFlags(node.children) |
23986                     propagateChildFlags(node.closingElement) |
23987                     2 /* ContainsJsx */;
23988             return node;
23989         }
23990         // @api
23991         function updateJsxElement(node, openingElement, children, closingElement) {
23992             return node.openingElement !== openingElement
23993                 || node.children !== children
23994                 || node.closingElement !== closingElement
23995                 ? update(createJsxElement(openingElement, children, closingElement), node)
23996                 : node;
23997         }
23998         // @api
23999         function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
24000             var node = createBaseNode(274 /* JsxSelfClosingElement */);
24001             node.tagName = tagName;
24002             node.typeArguments = asNodeArray(typeArguments);
24003             node.attributes = attributes;
24004             node.transformFlags |=
24005                 propagateChildFlags(node.tagName) |
24006                     propagateChildrenFlags(node.typeArguments) |
24007                     propagateChildFlags(node.attributes) |
24008                     2 /* ContainsJsx */;
24009             if (node.typeArguments) {
24010                 node.transformFlags |= 1 /* ContainsTypeScript */;
24011             }
24012             return node;
24013         }
24014         // @api
24015         function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
24016             return node.tagName !== tagName
24017                 || node.typeArguments !== typeArguments
24018                 || node.attributes !== attributes
24019                 ? update(createJsxSelfClosingElement(tagName, typeArguments, attributes), node)
24020                 : node;
24021         }
24022         // @api
24023         function createJsxOpeningElement(tagName, typeArguments, attributes) {
24024             var node = createBaseNode(275 /* JsxOpeningElement */);
24025             node.tagName = tagName;
24026             node.typeArguments = asNodeArray(typeArguments);
24027             node.attributes = attributes;
24028             node.transformFlags |=
24029                 propagateChildFlags(node.tagName) |
24030                     propagateChildrenFlags(node.typeArguments) |
24031                     propagateChildFlags(node.attributes) |
24032                     2 /* ContainsJsx */;
24033             if (typeArguments) {
24034                 node.transformFlags |= 1 /* ContainsTypeScript */;
24035             }
24036             return node;
24037         }
24038         // @api
24039         function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
24040             return node.tagName !== tagName
24041                 || node.typeArguments !== typeArguments
24042                 || node.attributes !== attributes
24043                 ? update(createJsxOpeningElement(tagName, typeArguments, attributes), node)
24044                 : node;
24045         }
24046         // @api
24047         function createJsxClosingElement(tagName) {
24048             var node = createBaseNode(276 /* JsxClosingElement */);
24049             node.tagName = tagName;
24050             node.transformFlags |=
24051                 propagateChildFlags(node.tagName) |
24052                     2 /* ContainsJsx */;
24053             return node;
24054         }
24055         // @api
24056         function updateJsxClosingElement(node, tagName) {
24057             return node.tagName !== tagName
24058                 ? update(createJsxClosingElement(tagName), node)
24059                 : node;
24060         }
24061         // @api
24062         function createJsxFragment(openingFragment, children, closingFragment) {
24063             var node = createBaseNode(277 /* JsxFragment */);
24064             node.openingFragment = openingFragment;
24065             node.children = createNodeArray(children);
24066             node.closingFragment = closingFragment;
24067             node.transformFlags |=
24068                 propagateChildFlags(node.openingFragment) |
24069                     propagateChildrenFlags(node.children) |
24070                     propagateChildFlags(node.closingFragment) |
24071                     2 /* ContainsJsx */;
24072             return node;
24073         }
24074         // @api
24075         function updateJsxFragment(node, openingFragment, children, closingFragment) {
24076             return node.openingFragment !== openingFragment
24077                 || node.children !== children
24078                 || node.closingFragment !== closingFragment
24079                 ? update(createJsxFragment(openingFragment, children, closingFragment), node)
24080                 : node;
24081         }
24082         // @api
24083         function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
24084             var node = createBaseNode(11 /* JsxText */);
24085             node.text = text;
24086             node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
24087             node.transformFlags |= 2 /* ContainsJsx */;
24088             return node;
24089         }
24090         // @api
24091         function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
24092             return node.text !== text
24093                 || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
24094                 ? update(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
24095                 : node;
24096         }
24097         // @api
24098         function createJsxOpeningFragment() {
24099             var node = createBaseNode(278 /* JsxOpeningFragment */);
24100             node.transformFlags |= 2 /* ContainsJsx */;
24101             return node;
24102         }
24103         // @api
24104         function createJsxJsxClosingFragment() {
24105             var node = createBaseNode(279 /* JsxClosingFragment */);
24106             node.transformFlags |= 2 /* ContainsJsx */;
24107             return node;
24108         }
24109         // @api
24110         function createJsxAttribute(name, initializer) {
24111             var node = createBaseNode(280 /* JsxAttribute */);
24112             node.name = name;
24113             node.initializer = initializer;
24114             node.transformFlags |=
24115                 propagateChildFlags(node.name) |
24116                     propagateChildFlags(node.initializer) |
24117                     2 /* ContainsJsx */;
24118             return node;
24119         }
24120         // @api
24121         function updateJsxAttribute(node, name, initializer) {
24122             return node.name !== name
24123                 || node.initializer !== initializer
24124                 ? update(createJsxAttribute(name, initializer), node)
24125                 : node;
24126         }
24127         // @api
24128         function createJsxAttributes(properties) {
24129             var node = createBaseNode(281 /* JsxAttributes */);
24130             node.properties = createNodeArray(properties);
24131             node.transformFlags |=
24132                 propagateChildrenFlags(node.properties) |
24133                     2 /* ContainsJsx */;
24134             return node;
24135         }
24136         // @api
24137         function updateJsxAttributes(node, properties) {
24138             return node.properties !== properties
24139                 ? update(createJsxAttributes(properties), node)
24140                 : node;
24141         }
24142         // @api
24143         function createJsxSpreadAttribute(expression) {
24144             var node = createBaseNode(282 /* JsxSpreadAttribute */);
24145             node.expression = expression;
24146             node.transformFlags |=
24147                 propagateChildFlags(node.expression) |
24148                     2 /* ContainsJsx */;
24149             return node;
24150         }
24151         // @api
24152         function updateJsxSpreadAttribute(node, expression) {
24153             return node.expression !== expression
24154                 ? update(createJsxSpreadAttribute(expression), node)
24155                 : node;
24156         }
24157         // @api
24158         function createJsxExpression(dotDotDotToken, expression) {
24159             var node = createBaseNode(283 /* JsxExpression */);
24160             node.dotDotDotToken = dotDotDotToken;
24161             node.expression = expression;
24162             node.transformFlags |=
24163                 propagateChildFlags(node.dotDotDotToken) |
24164                     propagateChildFlags(node.expression) |
24165                     2 /* ContainsJsx */;
24166             return node;
24167         }
24168         // @api
24169         function updateJsxExpression(node, expression) {
24170             return node.expression !== expression
24171                 ? update(createJsxExpression(node.dotDotDotToken, expression), node)
24172                 : node;
24173         }
24174         //
24175         // Clauses
24176         //
24177         // @api
24178         function createCaseClause(expression, statements) {
24179             var node = createBaseNode(284 /* CaseClause */);
24180             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
24181             node.statements = createNodeArray(statements);
24182             node.transformFlags |=
24183                 propagateChildFlags(node.expression) |
24184                     propagateChildrenFlags(node.statements);
24185             return node;
24186         }
24187         // @api
24188         function updateCaseClause(node, expression, statements) {
24189             return node.expression !== expression
24190                 || node.statements !== statements
24191                 ? update(createCaseClause(expression, statements), node)
24192                 : node;
24193         }
24194         // @api
24195         function createDefaultClause(statements) {
24196             var node = createBaseNode(285 /* DefaultClause */);
24197             node.statements = createNodeArray(statements);
24198             node.transformFlags = propagateChildrenFlags(node.statements);
24199             return node;
24200         }
24201         // @api
24202         function updateDefaultClause(node, statements) {
24203             return node.statements !== statements
24204                 ? update(createDefaultClause(statements), node)
24205                 : node;
24206         }
24207         // @api
24208         function createHeritageClause(token, types) {
24209             var node = createBaseNode(286 /* HeritageClause */);
24210             node.token = token;
24211             node.types = createNodeArray(types);
24212             node.transformFlags |= propagateChildrenFlags(node.types);
24213             switch (token) {
24214                 case 93 /* ExtendsKeyword */:
24215                     node.transformFlags |= 256 /* ContainsES2015 */;
24216                     break;
24217                 case 116 /* ImplementsKeyword */:
24218                     node.transformFlags |= 1 /* ContainsTypeScript */;
24219                     break;
24220                 default:
24221                     return ts.Debug.assertNever(token);
24222             }
24223             return node;
24224         }
24225         // @api
24226         function updateHeritageClause(node, types) {
24227             return node.types !== types
24228                 ? update(createHeritageClause(node.token, types), node)
24229                 : node;
24230         }
24231         // @api
24232         function createCatchClause(variableDeclaration, block) {
24233             var node = createBaseNode(287 /* CatchClause */);
24234             variableDeclaration = !ts.isString(variableDeclaration) ? variableDeclaration : createVariableDeclaration(variableDeclaration, 
24235             /*exclamationToken*/ undefined, 
24236             /*type*/ undefined, 
24237             /*initializer*/ undefined);
24238             node.variableDeclaration = variableDeclaration;
24239             node.block = block;
24240             node.transformFlags |=
24241                 propagateChildFlags(node.variableDeclaration) |
24242                     propagateChildFlags(node.block);
24243             if (!variableDeclaration)
24244                 node.transformFlags |= 16 /* ContainsES2019 */;
24245             return node;
24246         }
24247         // @api
24248         function updateCatchClause(node, variableDeclaration, block) {
24249             return node.variableDeclaration !== variableDeclaration
24250                 || node.block !== block
24251                 ? update(createCatchClause(variableDeclaration, block), node)
24252                 : node;
24253         }
24254         //
24255         // Property assignments
24256         //
24257         // @api
24258         function createPropertyAssignment(name, initializer) {
24259             var node = createBaseNamedDeclaration(288 /* PropertyAssignment */, 
24260             /*decorators*/ undefined, 
24261             /*modifiers*/ undefined, name);
24262             node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer);
24263             node.transformFlags |=
24264                 propagateChildFlags(node.name) |
24265                     propagateChildFlags(node.initializer);
24266             return node;
24267         }
24268         function finishUpdatePropertyAssignment(updated, original) {
24269             // copy children used only for error reporting
24270             if (original.decorators)
24271                 updated.decorators = original.decorators;
24272             if (original.modifiers)
24273                 updated.modifiers = original.modifiers;
24274             if (original.questionToken)
24275                 updated.questionToken = original.questionToken;
24276             if (original.exclamationToken)
24277                 updated.exclamationToken = original.exclamationToken;
24278             return update(updated, original);
24279         }
24280         // @api
24281         function updatePropertyAssignment(node, name, initializer) {
24282             return node.name !== name
24283                 || node.initializer !== initializer
24284                 ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node)
24285                 : node;
24286         }
24287         // @api
24288         function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
24289             var node = createBaseNamedDeclaration(289 /* ShorthandPropertyAssignment */, 
24290             /*decorators*/ undefined, 
24291             /*modifiers*/ undefined, name);
24292             node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer);
24293             node.transformFlags |=
24294                 propagateChildFlags(node.objectAssignmentInitializer) |
24295                     256 /* ContainsES2015 */;
24296             return node;
24297         }
24298         function finishUpdateShorthandPropertyAssignment(updated, original) {
24299             // copy children used only for error reporting
24300             if (original.decorators)
24301                 updated.decorators = original.decorators;
24302             if (original.modifiers)
24303                 updated.modifiers = original.modifiers;
24304             if (original.equalsToken)
24305                 updated.equalsToken = original.equalsToken;
24306             if (original.questionToken)
24307                 updated.questionToken = original.questionToken;
24308             if (original.exclamationToken)
24309                 updated.exclamationToken = original.exclamationToken;
24310             return update(updated, original);
24311         }
24312         // @api
24313         function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
24314             return node.name !== name
24315                 || node.objectAssignmentInitializer !== objectAssignmentInitializer
24316                 ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
24317                 : node;
24318         }
24319         // @api
24320         function createSpreadAssignment(expression) {
24321             var node = createBaseNode(290 /* SpreadAssignment */);
24322             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
24323             node.transformFlags |=
24324                 propagateChildFlags(node.expression) |
24325                     32 /* ContainsES2018 */ |
24326                     16384 /* ContainsObjectRestOrSpread */;
24327             return node;
24328         }
24329         // @api
24330         function updateSpreadAssignment(node, expression) {
24331             return node.expression !== expression
24332                 ? update(createSpreadAssignment(expression), node)
24333                 : node;
24334         }
24335         //
24336         // Enum
24337         //
24338         // @api
24339         function createEnumMember(name, initializer) {
24340             var node = createBaseNode(291 /* EnumMember */);
24341             node.name = asName(name);
24342             node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer);
24343             node.transformFlags |=
24344                 propagateChildFlags(node.name) |
24345                     propagateChildFlags(node.initializer) |
24346                     1 /* ContainsTypeScript */;
24347             return node;
24348         }
24349         // @api
24350         function updateEnumMember(node, name, initializer) {
24351             return node.name !== name
24352                 || node.initializer !== initializer
24353                 ? update(createEnumMember(name, initializer), node)
24354                 : node;
24355         }
24356         //
24357         // Top-level nodes
24358         //
24359         // @api
24360         function createSourceFile(statements, endOfFileToken, flags) {
24361             var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */);
24362             node.statements = createNodeArray(statements);
24363             node.endOfFileToken = endOfFileToken;
24364             node.flags |= flags;
24365             node.fileName = "";
24366             node.text = "";
24367             node.languageVersion = 0;
24368             node.languageVariant = 0;
24369             node.scriptKind = 0;
24370             node.isDeclarationFile = false;
24371             node.hasNoDefaultLib = false;
24372             node.transformFlags |=
24373                 propagateChildrenFlags(node.statements) |
24374                     propagateChildFlags(node.endOfFileToken);
24375             return node;
24376         }
24377         function cloneSourceFileWithChanges(source, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
24378             var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */);
24379             for (var p in source) {
24380                 if (p === "emitNode" || ts.hasProperty(node, p) || !ts.hasProperty(source, p))
24381                     continue;
24382                 node[p] = source[p];
24383             }
24384             node.flags |= source.flags;
24385             node.statements = createNodeArray(statements);
24386             node.endOfFileToken = source.endOfFileToken;
24387             node.isDeclarationFile = isDeclarationFile;
24388             node.referencedFiles = referencedFiles;
24389             node.typeReferenceDirectives = typeReferences;
24390             node.hasNoDefaultLib = hasNoDefaultLib;
24391             node.libReferenceDirectives = libReferences;
24392             node.transformFlags =
24393                 propagateChildrenFlags(node.statements) |
24394                     propagateChildFlags(node.endOfFileToken);
24395             return node;
24396         }
24397         // @api
24398         function updateSourceFile(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives) {
24399             if (isDeclarationFile === void 0) { isDeclarationFile = node.isDeclarationFile; }
24400             if (referencedFiles === void 0) { referencedFiles = node.referencedFiles; }
24401             if (typeReferenceDirectives === void 0) { typeReferenceDirectives = node.typeReferenceDirectives; }
24402             if (hasNoDefaultLib === void 0) { hasNoDefaultLib = node.hasNoDefaultLib; }
24403             if (libReferenceDirectives === void 0) { libReferenceDirectives = node.libReferenceDirectives; }
24404             return node.statements !== statements
24405                 || node.isDeclarationFile !== isDeclarationFile
24406                 || node.referencedFiles !== referencedFiles
24407                 || node.typeReferenceDirectives !== typeReferenceDirectives
24408                 || node.hasNoDefaultLib !== hasNoDefaultLib
24409                 || node.libReferenceDirectives !== libReferenceDirectives
24410                 ? update(cloneSourceFileWithChanges(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives), node)
24411                 : node;
24412         }
24413         // @api
24414         function createBundle(sourceFiles, prepends) {
24415             if (prepends === void 0) { prepends = ts.emptyArray; }
24416             var node = createBaseNode(298 /* Bundle */);
24417             node.prepends = prepends;
24418             node.sourceFiles = sourceFiles;
24419             return node;
24420         }
24421         // @api
24422         function updateBundle(node, sourceFiles, prepends) {
24423             if (prepends === void 0) { prepends = ts.emptyArray; }
24424             return node.sourceFiles !== sourceFiles
24425                 || node.prepends !== prepends
24426                 ? update(createBundle(sourceFiles, prepends), node)
24427                 : node;
24428         }
24429         // @api
24430         function createUnparsedSource(prologues, syntheticReferences, texts) {
24431             var node = createBaseNode(299 /* UnparsedSource */);
24432             node.prologues = prologues;
24433             node.syntheticReferences = syntheticReferences;
24434             node.texts = texts;
24435             node.fileName = "";
24436             node.text = "";
24437             node.referencedFiles = ts.emptyArray;
24438             node.libReferenceDirectives = ts.emptyArray;
24439             node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
24440             return node;
24441         }
24442         function createBaseUnparsedNode(kind, data) {
24443             var node = createBaseNode(kind);
24444             node.data = data;
24445             return node;
24446         }
24447         // @api
24448         function createUnparsedPrologue(data) {
24449             return createBaseUnparsedNode(292 /* UnparsedPrologue */, data);
24450         }
24451         // @api
24452         function createUnparsedPrepend(data, texts) {
24453             var node = createBaseUnparsedNode(293 /* UnparsedPrepend */, data);
24454             node.texts = texts;
24455             return node;
24456         }
24457         // @api
24458         function createUnparsedTextLike(data, internal) {
24459             return createBaseUnparsedNode(internal ? 295 /* UnparsedInternalText */ : 294 /* UnparsedText */, data);
24460         }
24461         // @api
24462         function createUnparsedSyntheticReference(section) {
24463             var node = createBaseNode(296 /* UnparsedSyntheticReference */);
24464             node.data = section.data;
24465             node.section = section;
24466             return node;
24467         }
24468         // @api
24469         function createInputFiles() {
24470             var node = createBaseNode(300 /* InputFiles */);
24471             node.javascriptText = "";
24472             node.declarationText = "";
24473             return node;
24474         }
24475         //
24476         // Synthetic Nodes (used by checker)
24477         //
24478         // @api
24479         function createSyntheticExpression(type, isSpread, tupleNameSource) {
24480             if (isSpread === void 0) { isSpread = false; }
24481             var node = createBaseNode(227 /* SyntheticExpression */);
24482             node.type = type;
24483             node.isSpread = isSpread;
24484             node.tupleNameSource = tupleNameSource;
24485             return node;
24486         }
24487         // @api
24488         function createSyntaxList(children) {
24489             var node = createBaseNode(334 /* SyntaxList */);
24490             node._children = children;
24491             return node;
24492         }
24493         //
24494         // Transformation nodes
24495         //
24496         /**
24497          * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
24498          * order to preserve comments.
24499          *
24500          * @param original The original statement.
24501          */
24502         // @api
24503         function createNotEmittedStatement(original) {
24504             var node = createBaseNode(335 /* NotEmittedStatement */);
24505             node.original = original;
24506             ts.setTextRange(node, original);
24507             return node;
24508         }
24509         /**
24510          * Creates a synthetic expression to act as a placeholder for a not-emitted expression in
24511          * order to preserve comments or sourcemap positions.
24512          *
24513          * @param expression The inner expression to emit.
24514          * @param original The original outer expression.
24515          */
24516         // @api
24517         function createPartiallyEmittedExpression(expression, original) {
24518             var node = createBaseNode(336 /* PartiallyEmittedExpression */);
24519             node.expression = expression;
24520             node.original = original;
24521             node.transformFlags |=
24522                 propagateChildFlags(node.expression) |
24523                     1 /* ContainsTypeScript */;
24524             ts.setTextRange(node, original);
24525             return node;
24526         }
24527         // @api
24528         function updatePartiallyEmittedExpression(node, expression) {
24529             return node.expression !== expression
24530                 ? update(createPartiallyEmittedExpression(expression, node.original), node)
24531                 : node;
24532         }
24533         function flattenCommaElements(node) {
24534             if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
24535                 if (ts.isCommaListExpression(node)) {
24536                     return node.elements;
24537                 }
24538                 if (ts.isBinaryExpression(node) && ts.isCommaToken(node.operatorToken)) {
24539                     return [node.left, node.right];
24540                 }
24541             }
24542             return node;
24543         }
24544         // @api
24545         function createCommaListExpression(elements) {
24546             var node = createBaseNode(337 /* CommaListExpression */);
24547             node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
24548             node.transformFlags |= propagateChildrenFlags(node.elements);
24549             return node;
24550         }
24551         // @api
24552         function updateCommaListExpression(node, elements) {
24553             return node.elements !== elements
24554                 ? update(createCommaListExpression(elements), node)
24555                 : node;
24556         }
24557         /**
24558          * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
24559          * order to properly emit exports.
24560          */
24561         // @api
24562         function createEndOfDeclarationMarker(original) {
24563             var node = createBaseNode(339 /* EndOfDeclarationMarker */);
24564             node.emitNode = {};
24565             node.original = original;
24566             return node;
24567         }
24568         /**
24569          * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
24570          * order to properly emit exports.
24571          */
24572         // @api
24573         function createMergeDeclarationMarker(original) {
24574             var node = createBaseNode(338 /* MergeDeclarationMarker */);
24575             node.emitNode = {};
24576             node.original = original;
24577             return node;
24578         }
24579         // @api
24580         function createSyntheticReferenceExpression(expression, thisArg) {
24581             var node = createBaseNode(340 /* SyntheticReferenceExpression */);
24582             node.expression = expression;
24583             node.thisArg = thisArg;
24584             node.transformFlags |=
24585                 propagateChildFlags(node.expression) |
24586                     propagateChildFlags(node.thisArg);
24587             return node;
24588         }
24589         // @api
24590         function updateSyntheticReferenceExpression(node, expression, thisArg) {
24591             return node.expression !== expression
24592                 || node.thisArg !== thisArg
24593                 ? update(createSyntheticReferenceExpression(expression, thisArg), node)
24594                 : node;
24595         }
24596         function cloneNode(node) {
24597             // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
24598             // the original node. We also need to exclude specific properties and only include own-
24599             // properties (to skip members already defined on the shared prototype).
24600             if (node === undefined) {
24601                 return node;
24602             }
24603             var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(297 /* SourceFile */) :
24604                 ts.isIdentifier(node) ? baseFactory.createBaseIdentifierNode(78 /* Identifier */) :
24605                     ts.isPrivateIdentifier(node) ? baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */) :
24606                         !ts.isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) :
24607                             baseFactory.createBaseNode(node.kind);
24608             clone.flags |= (node.flags & ~8 /* Synthesized */);
24609             clone.transformFlags = node.transformFlags;
24610             setOriginalNode(clone, node);
24611             for (var key in node) {
24612                 if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
24613                     continue;
24614                 }
24615                 clone[key] = node[key];
24616             }
24617             return clone;
24618         }
24619         function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
24620             return createCallExpression(createFunctionExpression(
24621             /*modifiers*/ undefined, 
24622             /*asteriskToken*/ undefined, 
24623             /*name*/ undefined, 
24624             /*typeParameters*/ undefined, 
24625             /*parameters*/ param ? [param] : [], 
24626             /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), 
24627             /*typeArguments*/ undefined, 
24628             /*argumentsArray*/ paramValue ? [paramValue] : []);
24629         }
24630         function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
24631             return createCallExpression(createArrowFunction(
24632             /*modifiers*/ undefined, 
24633             /*typeParameters*/ undefined, 
24634             /*parameters*/ param ? [param] : [], 
24635             /*type*/ undefined, 
24636             /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), 
24637             /*typeArguments*/ undefined, 
24638             /*argumentsArray*/ paramValue ? [paramValue] : []);
24639         }
24640         function createVoidZero() {
24641             return createVoidExpression(createNumericLiteral("0"));
24642         }
24643         function createExportDefault(expression) {
24644             return createExportAssignment(
24645             /*decorators*/ undefined, 
24646             /*modifiers*/ undefined, 
24647             /*isExportEquals*/ false, expression);
24648         }
24649         function createExternalModuleExport(exportName) {
24650             return createExportDeclaration(
24651             /*decorators*/ undefined, 
24652             /*modifiers*/ undefined, 
24653             /*isTypeOnly*/ false, createNamedExports([
24654                 createExportSpecifier(/*propertyName*/ undefined, exportName)
24655             ]));
24656         }
24657         //
24658         // Utilities
24659         //
24660         function createTypeCheck(value, tag) {
24661             return tag === "undefined"
24662                 ? factory.createStrictEquality(value, createVoidZero())
24663                 : factory.createStrictEquality(createTypeOfExpression(value), createStringLiteral(tag));
24664         }
24665         function createMethodCall(object, methodName, argumentsList) {
24666             return createCallExpression(createPropertyAccessExpression(object, methodName), 
24667             /*typeArguments*/ undefined, argumentsList);
24668         }
24669         function createFunctionBindCall(target, thisArg, argumentsList) {
24670             return createMethodCall(target, "bind", __spreadArray([thisArg], argumentsList));
24671         }
24672         function createFunctionCallCall(target, thisArg, argumentsList) {
24673             return createMethodCall(target, "call", __spreadArray([thisArg], argumentsList));
24674         }
24675         function createFunctionApplyCall(target, thisArg, argumentsExpression) {
24676             return createMethodCall(target, "apply", [thisArg, argumentsExpression]);
24677         }
24678         function createGlobalMethodCall(globalObjectName, methodName, argumentsList) {
24679             return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList);
24680         }
24681         function createArraySliceCall(array, start) {
24682             return createMethodCall(array, "slice", start === undefined ? [] : [asExpression(start)]);
24683         }
24684         function createArrayConcatCall(array, argumentsList) {
24685             return createMethodCall(array, "concat", argumentsList);
24686         }
24687         function createObjectDefinePropertyCall(target, propertyName, attributes) {
24688             return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]);
24689         }
24690         function tryAddPropertyAssignment(properties, propertyName, expression) {
24691             if (expression) {
24692                 properties.push(createPropertyAssignment(propertyName, expression));
24693                 return true;
24694             }
24695             return false;
24696         }
24697         function createPropertyDescriptor(attributes, singleLine) {
24698             var properties = [];
24699             tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable));
24700             tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable));
24701             var isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable));
24702             isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData;
24703             var isAccessor = tryAddPropertyAssignment(properties, "get", attributes.get);
24704             isAccessor = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor;
24705             ts.Debug.assert(!(isData && isAccessor), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor.");
24706             return createObjectLiteralExpression(properties, !singleLine);
24707         }
24708         function updateOuterExpression(outerExpression, expression) {
24709             switch (outerExpression.kind) {
24710                 case 207 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression);
24711                 case 206 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression);
24712                 case 224 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type);
24713                 case 225 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression);
24714                 case 336 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression);
24715             }
24716         }
24717         /**
24718          * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions.
24719          *
24720          * A parenthesized expression can be ignored when all of the following are true:
24721          *
24722          * - It's `pos` and `end` are not -1
24723          * - It does not have a custom source map range
24724          * - It does not have a custom comment range
24725          * - It does not have synthetic leading or trailing comments
24726          *
24727          * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around
24728          * the expression to maintain precedence, a new parenthesized expression should be created automatically when
24729          * the containing expression is created/updated.
24730          */
24731         function isIgnorableParen(node) {
24732             return ts.isParenthesizedExpression(node)
24733                 && ts.nodeIsSynthesized(node)
24734                 && ts.nodeIsSynthesized(ts.getSourceMapRange(node))
24735                 && ts.nodeIsSynthesized(ts.getCommentRange(node))
24736                 && !ts.some(ts.getSyntheticLeadingComments(node))
24737                 && !ts.some(ts.getSyntheticTrailingComments(node));
24738         }
24739         function restoreOuterExpressions(outerExpression, innerExpression, kinds) {
24740             if (kinds === void 0) { kinds = 15 /* All */; }
24741             if (outerExpression && ts.isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
24742                 return updateOuterExpression(outerExpression, restoreOuterExpressions(outerExpression.expression, innerExpression));
24743             }
24744             return innerExpression;
24745         }
24746         function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
24747             if (!outermostLabeledStatement) {
24748                 return node;
24749             }
24750             var updated = updateLabeledStatement(outermostLabeledStatement, outermostLabeledStatement.label, ts.isLabeledStatement(outermostLabeledStatement.statement)
24751                 ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
24752                 : node);
24753             if (afterRestoreLabelCallback) {
24754                 afterRestoreLabelCallback(outermostLabeledStatement);
24755             }
24756             return updated;
24757         }
24758         function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
24759             var target = ts.skipParentheses(node);
24760             switch (target.kind) {
24761                 case 78 /* Identifier */:
24762                     return cacheIdentifiers;
24763                 case 107 /* ThisKeyword */:
24764                 case 8 /* NumericLiteral */:
24765                 case 9 /* BigIntLiteral */:
24766                 case 10 /* StringLiteral */:
24767                     return false;
24768                 case 199 /* ArrayLiteralExpression */:
24769                     var elements = target.elements;
24770                     if (elements.length === 0) {
24771                         return false;
24772                     }
24773                     return true;
24774                 case 200 /* ObjectLiteralExpression */:
24775                     return target.properties.length > 0;
24776                 default:
24777                     return true;
24778             }
24779         }
24780         function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
24781             if (cacheIdentifiers === void 0) { cacheIdentifiers = false; }
24782             var callee = ts.skipOuterExpressions(expression, 15 /* All */);
24783             var thisArg;
24784             var target;
24785             if (ts.isSuperProperty(callee)) {
24786                 thisArg = createThis();
24787                 target = callee;
24788             }
24789             else if (ts.isSuperKeyword(callee)) {
24790                 thisArg = createThis();
24791                 target = languageVersion !== undefined && languageVersion < 2 /* ES2015 */
24792                     ? ts.setTextRange(createIdentifier("_super"), callee)
24793                     : callee;
24794             }
24795             else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
24796                 thisArg = createVoidZero();
24797                 target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee);
24798             }
24799             else if (ts.isPropertyAccessExpression(callee)) {
24800                 if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
24801                     // for `a.b()` target is `(_a = a).b` and thisArg is `_a`
24802                     thisArg = createTempVariable(recordTempVariable);
24803                     target = createPropertyAccessExpression(ts.setTextRange(factory.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
24804                     ts.setTextRange(target, callee);
24805                 }
24806                 else {
24807                     thisArg = callee.expression;
24808                     target = callee;
24809                 }
24810             }
24811             else if (ts.isElementAccessExpression(callee)) {
24812                 if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
24813                     // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
24814                     thisArg = createTempVariable(recordTempVariable);
24815                     target = createElementAccessExpression(ts.setTextRange(factory.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
24816                     ts.setTextRange(target, callee);
24817                 }
24818                 else {
24819                     thisArg = callee.expression;
24820                     target = callee;
24821                 }
24822             }
24823             else {
24824                 // for `a()` target is `a` and thisArg is `void 0`
24825                 thisArg = createVoidZero();
24826                 target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
24827             }
24828             return { target: target, thisArg: thisArg };
24829         }
24830         function inlineExpressions(expressions) {
24831             // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call
24832             // stack size exceeded" errors.
24833             return expressions.length > 10
24834                 ? createCommaListExpression(expressions)
24835                 : ts.reduceLeft(expressions, factory.createComma);
24836         }
24837         function getName(node, allowComments, allowSourceMaps, emitFlags) {
24838             if (emitFlags === void 0) { emitFlags = 0; }
24839             var nodeName = ts.getNameOfDeclaration(node);
24840             if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) {
24841                 // TODO(rbuckton): Does this need to be parented?
24842                 var name = ts.setParent(ts.setTextRange(cloneNode(nodeName), nodeName), nodeName.parent);
24843                 emitFlags |= ts.getEmitFlags(nodeName);
24844                 if (!allowSourceMaps)
24845                     emitFlags |= 48 /* NoSourceMap */;
24846                 if (!allowComments)
24847                     emitFlags |= 1536 /* NoComments */;
24848                 if (emitFlags)
24849                     ts.setEmitFlags(name, emitFlags);
24850                 return name;
24851             }
24852             return getGeneratedNameForNode(node);
24853         }
24854         /**
24855          * Gets the internal name of a declaration. This is primarily used for declarations that can be
24856          * referred to by name in the body of an ES5 class function body. An internal name will *never*
24857          * be prefixed with an module or namespace export modifier like "exports." when emitted as an
24858          * expression. An internal name will also *never* be renamed due to a collision with a block
24859          * scoped variable.
24860          *
24861          * @param node The declaration.
24862          * @param allowComments A value indicating whether comments may be emitted for the name.
24863          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24864          */
24865         function getInternalName(node, allowComments, allowSourceMaps) {
24866             return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */);
24867         }
24868         /**
24869          * Gets the local name of a declaration. This is primarily used for declarations that can be
24870          * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
24871          * local name will *never* be prefixed with an module or namespace export modifier like
24872          * "exports." when emitted as an expression.
24873          *
24874          * @param node The declaration.
24875          * @param allowComments A value indicating whether comments may be emitted for the name.
24876          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24877          */
24878         function getLocalName(node, allowComments, allowSourceMaps) {
24879             return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
24880         }
24881         /**
24882          * Gets the export name of a declaration. This is primarily used for declarations that can be
24883          * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An
24884          * export name will *always* be prefixed with an module or namespace export modifier like
24885          * `"exports."` when emitted as an expression if the name points to an exported symbol.
24886          *
24887          * @param node The declaration.
24888          * @param allowComments A value indicating whether comments may be emitted for the name.
24889          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24890          */
24891         function getExportName(node, allowComments, allowSourceMaps) {
24892             return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
24893         }
24894         /**
24895          * Gets the name of a declaration for use in declarations.
24896          *
24897          * @param node The declaration.
24898          * @param allowComments A value indicating whether comments may be emitted for the name.
24899          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24900          */
24901         function getDeclarationName(node, allowComments, allowSourceMaps) {
24902             return getName(node, allowComments, allowSourceMaps);
24903         }
24904         /**
24905          * Gets a namespace-qualified name for use in expressions.
24906          *
24907          * @param ns The namespace identifier.
24908          * @param name The name.
24909          * @param allowComments A value indicating whether comments may be emitted for the name.
24910          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24911          */
24912         function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
24913             var qualifiedName = createPropertyAccessExpression(ns, ts.nodeIsSynthesized(name) ? name : cloneNode(name));
24914             ts.setTextRange(qualifiedName, name);
24915             var emitFlags = 0;
24916             if (!allowSourceMaps)
24917                 emitFlags |= 48 /* NoSourceMap */;
24918             if (!allowComments)
24919                 emitFlags |= 1536 /* NoComments */;
24920             if (emitFlags)
24921                 ts.setEmitFlags(qualifiedName, emitFlags);
24922             return qualifiedName;
24923         }
24924         /**
24925          * Gets the exported name of a declaration for use in expressions.
24926          *
24927          * An exported name will *always* be prefixed with an module or namespace export modifier like
24928          * "exports." if the name points to an exported symbol.
24929          *
24930          * @param ns The namespace identifier.
24931          * @param node The declaration.
24932          * @param allowComments A value indicating whether comments may be emitted for the name.
24933          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24934          */
24935         function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
24936             if (ns && ts.hasSyntacticModifier(node, 1 /* Export */)) {
24937                 return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
24938             }
24939             return getExportName(node, allowComments, allowSourceMaps);
24940         }
24941         /**
24942          * Copies any necessary standard and custom prologue-directives into target array.
24943          * @param source origin statements array
24944          * @param target result statements array
24945          * @param ensureUseStrict boolean determining whether the function need to add prologue-directives
24946          * @param visitor Optional callback used to visit any custom prologue directives.
24947          */
24948         function copyPrologue(source, target, ensureUseStrict, visitor) {
24949             var offset = copyStandardPrologue(source, target, ensureUseStrict);
24950             return copyCustomPrologue(source, target, offset, visitor);
24951         }
24952         function isUseStrictPrologue(node) {
24953             return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
24954         }
24955         function createUseStrictPrologue() {
24956             return ts.startOnNewLine(createExpressionStatement(createStringLiteral("use strict")));
24957         }
24958         /**
24959          * Copies only the standard (string-expression) prologue-directives into the target statement-array.
24960          * @param source origin statements array
24961          * @param target result statements array
24962          * @param ensureUseStrict boolean determining whether the function need to add prologue-directives
24963          */
24964         function copyStandardPrologue(source, target, ensureUseStrict) {
24965             ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
24966             var foundUseStrict = false;
24967             var statementOffset = 0;
24968             var numStatements = source.length;
24969             while (statementOffset < numStatements) {
24970                 var statement = source[statementOffset];
24971                 if (ts.isPrologueDirective(statement)) {
24972                     if (isUseStrictPrologue(statement)) {
24973                         foundUseStrict = true;
24974                     }
24975                     target.push(statement);
24976                 }
24977                 else {
24978                     break;
24979                 }
24980                 statementOffset++;
24981             }
24982             if (ensureUseStrict && !foundUseStrict) {
24983                 target.push(createUseStrictPrologue());
24984             }
24985             return statementOffset;
24986         }
24987         function copyCustomPrologue(source, target, statementOffset, visitor, filter) {
24988             if (filter === void 0) { filter = ts.returnTrue; }
24989             var numStatements = source.length;
24990             while (statementOffset !== undefined && statementOffset < numStatements) {
24991                 var statement = source[statementOffset];
24992                 if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) {
24993                     ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
24994                 }
24995                 else {
24996                     break;
24997                 }
24998                 statementOffset++;
24999             }
25000             return statementOffset;
25001         }
25002         /**
25003          * Ensures "use strict" directive is added
25004          *
25005          * @param statements An array of statements
25006          */
25007         function ensureUseStrict(statements) {
25008             var foundUseStrict = ts.findUseStrictPrologue(statements);
25009             if (!foundUseStrict) {
25010                 return ts.setTextRange(createNodeArray(__spreadArray([createUseStrictPrologue()], statements)), statements);
25011             }
25012             return statements;
25013         }
25014         /**
25015          * Lifts a NodeArray containing only Statement nodes to a block.
25016          *
25017          * @param nodes The NodeArray.
25018          */
25019         function liftToBlock(nodes) {
25020             ts.Debug.assert(ts.every(nodes, ts.isStatementOrBlock), "Cannot lift nodes to a Block.");
25021             return ts.singleOrUndefined(nodes) || createBlock(nodes);
25022         }
25023         function findSpanEnd(array, test, start) {
25024             var i = start;
25025             while (i < array.length && test(array[i])) {
25026                 i++;
25027             }
25028             return i;
25029         }
25030         function mergeLexicalEnvironment(statements, declarations) {
25031             if (!ts.some(declarations)) {
25032                 return statements;
25033             }
25034             // When we merge new lexical statements into an existing statement list, we merge them in the following manner:
25035             //
25036             // Given:
25037             //
25038             // | Left                               | Right                               |
25039             // |------------------------------------|-------------------------------------|
25040             // | [standard prologues (left)]        | [standard prologues (right)]        |
25041             // | [hoisted functions (left)]         | [hoisted functions (right)]         |
25042             // | [hoisted variables (left)]         | [hoisted variables (right)]         |
25043             // | [lexical init statements (left)]   | [lexical init statements (right)]   |
25044             // | [other statements (left)]          |                                     |
25045             //
25046             // The resulting statement list will be:
25047             //
25048             // | Result                              |
25049             // |-------------------------------------|
25050             // | [standard prologues (right)]        |
25051             // | [standard prologues (left)]         |
25052             // | [hoisted functions (right)]         |
25053             // | [hoisted functions (left)]          |
25054             // | [hoisted variables (right)]         |
25055             // | [hoisted variables (left)]          |
25056             // | [lexical init statements (right)]   |
25057             // | [lexical init statements (left)]    |
25058             // | [other statements (left)]           |
25059             //
25060             // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements,
25061             // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state.
25062             // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom
25063             var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0);
25064             var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd);
25065             var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd);
25066             // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom
25067             var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0);
25068             var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd);
25069             var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd);
25070             var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd);
25071             ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues");
25072             // splice prologues from the right into the left. We do this in reverse order
25073             // so that we don't need to recompute the index on the left when we insert items.
25074             var left = ts.isNodeArray(statements) ? statements.slice() : statements;
25075             // splice other custom prologues from right into left
25076             if (rightCustomPrologueEnd > rightHoistedVariablesEnd) {
25077                 left.splice.apply(left, __spreadArray([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd)));
25078             }
25079             // splice hoisted variables from right into left
25080             if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) {
25081                 left.splice.apply(left, __spreadArray([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd)));
25082             }
25083             // splice hoisted functions from right into left
25084             if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) {
25085                 left.splice.apply(left, __spreadArray([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd)));
25086             }
25087             // splice standard prologues from right into left (that are not already in left)
25088             if (rightStandardPrologueEnd > 0) {
25089                 if (leftStandardPrologueEnd === 0) {
25090                     left.splice.apply(left, __spreadArray([0, 0], declarations.slice(0, rightStandardPrologueEnd)));
25091                 }
25092                 else {
25093                     var leftPrologues = new ts.Map();
25094                     for (var i = 0; i < leftStandardPrologueEnd; i++) {
25095                         var leftPrologue = statements[i];
25096                         leftPrologues.set(leftPrologue.expression.text, true);
25097                     }
25098                     for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) {
25099                         var rightPrologue = declarations[i];
25100                         if (!leftPrologues.has(rightPrologue.expression.text)) {
25101                             left.unshift(rightPrologue);
25102                         }
25103                     }
25104                 }
25105             }
25106             if (ts.isNodeArray(statements)) {
25107                 return ts.setTextRange(createNodeArray(left, statements.hasTrailingComma), statements);
25108             }
25109             return statements;
25110         }
25111         function updateModifiers(node, modifiers) {
25112             var _a;
25113             if (typeof modifiers === "number") {
25114                 modifiers = createModifiersFromModifierFlags(modifiers);
25115             }
25116             return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) :
25117                 ts.isPropertySignature(node) ? updatePropertySignature(node, modifiers, node.name, node.questionToken, node.type) :
25118                     ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifiers, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) :
25119                         ts.isMethodSignature(node) ? updateMethodSignature(node, modifiers, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) :
25120                             ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) :
25121                                 ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifiers, node.parameters, node.body) :
25122                                     ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.type, node.body) :
25123                                         ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.body) :
25124                                             ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifiers, node.parameters, node.type) :
25125                                                 ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
25126                                                     ts.isArrowFunction(node) ? updateArrowFunction(node, modifiers, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) :
25127                                                         ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
25128                                                             ts.isVariableStatement(node) ? updateVariableStatement(node, modifiers, node.declarationList) :
25129                                                                 ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
25130                                                                     ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
25131                                                                         ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
25132                                                                             ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.type) :
25133                                                                                 ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifiers, node.name, node.members) :
25134                                                                                     ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifiers, node.name, node.body) :
25135                                                                                         ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.name, node.moduleReference) :
25136                                                                                             ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifiers, node.importClause, node.moduleSpecifier) :
25137                                                                                                 ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifiers, node.expression) :
25138                                                                                                     ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.exportClause, node.moduleSpecifier) :
25139                                                                                                         ts.Debug.assertNever(node);
25140         }
25141         function asNodeArray(array) {
25142             return array ? createNodeArray(array) : undefined;
25143         }
25144         function asName(name) {
25145             return typeof name === "string" ? createIdentifier(name) :
25146                 name;
25147         }
25148         function asExpression(value) {
25149             return typeof value === "string" ? createStringLiteral(value) :
25150                 typeof value === "number" ? createNumericLiteral(value) :
25151                     typeof value === "boolean" ? value ? createTrue() : createFalse() :
25152                         value;
25153         }
25154         function asToken(value) {
25155             return typeof value === "number" ? createToken(value) : value;
25156         }
25157         function asEmbeddedStatement(statement) {
25158             return statement && ts.isNotEmittedStatement(statement) ? ts.setTextRange(setOriginalNode(createEmptyStatement(), statement), statement) : statement;
25159         }
25160     }
25161     ts.createNodeFactory = createNodeFactory;
25162     function updateWithoutOriginal(updated, original) {
25163         if (updated !== original) {
25164             ts.setTextRange(updated, original);
25165         }
25166         return updated;
25167     }
25168     function updateWithOriginal(updated, original) {
25169         if (updated !== original) {
25170             setOriginalNode(updated, original);
25171             ts.setTextRange(updated, original);
25172         }
25173         return updated;
25174     }
25175     function getDefaultTagNameForKind(kind) {
25176         switch (kind) {
25177             case 329 /* JSDocTypeTag */: return "type";
25178             case 327 /* JSDocReturnTag */: return "returns";
25179             case 328 /* JSDocThisTag */: return "this";
25180             case 325 /* JSDocEnumTag */: return "enum";
25181             case 317 /* JSDocAuthorTag */: return "author";
25182             case 319 /* JSDocClassTag */: return "class";
25183             case 320 /* JSDocPublicTag */: return "public";
25184             case 321 /* JSDocPrivateTag */: return "private";
25185             case 322 /* JSDocProtectedTag */: return "protected";
25186             case 323 /* JSDocReadonlyTag */: return "readonly";
25187             case 330 /* JSDocTemplateTag */: return "template";
25188             case 331 /* JSDocTypedefTag */: return "typedef";
25189             case 326 /* JSDocParameterTag */: return "param";
25190             case 333 /* JSDocPropertyTag */: return "prop";
25191             case 324 /* JSDocCallbackTag */: return "callback";
25192             case 315 /* JSDocAugmentsTag */: return "augments";
25193             case 316 /* JSDocImplementsTag */: return "implements";
25194             default:
25195                 return ts.Debug.fail("Unsupported kind: " + ts.Debug.formatSyntaxKind(kind));
25196         }
25197     }
25198     var rawTextScanner;
25199     var invalidValueSentinel = {};
25200     function getCookedText(kind, rawText) {
25201         if (!rawTextScanner) {
25202             rawTextScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
25203         }
25204         switch (kind) {
25205             case 14 /* NoSubstitutionTemplateLiteral */:
25206                 rawTextScanner.setText("`" + rawText + "`");
25207                 break;
25208             case 15 /* TemplateHead */:
25209                 // tslint:disable-next-line no-invalid-template-strings
25210                 rawTextScanner.setText("`" + rawText + "${");
25211                 break;
25212             case 16 /* TemplateMiddle */:
25213                 // tslint:disable-next-line no-invalid-template-strings
25214                 rawTextScanner.setText("}" + rawText + "${");
25215                 break;
25216             case 17 /* TemplateTail */:
25217                 rawTextScanner.setText("}" + rawText + "`");
25218                 break;
25219         }
25220         var token = rawTextScanner.scan();
25221         if (token === 23 /* CloseBracketToken */) {
25222             token = rawTextScanner.reScanTemplateToken(/*isTaggedTemplate*/ false);
25223         }
25224         if (rawTextScanner.isUnterminated()) {
25225             rawTextScanner.setText(undefined);
25226             return invalidValueSentinel;
25227         }
25228         var tokenValue;
25229         switch (token) {
25230             case 14 /* NoSubstitutionTemplateLiteral */:
25231             case 15 /* TemplateHead */:
25232             case 16 /* TemplateMiddle */:
25233             case 17 /* TemplateTail */:
25234                 tokenValue = rawTextScanner.getTokenValue();
25235                 break;
25236         }
25237         if (tokenValue === undefined || rawTextScanner.scan() !== 1 /* EndOfFileToken */) {
25238             rawTextScanner.setText(undefined);
25239             return invalidValueSentinel;
25240         }
25241         rawTextScanner.setText(undefined);
25242         return tokenValue;
25243     }
25244     function propagateIdentifierNameFlags(node) {
25245         // An IdentifierName is allowed to be `await`
25246         return propagateChildFlags(node) & ~8388608 /* ContainsPossibleTopLevelAwait */;
25247     }
25248     function propagatePropertyNameFlagsOfChild(node, transformFlags) {
25249         return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */);
25250     }
25251     function propagateChildFlags(child) {
25252         if (!child)
25253             return 0 /* None */;
25254         var childFlags = child.transformFlags & ~getTransformFlagsSubtreeExclusions(child.kind);
25255         return ts.isNamedDeclaration(child) && ts.isPropertyName(child.name) ? propagatePropertyNameFlagsOfChild(child.name, childFlags) : childFlags;
25256     }
25257     function propagateChildrenFlags(children) {
25258         return children ? children.transformFlags : 0 /* None */;
25259     }
25260     function aggregateChildrenFlags(children) {
25261         var subtreeFlags = 0 /* None */;
25262         for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
25263             var child = children_2[_i];
25264             subtreeFlags |= propagateChildFlags(child);
25265         }
25266         children.transformFlags = subtreeFlags;
25267     }
25268     /**
25269      * Gets the transform flags to exclude when unioning the transform flags of a subtree.
25270      */
25271     /* @internal */
25272     function getTransformFlagsSubtreeExclusions(kind) {
25273         if (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */) {
25274             return -2 /* TypeExcludes */;
25275         }
25276         switch (kind) {
25277             case 203 /* CallExpression */:
25278             case 204 /* NewExpression */:
25279             case 199 /* ArrayLiteralExpression */:
25280                 return 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
25281             case 256 /* ModuleDeclaration */:
25282                 return 546379776 /* ModuleExcludes */;
25283             case 160 /* Parameter */:
25284                 return 536870912 /* ParameterExcludes */;
25285             case 209 /* ArrowFunction */:
25286                 return 547309568 /* ArrowFunctionExcludes */;
25287             case 208 /* FunctionExpression */:
25288             case 251 /* FunctionDeclaration */:
25289                 return 547313664 /* FunctionExcludes */;
25290             case 250 /* VariableDeclarationList */:
25291                 return 537018368 /* VariableDeclarationListExcludes */;
25292             case 252 /* ClassDeclaration */:
25293             case 221 /* ClassExpression */:
25294                 return 536905728 /* ClassExcludes */;
25295             case 166 /* Constructor */:
25296                 return 547311616 /* ConstructorExcludes */;
25297             case 163 /* PropertyDeclaration */:
25298                 return 536875008 /* PropertyExcludes */;
25299             case 165 /* MethodDeclaration */:
25300             case 167 /* GetAccessor */:
25301             case 168 /* SetAccessor */:
25302                 return 538923008 /* MethodOrAccessorExcludes */;
25303             case 128 /* AnyKeyword */:
25304             case 144 /* NumberKeyword */:
25305             case 155 /* BigIntKeyword */:
25306             case 141 /* NeverKeyword */:
25307             case 147 /* StringKeyword */:
25308             case 145 /* ObjectKeyword */:
25309             case 131 /* BooleanKeyword */:
25310             case 148 /* SymbolKeyword */:
25311             case 113 /* VoidKeyword */:
25312             case 159 /* TypeParameter */:
25313             case 162 /* PropertySignature */:
25314             case 164 /* MethodSignature */:
25315             case 169 /* CallSignature */:
25316             case 170 /* ConstructSignature */:
25317             case 171 /* IndexSignature */:
25318             case 253 /* InterfaceDeclaration */:
25319             case 254 /* TypeAliasDeclaration */:
25320                 return -2 /* TypeExcludes */;
25321             case 200 /* ObjectLiteralExpression */:
25322                 return 536922112 /* ObjectLiteralExcludes */;
25323             case 287 /* CatchClause */:
25324                 return 536887296 /* CatchClauseExcludes */;
25325             case 196 /* ObjectBindingPattern */:
25326             case 197 /* ArrayBindingPattern */:
25327                 return 536879104 /* BindingPatternExcludes */;
25328             case 206 /* TypeAssertionExpression */:
25329             case 224 /* AsExpression */:
25330             case 336 /* PartiallyEmittedExpression */:
25331             case 207 /* ParenthesizedExpression */:
25332             case 105 /* SuperKeyword */:
25333                 return 536870912 /* OuterExpressionExcludes */;
25334             case 201 /* PropertyAccessExpression */:
25335             case 202 /* ElementAccessExpression */:
25336                 return 536870912 /* PropertyAccessExcludes */;
25337             default:
25338                 return 536870912 /* NodeExcludes */;
25339         }
25340     }
25341     ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
25342     var baseFactory = ts.createBaseNodeFactory();
25343     function makeSynthetic(node) {
25344         node.flags |= 8 /* Synthesized */;
25345         return node;
25346     }
25347     var syntheticFactory = {
25348         createBaseSourceFileNode: function (kind) { return makeSynthetic(baseFactory.createBaseSourceFileNode(kind)); },
25349         createBaseIdentifierNode: function (kind) { return makeSynthetic(baseFactory.createBaseIdentifierNode(kind)); },
25350         createBasePrivateIdentifierNode: function (kind) { return makeSynthetic(baseFactory.createBasePrivateIdentifierNode(kind)); },
25351         createBaseTokenNode: function (kind) { return makeSynthetic(baseFactory.createBaseTokenNode(kind)); },
25352         createBaseNode: function (kind) { return makeSynthetic(baseFactory.createBaseNode(kind)); },
25353     };
25354     ts.factory = createNodeFactory(4 /* NoIndentationOnFreshPropertyAccess */, syntheticFactory);
25355     function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
25356         var stripInternal;
25357         var bundleFileInfo;
25358         var fileName;
25359         var text;
25360         var length;
25361         var sourceMapPath;
25362         var sourceMapText;
25363         var getText;
25364         var getSourceMapText;
25365         var oldFileOfCurrentEmit;
25366         if (!ts.isString(textOrInputFiles)) {
25367             ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
25368             fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
25369             sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
25370             getText = function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; };
25371             getSourceMapText = function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; };
25372             length = function () { return getText().length; };
25373             if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
25374                 ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
25375                 stripInternal = mapTextOrStripInternal;
25376                 bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
25377                 oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
25378             }
25379         }
25380         else {
25381             fileName = "";
25382             text = textOrInputFiles;
25383             length = textOrInputFiles.length;
25384             sourceMapPath = mapPathOrType;
25385             sourceMapText = mapTextOrStripInternal;
25386         }
25387         var node = oldFileOfCurrentEmit ?
25388             parseOldFileOfCurrentEmit(ts.Debug.assertDefined(bundleFileInfo)) :
25389             parseUnparsedSourceFile(bundleFileInfo, stripInternal, length);
25390         node.fileName = fileName;
25391         node.sourceMapPath = sourceMapPath;
25392         node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
25393         if (getText && getSourceMapText) {
25394             Object.defineProperty(node, "text", { get: getText });
25395             Object.defineProperty(node, "sourceMapText", { get: getSourceMapText });
25396         }
25397         else {
25398             ts.Debug.assert(!oldFileOfCurrentEmit);
25399             node.text = text !== null && text !== void 0 ? text : "";
25400             node.sourceMapText = sourceMapText;
25401         }
25402         return node;
25403     }
25404     ts.createUnparsedSourceFile = createUnparsedSourceFile;
25405     function parseUnparsedSourceFile(bundleFileInfo, stripInternal, length) {
25406         var prologues;
25407         var helpers;
25408         var referencedFiles;
25409         var typeReferenceDirectives;
25410         var libReferenceDirectives;
25411         var prependChildren;
25412         var texts;
25413         var hasNoDefaultLib;
25414         for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
25415             var section = _a[_i];
25416             switch (section.kind) {
25417                 case "prologue" /* Prologue */:
25418                     prologues = ts.append(prologues, ts.setTextRange(ts.factory.createUnparsedPrologue(section.data), section));
25419                     break;
25420                 case "emitHelpers" /* EmitHelpers */:
25421                     helpers = ts.append(helpers, ts.getAllUnscopedEmitHelpers().get(section.data));
25422                     break;
25423                 case "no-default-lib" /* NoDefaultLib */:
25424                     hasNoDefaultLib = true;
25425                     break;
25426                 case "reference" /* Reference */:
25427                     referencedFiles = ts.append(referencedFiles, { pos: -1, end: -1, fileName: section.data });
25428                     break;
25429                 case "type" /* Type */:
25430                     typeReferenceDirectives = ts.append(typeReferenceDirectives, section.data);
25431                     break;
25432                 case "lib" /* Lib */:
25433                     libReferenceDirectives = ts.append(libReferenceDirectives, { pos: -1, end: -1, fileName: section.data });
25434                     break;
25435                 case "prepend" /* Prepend */:
25436                     var prependTexts = void 0;
25437                     for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
25438                         var text = _c[_b];
25439                         if (!stripInternal || text.kind !== "internal" /* Internal */) {
25440                             prependTexts = ts.append(prependTexts, ts.setTextRange(ts.factory.createUnparsedTextLike(text.data, text.kind === "internal" /* Internal */), text));
25441                         }
25442                     }
25443                     prependChildren = ts.addRange(prependChildren, prependTexts);
25444                     texts = ts.append(texts, ts.factory.createUnparsedPrepend(section.data, prependTexts !== null && prependTexts !== void 0 ? prependTexts : ts.emptyArray));
25445                     break;
25446                 case "internal" /* Internal */:
25447                     if (stripInternal) {
25448                         if (!texts)
25449                             texts = [];
25450                         break;
25451                     }
25452                 // falls through
25453                 case "text" /* Text */:
25454                     texts = ts.append(texts, ts.setTextRange(ts.factory.createUnparsedTextLike(section.data, section.kind === "internal" /* Internal */), section));
25455                     break;
25456                 default:
25457                     ts.Debug.assertNever(section);
25458             }
25459         }
25460         if (!texts) {
25461             var textNode = ts.factory.createUnparsedTextLike(/*data*/ undefined, /*internal*/ false);
25462             ts.setTextRangePosWidth(textNode, 0, typeof length === "function" ? length() : length);
25463             texts = [textNode];
25464         }
25465         var node = ts.parseNodeFactory.createUnparsedSource(prologues !== null && prologues !== void 0 ? prologues : ts.emptyArray, /*syntheticReferences*/ undefined, texts);
25466         ts.setEachParent(prologues, node);
25467         ts.setEachParent(texts, node);
25468         ts.setEachParent(prependChildren, node);
25469         node.hasNoDefaultLib = hasNoDefaultLib;
25470         node.helpers = helpers;
25471         node.referencedFiles = referencedFiles || ts.emptyArray;
25472         node.typeReferenceDirectives = typeReferenceDirectives;
25473         node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
25474         return node;
25475     }
25476     function parseOldFileOfCurrentEmit(bundleFileInfo) {
25477         var texts;
25478         var syntheticReferences;
25479         for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
25480             var section = _a[_i];
25481             switch (section.kind) {
25482                 case "internal" /* Internal */:
25483                 case "text" /* Text */:
25484                     texts = ts.append(texts, ts.setTextRange(ts.factory.createUnparsedTextLike(section.data, section.kind === "internal" /* Internal */), section));
25485                     break;
25486                 case "no-default-lib" /* NoDefaultLib */:
25487                 case "reference" /* Reference */:
25488                 case "type" /* Type */:
25489                 case "lib" /* Lib */:
25490                     syntheticReferences = ts.append(syntheticReferences, ts.setTextRange(ts.factory.createUnparsedSyntheticReference(section), section));
25491                     break;
25492                 // Ignore
25493                 case "prologue" /* Prologue */:
25494                 case "emitHelpers" /* EmitHelpers */:
25495                 case "prepend" /* Prepend */:
25496                     break;
25497                 default:
25498                     ts.Debug.assertNever(section);
25499             }
25500         }
25501         var node = ts.factory.createUnparsedSource(ts.emptyArray, syntheticReferences, texts !== null && texts !== void 0 ? texts : ts.emptyArray);
25502         ts.setEachParent(syntheticReferences, node);
25503         ts.setEachParent(texts, node);
25504         node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return ts.getAllUnscopedEmitHelpers().get(name); });
25505         return node;
25506     }
25507     function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
25508         var node = ts.parseNodeFactory.createInputFiles();
25509         if (!ts.isString(javascriptTextOrReadFileText)) {
25510             var cache_1 = new ts.Map();
25511             var textGetter_1 = function (path) {
25512                 if (path === undefined)
25513                     return undefined;
25514                 var value = cache_1.get(path);
25515                 if (value === undefined) {
25516                     value = javascriptTextOrReadFileText(path);
25517                     cache_1.set(path, value !== undefined ? value : false);
25518                 }
25519                 return value !== false ? value : undefined;
25520             };
25521             var definedTextGetter_1 = function (path) {
25522                 var result = textGetter_1(path);
25523                 return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
25524             };
25525             var buildInfo_1;
25526             var getAndCacheBuildInfo_1 = function (getText) {
25527                 if (buildInfo_1 === undefined) {
25528                     var result = getText();
25529                     buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
25530                 }
25531                 return buildInfo_1 || undefined;
25532             };
25533             node.javascriptPath = declarationTextOrJavascriptPath;
25534             node.javascriptMapPath = javascriptMapPath;
25535             node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
25536             node.declarationMapPath = declarationMapPath;
25537             node.buildInfoPath = declarationMapTextOrBuildInfoPath;
25538             Object.defineProperties(node, {
25539                 javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
25540                 javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
25541                 declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
25542                 declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
25543                 buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
25544             });
25545         }
25546         else {
25547             node.javascriptText = javascriptTextOrReadFileText;
25548             node.javascriptMapPath = javascriptMapPath;
25549             node.javascriptMapText = javascriptMapTextOrDeclarationPath;
25550             node.declarationText = declarationTextOrJavascriptPath;
25551             node.declarationMapPath = declarationMapPath;
25552             node.declarationMapText = declarationMapTextOrBuildInfoPath;
25553             node.javascriptPath = javascriptPath;
25554             node.declarationPath = declarationPath;
25555             node.buildInfoPath = buildInfoPath;
25556             node.buildInfo = buildInfo;
25557             node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
25558         }
25559         return node;
25560     }
25561     ts.createInputFiles = createInputFiles;
25562     // tslint:disable-next-line variable-name
25563     var SourceMapSource;
25564     /**
25565      * Create an external source map source file reference
25566      */
25567     function createSourceMapSource(fileName, text, skipTrivia) {
25568         return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia);
25569     }
25570     ts.createSourceMapSource = createSourceMapSource;
25571     // Utilities
25572     function setOriginalNode(node, original) {
25573         node.original = original;
25574         if (original) {
25575             var emitNode = original.emitNode;
25576             if (emitNode)
25577                 node.emitNode = mergeEmitNode(emitNode, node.emitNode);
25578         }
25579         return node;
25580     }
25581     ts.setOriginalNode = setOriginalNode;
25582     function mergeEmitNode(sourceEmitNode, destEmitNode) {
25583         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;
25584         if (!destEmitNode)
25585             destEmitNode = {};
25586         // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
25587         if (leadingComments)
25588             destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
25589         if (trailingComments)
25590             destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
25591         if (flags)
25592             destEmitNode.flags = flags;
25593         if (commentRange)
25594             destEmitNode.commentRange = commentRange;
25595         if (sourceMapRange)
25596             destEmitNode.sourceMapRange = sourceMapRange;
25597         if (tokenSourceMapRanges)
25598             destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
25599         if (constantValue !== undefined)
25600             destEmitNode.constantValue = constantValue;
25601         if (helpers) {
25602             for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
25603                 var helper = helpers_1[_i];
25604                 destEmitNode.helpers = ts.appendIfUnique(destEmitNode.helpers, helper);
25605             }
25606         }
25607         if (startsOnNewLine !== undefined)
25608             destEmitNode.startsOnNewLine = startsOnNewLine;
25609         return destEmitNode;
25610     }
25611     function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
25612         if (!destRanges)
25613             destRanges = [];
25614         for (var key in sourceRanges) {
25615             destRanges[key] = sourceRanges[key];
25616         }
25617         return destRanges;
25618     }
25619 })(ts || (ts = {}));
25620 var ts;
25621 (function (ts) {
25622     /**
25623      * Associates a node with the current transformation, initializing
25624      * various transient transformation properties.
25625      * @internal
25626      */
25627     function getOrCreateEmitNode(node) {
25628         var _a;
25629         if (!node.emitNode) {
25630             if (ts.isParseTreeNode(node)) {
25631                 // To avoid holding onto transformation artifacts, we keep track of any
25632                 // parse tree node we are annotating. This allows us to clean them up after
25633                 // all transformations have completed.
25634                 if (node.kind === 297 /* SourceFile */) {
25635                     return node.emitNode = { annotatedNodes: [node] };
25636                 }
25637                 var sourceFile = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)))) !== null && _a !== void 0 ? _a : ts.Debug.fail("Could not determine parsed source file.");
25638                 getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
25639             }
25640             node.emitNode = {};
25641         }
25642         return node.emitNode;
25643     }
25644     ts.getOrCreateEmitNode = getOrCreateEmitNode;
25645     /**
25646      * Clears any `EmitNode` entries from parse-tree nodes.
25647      * @param sourceFile A source file.
25648      */
25649     function disposeEmitNodes(sourceFile) {
25650         var _a, _b;
25651         // During transformation we may need to annotate a parse tree node with transient
25652         // transformation properties. As parse tree nodes live longer than transformation
25653         // nodes, we need to make sure we reclaim any memory allocated for custom ranges
25654         // from these nodes to ensure we do not hold onto entire subtrees just for position
25655         // information. We also need to reset these nodes to a pre-transformation state
25656         // for incremental parsing scenarios so that we do not impact later emit.
25657         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;
25658         if (annotatedNodes) {
25659             for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
25660                 var node = annotatedNodes_1[_i];
25661                 node.emitNode = undefined;
25662             }
25663         }
25664     }
25665     ts.disposeEmitNodes = disposeEmitNodes;
25666     /**
25667      * Sets `EmitFlags.NoComments` on a node and removes any leading and trailing synthetic comments.
25668      * @internal
25669      */
25670     function removeAllComments(node) {
25671         var emitNode = getOrCreateEmitNode(node);
25672         emitNode.flags |= 1536 /* NoComments */;
25673         emitNode.leadingComments = undefined;
25674         emitNode.trailingComments = undefined;
25675         return node;
25676     }
25677     ts.removeAllComments = removeAllComments;
25678     /**
25679      * Sets flags that control emit behavior of a node.
25680      */
25681     function setEmitFlags(node, emitFlags) {
25682         getOrCreateEmitNode(node).flags = emitFlags;
25683         return node;
25684     }
25685     ts.setEmitFlags = setEmitFlags;
25686     /**
25687      * Sets flags that control emit behavior of a node.
25688      */
25689     /* @internal */
25690     function addEmitFlags(node, emitFlags) {
25691         var emitNode = getOrCreateEmitNode(node);
25692         emitNode.flags = emitNode.flags | emitFlags;
25693         return node;
25694     }
25695     ts.addEmitFlags = addEmitFlags;
25696     /**
25697      * Gets a custom text range to use when emitting source maps.
25698      */
25699     function getSourceMapRange(node) {
25700         var _a, _b;
25701         return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.sourceMapRange) !== null && _b !== void 0 ? _b : node;
25702     }
25703     ts.getSourceMapRange = getSourceMapRange;
25704     /**
25705      * Sets a custom text range to use when emitting source maps.
25706      */
25707     function setSourceMapRange(node, range) {
25708         getOrCreateEmitNode(node).sourceMapRange = range;
25709         return node;
25710     }
25711     ts.setSourceMapRange = setSourceMapRange;
25712     /**
25713      * Gets the TextRange to use for source maps for a token of a node.
25714      */
25715     function getTokenSourceMapRange(node, token) {
25716         var _a, _b;
25717         return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.tokenSourceMapRanges) === null || _b === void 0 ? void 0 : _b[token];
25718     }
25719     ts.getTokenSourceMapRange = getTokenSourceMapRange;
25720     /**
25721      * Sets the TextRange to use for source maps for a token of a node.
25722      */
25723     function setTokenSourceMapRange(node, token, range) {
25724         var _a;
25725         var emitNode = getOrCreateEmitNode(node);
25726         var tokenSourceMapRanges = (_a = emitNode.tokenSourceMapRanges) !== null && _a !== void 0 ? _a : (emitNode.tokenSourceMapRanges = []);
25727         tokenSourceMapRanges[token] = range;
25728         return node;
25729     }
25730     ts.setTokenSourceMapRange = setTokenSourceMapRange;
25731     /**
25732      * Gets a custom text range to use when emitting comments.
25733      */
25734     /*@internal*/
25735     function getStartsOnNewLine(node) {
25736         var _a;
25737         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.startsOnNewLine;
25738     }
25739     ts.getStartsOnNewLine = getStartsOnNewLine;
25740     /**
25741      * Sets a custom text range to use when emitting comments.
25742      */
25743     /*@internal*/
25744     function setStartsOnNewLine(node, newLine) {
25745         getOrCreateEmitNode(node).startsOnNewLine = newLine;
25746         return node;
25747     }
25748     ts.setStartsOnNewLine = setStartsOnNewLine;
25749     /**
25750      * Gets a custom text range to use when emitting comments.
25751      */
25752     function getCommentRange(node) {
25753         var _a, _b;
25754         return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.commentRange) !== null && _b !== void 0 ? _b : node;
25755     }
25756     ts.getCommentRange = getCommentRange;
25757     /**
25758      * Sets a custom text range to use when emitting comments.
25759      */
25760     function setCommentRange(node, range) {
25761         getOrCreateEmitNode(node).commentRange = range;
25762         return node;
25763     }
25764     ts.setCommentRange = setCommentRange;
25765     function getSyntheticLeadingComments(node) {
25766         var _a;
25767         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.leadingComments;
25768     }
25769     ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
25770     function setSyntheticLeadingComments(node, comments) {
25771         getOrCreateEmitNode(node).leadingComments = comments;
25772         return node;
25773     }
25774     ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
25775     function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
25776         return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
25777     }
25778     ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
25779     function getSyntheticTrailingComments(node) {
25780         var _a;
25781         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.trailingComments;
25782     }
25783     ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
25784     function setSyntheticTrailingComments(node, comments) {
25785         getOrCreateEmitNode(node).trailingComments = comments;
25786         return node;
25787     }
25788     ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
25789     function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
25790         return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
25791     }
25792     ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
25793     function moveSyntheticComments(node, original) {
25794         setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
25795         setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
25796         var emit = getOrCreateEmitNode(original);
25797         emit.leadingComments = undefined;
25798         emit.trailingComments = undefined;
25799         return node;
25800     }
25801     ts.moveSyntheticComments = moveSyntheticComments;
25802     /**
25803      * Gets the constant value to emit for an expression representing an enum.
25804      */
25805     function getConstantValue(node) {
25806         var _a;
25807         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.constantValue;
25808     }
25809     ts.getConstantValue = getConstantValue;
25810     /**
25811      * Sets the constant value to emit for an expression.
25812      */
25813     function setConstantValue(node, value) {
25814         var emitNode = getOrCreateEmitNode(node);
25815         emitNode.constantValue = value;
25816         return node;
25817     }
25818     ts.setConstantValue = setConstantValue;
25819     /**
25820      * Adds an EmitHelper to a node.
25821      */
25822     function addEmitHelper(node, helper) {
25823         var emitNode = getOrCreateEmitNode(node);
25824         emitNode.helpers = ts.append(emitNode.helpers, helper);
25825         return node;
25826     }
25827     ts.addEmitHelper = addEmitHelper;
25828     /**
25829      * Add EmitHelpers to a node.
25830      */
25831     function addEmitHelpers(node, helpers) {
25832         if (ts.some(helpers)) {
25833             var emitNode = getOrCreateEmitNode(node);
25834             for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
25835                 var helper = helpers_2[_i];
25836                 emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper);
25837             }
25838         }
25839         return node;
25840     }
25841     ts.addEmitHelpers = addEmitHelpers;
25842     /**
25843      * Removes an EmitHelper from a node.
25844      */
25845     function removeEmitHelper(node, helper) {
25846         var _a;
25847         var helpers = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.helpers;
25848         if (helpers) {
25849             return ts.orderedRemoveItem(helpers, helper);
25850         }
25851         return false;
25852     }
25853     ts.removeEmitHelper = removeEmitHelper;
25854     /**
25855      * Gets the EmitHelpers of a node.
25856      */
25857     function getEmitHelpers(node) {
25858         var _a;
25859         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.helpers;
25860     }
25861     ts.getEmitHelpers = getEmitHelpers;
25862     /**
25863      * Moves matching emit helpers from a source node to a target node.
25864      */
25865     function moveEmitHelpers(source, target, predicate) {
25866         var sourceEmitNode = source.emitNode;
25867         var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
25868         if (!ts.some(sourceEmitHelpers))
25869             return;
25870         var targetEmitNode = getOrCreateEmitNode(target);
25871         var helpersRemoved = 0;
25872         for (var i = 0; i < sourceEmitHelpers.length; i++) {
25873             var helper = sourceEmitHelpers[i];
25874             if (predicate(helper)) {
25875                 helpersRemoved++;
25876                 targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper);
25877             }
25878             else if (helpersRemoved > 0) {
25879                 sourceEmitHelpers[i - helpersRemoved] = helper;
25880             }
25881         }
25882         if (helpersRemoved > 0) {
25883             sourceEmitHelpers.length -= helpersRemoved;
25884         }
25885     }
25886     ts.moveEmitHelpers = moveEmitHelpers;
25887     /* @internal */
25888     function ignoreSourceNewlines(node) {
25889         getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */;
25890         return node;
25891     }
25892     ts.ignoreSourceNewlines = ignoreSourceNewlines;
25893 })(ts || (ts = {}));
25894 /* @internal */
25895 var ts;
25896 (function (ts) {
25897     function createEmitHelperFactory(context) {
25898         var factory = context.factory;
25899         return {
25900             getUnscopedHelperName: getUnscopedHelperName,
25901             // TypeScript Helpers
25902             createDecorateHelper: createDecorateHelper,
25903             createMetadataHelper: createMetadataHelper,
25904             createParamHelper: createParamHelper,
25905             // ES2018 Helpers
25906             createAssignHelper: createAssignHelper,
25907             createAwaitHelper: createAwaitHelper,
25908             createAsyncGeneratorHelper: createAsyncGeneratorHelper,
25909             createAsyncDelegatorHelper: createAsyncDelegatorHelper,
25910             createAsyncValuesHelper: createAsyncValuesHelper,
25911             // ES2018 Destructuring Helpers
25912             createRestHelper: createRestHelper,
25913             // ES2017 Helpers
25914             createAwaiterHelper: createAwaiterHelper,
25915             // ES2015 Helpers
25916             createExtendsHelper: createExtendsHelper,
25917             createTemplateObjectHelper: createTemplateObjectHelper,
25918             createSpreadArrayHelper: createSpreadArrayHelper,
25919             // ES2015 Destructuring Helpers
25920             createValuesHelper: createValuesHelper,
25921             createReadHelper: createReadHelper,
25922             // ES2015 Generator Helpers
25923             createGeneratorHelper: createGeneratorHelper,
25924             // ES Module Helpers
25925             createCreateBindingHelper: createCreateBindingHelper,
25926             createImportStarHelper: createImportStarHelper,
25927             createImportStarCallbackHelper: createImportStarCallbackHelper,
25928             createImportDefaultHelper: createImportDefaultHelper,
25929             createExportStarHelper: createExportStarHelper,
25930             // Class Fields Helpers
25931             createClassPrivateFieldGetHelper: createClassPrivateFieldGetHelper,
25932             createClassPrivateFieldSetHelper: createClassPrivateFieldSetHelper,
25933         };
25934         /**
25935          * Gets an identifier for the name of an *unscoped* emit helper.
25936          */
25937         function getUnscopedHelperName(name) {
25938             return ts.setEmitFlags(factory.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
25939         }
25940         // TypeScript Helpers
25941         function createDecorateHelper(decoratorExpressions, target, memberName, descriptor) {
25942             context.requestEmitHelper(ts.decorateHelper);
25943             var argumentsArray = [];
25944             argumentsArray.push(factory.createArrayLiteralExpression(decoratorExpressions, /*multiLine*/ true));
25945             argumentsArray.push(target);
25946             if (memberName) {
25947                 argumentsArray.push(memberName);
25948                 if (descriptor) {
25949                     argumentsArray.push(descriptor);
25950                 }
25951             }
25952             return factory.createCallExpression(getUnscopedHelperName("__decorate"), 
25953             /*typeArguments*/ undefined, argumentsArray);
25954         }
25955         function createMetadataHelper(metadataKey, metadataValue) {
25956             context.requestEmitHelper(ts.metadataHelper);
25957             return factory.createCallExpression(getUnscopedHelperName("__metadata"), 
25958             /*typeArguments*/ undefined, [
25959                 factory.createStringLiteral(metadataKey),
25960                 metadataValue
25961             ]);
25962         }
25963         function createParamHelper(expression, parameterOffset, location) {
25964             context.requestEmitHelper(ts.paramHelper);
25965             return ts.setTextRange(factory.createCallExpression(getUnscopedHelperName("__param"), 
25966             /*typeArguments*/ undefined, [
25967                 factory.createNumericLiteral(parameterOffset + ""),
25968                 expression
25969             ]), location);
25970         }
25971         // ES2018 Helpers
25972         function createAssignHelper(attributesSegments) {
25973             if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
25974                 return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "assign"), 
25975                 /*typeArguments*/ undefined, attributesSegments);
25976             }
25977             context.requestEmitHelper(ts.assignHelper);
25978             return factory.createCallExpression(getUnscopedHelperName("__assign"), 
25979             /*typeArguments*/ undefined, attributesSegments);
25980         }
25981         function createAwaitHelper(expression) {
25982             context.requestEmitHelper(ts.awaitHelper);
25983             return factory.createCallExpression(getUnscopedHelperName("__await"), /*typeArguments*/ undefined, [expression]);
25984         }
25985         function createAsyncGeneratorHelper(generatorFunc, hasLexicalThis) {
25986             context.requestEmitHelper(ts.awaitHelper);
25987             context.requestEmitHelper(ts.asyncGeneratorHelper);
25988             // Mark this node as originally an async function
25989             (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
25990             return factory.createCallExpression(getUnscopedHelperName("__asyncGenerator"), 
25991             /*typeArguments*/ undefined, [
25992                 hasLexicalThis ? factory.createThis() : factory.createVoidZero(),
25993                 factory.createIdentifier("arguments"),
25994                 generatorFunc
25995             ]);
25996         }
25997         function createAsyncDelegatorHelper(expression) {
25998             context.requestEmitHelper(ts.awaitHelper);
25999             context.requestEmitHelper(ts.asyncDelegator);
26000             return factory.createCallExpression(getUnscopedHelperName("__asyncDelegator"), 
26001             /*typeArguments*/ undefined, [expression]);
26002         }
26003         function createAsyncValuesHelper(expression) {
26004             context.requestEmitHelper(ts.asyncValues);
26005             return factory.createCallExpression(getUnscopedHelperName("__asyncValues"), 
26006             /*typeArguments*/ undefined, [expression]);
26007         }
26008         // ES2018 Destructuring Helpers
26009         /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
26010          * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
26011          */
26012         function createRestHelper(value, elements, computedTempVariables, location) {
26013             context.requestEmitHelper(ts.restHelper);
26014             var propertyNames = [];
26015             var computedTempVariableOffset = 0;
26016             for (var i = 0; i < elements.length - 1; i++) {
26017                 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]);
26018                 if (propertyName) {
26019                     if (ts.isComputedPropertyName(propertyName)) {
26020                         ts.Debug.assertIsDefined(computedTempVariables, "Encountered computed property name but 'computedTempVariables' argument was not provided.");
26021                         var temp = computedTempVariables[computedTempVariableOffset];
26022                         computedTempVariableOffset++;
26023                         // typeof _tmp === "symbol" ? _tmp : _tmp + ""
26024                         propertyNames.push(factory.createConditionalExpression(factory.createTypeCheck(temp, "symbol"), 
26025                         /*questionToken*/ undefined, temp, 
26026                         /*colonToken*/ undefined, factory.createAdd(temp, factory.createStringLiteral(""))));
26027                     }
26028                     else {
26029                         propertyNames.push(factory.createStringLiteralFromNode(propertyName));
26030                     }
26031                 }
26032             }
26033             return factory.createCallExpression(getUnscopedHelperName("__rest"), 
26034             /*typeArguments*/ undefined, [
26035                 value,
26036                 ts.setTextRange(factory.createArrayLiteralExpression(propertyNames), location)
26037             ]);
26038         }
26039         // ES2017 Helpers
26040         function createAwaiterHelper(hasLexicalThis, hasLexicalArguments, promiseConstructor, body) {
26041             context.requestEmitHelper(ts.awaiterHelper);
26042             var generatorFunc = factory.createFunctionExpression(
26043             /*modifiers*/ undefined, factory.createToken(41 /* AsteriskToken */), 
26044             /*name*/ undefined, 
26045             /*typeParameters*/ undefined, 
26046             /*parameters*/ [], 
26047             /*type*/ undefined, body);
26048             // Mark this node as originally an async function
26049             (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
26050             return factory.createCallExpression(getUnscopedHelperName("__awaiter"), 
26051             /*typeArguments*/ undefined, [
26052                 hasLexicalThis ? factory.createThis() : factory.createVoidZero(),
26053                 hasLexicalArguments ? factory.createIdentifier("arguments") : factory.createVoidZero(),
26054                 promiseConstructor ? ts.createExpressionFromEntityName(factory, promiseConstructor) : factory.createVoidZero(),
26055                 generatorFunc
26056             ]);
26057         }
26058         // ES2015 Helpers
26059         function createExtendsHelper(name) {
26060             context.requestEmitHelper(ts.extendsHelper);
26061             return factory.createCallExpression(getUnscopedHelperName("__extends"), 
26062             /*typeArguments*/ undefined, [name, factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */)]);
26063         }
26064         function createTemplateObjectHelper(cooked, raw) {
26065             context.requestEmitHelper(ts.templateObjectHelper);
26066             return factory.createCallExpression(getUnscopedHelperName("__makeTemplateObject"), 
26067             /*typeArguments*/ undefined, [cooked, raw]);
26068         }
26069         function createSpreadArrayHelper(to, from) {
26070             context.requestEmitHelper(ts.spreadArrayHelper);
26071             return factory.createCallExpression(getUnscopedHelperName("__spreadArray"), 
26072             /*typeArguments*/ undefined, [to, from]);
26073         }
26074         // ES2015 Destructuring Helpers
26075         function createValuesHelper(expression) {
26076             context.requestEmitHelper(ts.valuesHelper);
26077             return factory.createCallExpression(getUnscopedHelperName("__values"), 
26078             /*typeArguments*/ undefined, [expression]);
26079         }
26080         function createReadHelper(iteratorRecord, count) {
26081             context.requestEmitHelper(ts.readHelper);
26082             return factory.createCallExpression(getUnscopedHelperName("__read"), 
26083             /*typeArguments*/ undefined, count !== undefined
26084                 ? [iteratorRecord, factory.createNumericLiteral(count + "")]
26085                 : [iteratorRecord]);
26086         }
26087         // ES2015 Generator Helpers
26088         function createGeneratorHelper(body) {
26089             context.requestEmitHelper(ts.generatorHelper);
26090             return factory.createCallExpression(getUnscopedHelperName("__generator"), 
26091             /*typeArguments*/ undefined, [factory.createThis(), body]);
26092         }
26093         // ES Module Helpers
26094         function createCreateBindingHelper(module, inputName, outputName) {
26095             context.requestEmitHelper(ts.createBindingHelper);
26096             return factory.createCallExpression(getUnscopedHelperName("__createBinding"), 
26097             /*typeArguments*/ undefined, __spreadArray([factory.createIdentifier("exports"), module, inputName], (outputName ? [outputName] : [])));
26098         }
26099         function createImportStarHelper(expression) {
26100             context.requestEmitHelper(ts.importStarHelper);
26101             return factory.createCallExpression(getUnscopedHelperName("__importStar"), 
26102             /*typeArguments*/ undefined, [expression]);
26103         }
26104         function createImportStarCallbackHelper() {
26105             context.requestEmitHelper(ts.importStarHelper);
26106             return getUnscopedHelperName("__importStar");
26107         }
26108         function createImportDefaultHelper(expression) {
26109             context.requestEmitHelper(ts.importDefaultHelper);
26110             return factory.createCallExpression(getUnscopedHelperName("__importDefault"), 
26111             /*typeArguments*/ undefined, [expression]);
26112         }
26113         function createExportStarHelper(moduleExpression, exportsExpression) {
26114             if (exportsExpression === void 0) { exportsExpression = factory.createIdentifier("exports"); }
26115             context.requestEmitHelper(ts.exportStarHelper);
26116             context.requestEmitHelper(ts.createBindingHelper);
26117             return factory.createCallExpression(getUnscopedHelperName("__exportStar"), 
26118             /*typeArguments*/ undefined, [moduleExpression, exportsExpression]);
26119         }
26120         // Class Fields Helpers
26121         function createClassPrivateFieldGetHelper(receiver, privateField) {
26122             context.requestEmitHelper(ts.classPrivateFieldGetHelper);
26123             return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, [receiver, privateField]);
26124         }
26125         function createClassPrivateFieldSetHelper(receiver, privateField, value) {
26126             context.requestEmitHelper(ts.classPrivateFieldSetHelper);
26127             return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, [receiver, privateField, value]);
26128         }
26129     }
26130     ts.createEmitHelperFactory = createEmitHelperFactory;
26131     /* @internal */
26132     function compareEmitHelpers(x, y) {
26133         if (x === y)
26134             return 0 /* EqualTo */;
26135         if (x.priority === y.priority)
26136             return 0 /* EqualTo */;
26137         if (x.priority === undefined)
26138             return 1 /* GreaterThan */;
26139         if (y.priority === undefined)
26140             return -1 /* LessThan */;
26141         return ts.compareValues(x.priority, y.priority);
26142     }
26143     ts.compareEmitHelpers = compareEmitHelpers;
26144     /**
26145      * @param input Template string input strings
26146      * @param args Names which need to be made file-level unique
26147      */
26148     function helperString(input) {
26149         var args = [];
26150         for (var _i = 1; _i < arguments.length; _i++) {
26151             args[_i - 1] = arguments[_i];
26152         }
26153         return function (uniqueName) {
26154             var result = "";
26155             for (var i = 0; i < args.length; i++) {
26156                 result += input[i];
26157                 result += uniqueName(args[i]);
26158             }
26159             result += input[input.length - 1];
26160             return result;
26161         };
26162     }
26163     ts.helperString = helperString;
26164     // TypeScript Helpers
26165     ts.decorateHelper = {
26166         name: "typescript:decorate",
26167         importName: "__decorate",
26168         scoped: false,
26169         priority: 2,
26170         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            };"
26171     };
26172     ts.metadataHelper = {
26173         name: "typescript:metadata",
26174         importName: "__metadata",
26175         scoped: false,
26176         priority: 3,
26177         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            };"
26178     };
26179     ts.paramHelper = {
26180         name: "typescript:param",
26181         importName: "__param",
26182         scoped: false,
26183         priority: 4,
26184         text: "\n            var __param = (this && this.__param) || function (paramIndex, decorator) {\n                return function (target, key) { decorator(target, key, paramIndex); }\n            };"
26185     };
26186     // ES2018 Helpers
26187     ts.assignHelper = {
26188         name: "typescript:assign",
26189         importName: "__assign",
26190         scoped: false,
26191         priority: 1,
26192         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            };"
26193     };
26194     ts.awaitHelper = {
26195         name: "typescript:await",
26196         importName: "__await",
26197         scoped: false,
26198         text: "\n            var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
26199     };
26200     ts.asyncGeneratorHelper = {
26201         name: "typescript:asyncGenerator",
26202         importName: "__asyncGenerator",
26203         scoped: false,
26204         dependencies: [ts.awaitHelper],
26205         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            };"
26206     };
26207     ts.asyncDelegator = {
26208         name: "typescript:asyncDelegator",
26209         importName: "__asyncDelegator",
26210         scoped: false,
26211         dependencies: [ts.awaitHelper],
26212         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            };"
26213     };
26214     ts.asyncValues = {
26215         name: "typescript:asyncValues",
26216         importName: "__asyncValues",
26217         scoped: false,
26218         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            };"
26219     };
26220     // ES2018 Destructuring Helpers
26221     ts.restHelper = {
26222         name: "typescript:rest",
26223         importName: "__rest",
26224         scoped: false,
26225         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            };"
26226     };
26227     // ES2017 Helpers
26228     ts.awaiterHelper = {
26229         name: "typescript:awaiter",
26230         importName: "__awaiter",
26231         scoped: false,
26232         priority: 5,
26233         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            };"
26234     };
26235     // ES2015 Helpers
26236     ts.extendsHelper = {
26237         name: "typescript:extends",
26238         importName: "__extends",
26239         scoped: false,
26240         priority: 0,
26241         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            })();"
26242     };
26243     ts.templateObjectHelper = {
26244         name: "typescript:makeTemplateObject",
26245         importName: "__makeTemplateObject",
26246         scoped: false,
26247         priority: 0,
26248         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            };"
26249     };
26250     ts.readHelper = {
26251         name: "typescript:read",
26252         importName: "__read",
26253         scoped: false,
26254         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            };"
26255     };
26256     ts.spreadArrayHelper = {
26257         name: "typescript:spreadArray",
26258         importName: "__spreadArray",
26259         scoped: false,
26260         text: "\n            var __spreadArray = (this && this.__spreadArray) || function (to, from) {\n                for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)\n                    to[j] = from[i];\n                return to;\n            };"
26261     };
26262     // ES2015 Destructuring Helpers
26263     ts.valuesHelper = {
26264         name: "typescript:values",
26265         importName: "__values",
26266         scoped: false,
26267         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            };"
26268     };
26269     // ES2015 Generator Helpers
26270     // The __generator helper is used by down-level transformations to emulate the runtime
26271     // semantics of an ES2015 generator function. When called, this helper returns an
26272     // object that implements the Iterator protocol, in that it has `next`, `return`, and
26273     // `throw` methods that step through the generator when invoked.
26274     //
26275     // parameters:
26276     //  @param thisArg  The value to use as the `this` binding for the transformed generator body.
26277     //  @param body     A function that acts as the transformed generator body.
26278     //
26279     // variables:
26280     //  _       Persistent state for the generator that is shared between the helper and the
26281     //          generator body. The state object has the following members:
26282     //            sent() - A method that returns or throws the current completion value.
26283     //            label  - The next point at which to resume evaluation of the generator body.
26284     //            trys   - A stack of protected regions (try/catch/finally blocks).
26285     //            ops    - A stack of pending instructions when inside of a finally block.
26286     //  f       A value indicating whether the generator is executing.
26287     //  y       An iterator to delegate for a yield*.
26288     //  t       A temporary variable that holds one of the following values (note that these
26289     //          cases do not overlap):
26290     //          - The completion value when resuming from a `yield` or `yield*`.
26291     //          - The error value for a catch block.
26292     //          - The current protected region (array of try/catch/finally/end labels).
26293     //          - The verb (`next`, `throw`, or `return` method) to delegate to the expression
26294     //            of a `yield*`.
26295     //          - The result of evaluating the verb delegated to the expression of a `yield*`.
26296     //
26297     // functions:
26298     //  verb(n)     Creates a bound callback to the `step` function for opcode `n`.
26299     //  step(op)    Evaluates opcodes in a generator body until execution is suspended or
26300     //              completed.
26301     //
26302     // The __generator helper understands a limited set of instructions:
26303     //  0: next(value?)     - Start or resume the generator with the specified value.
26304     //  1: throw(error)     - Resume the generator with an exception. If the generator is
26305     //                        suspended inside of one or more protected regions, evaluates
26306     //                        any intervening finally blocks between the current label and
26307     //                        the nearest catch block or function boundary. If uncaught, the
26308     //                        exception is thrown to the caller.
26309     //  2: return(value?)   - Resume the generator as if with a return. If the generator is
26310     //                        suspended inside of one or more protected regions, evaluates any
26311     //                        intervening finally blocks.
26312     //  3: break(label)     - Jump to the specified label. If the label is outside of the
26313     //                        current protected region, evaluates any intervening finally
26314     //                        blocks.
26315     //  4: yield(value?)    - Yield execution to the caller with an optional value. When
26316     //                        resumed, the generator will continue at the next label.
26317     //  5: yield*(value)    - Delegates evaluation to the supplied iterator. When
26318     //                        delegation completes, the generator will continue at the next
26319     //                        label.
26320     //  6: catch(error)     - Handles an exception thrown from within the generator body. If
26321     //                        the current label is inside of one or more protected regions,
26322     //                        evaluates any intervening finally blocks between the current
26323     //                        label and the nearest catch block or function boundary. If
26324     //                        uncaught, the exception is thrown to the caller.
26325     //  7: endfinally       - Ends a finally block, resuming the last instruction prior to
26326     //                        entering a finally block.
26327     //
26328     // For examples of how these are used, see the comments in ./transformers/generators.ts
26329     ts.generatorHelper = {
26330         name: "typescript:generator",
26331         importName: "__generator",
26332         scoped: false,
26333         priority: 6,
26334         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            };"
26335     };
26336     // ES Module Helpers
26337     ts.createBindingHelper = {
26338         name: "typescript:commonjscreatebinding",
26339         importName: "__createBinding",
26340         scoped: false,
26341         priority: 1,
26342         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            }));"
26343     };
26344     ts.setModuleDefaultHelper = {
26345         name: "typescript:commonjscreatevalue",
26346         importName: "__setModuleDefault",
26347         scoped: false,
26348         priority: 1,
26349         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            });"
26350     };
26351     // emit helper for `import * as Name from "foo"`
26352     ts.importStarHelper = {
26353         name: "typescript:commonjsimportstar",
26354         importName: "__importStar",
26355         scoped: false,
26356         dependencies: [ts.createBindingHelper, ts.setModuleDefaultHelper],
26357         priority: 2,
26358         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            };"
26359     };
26360     // emit helper for `import Name from "foo"`
26361     ts.importDefaultHelper = {
26362         name: "typescript:commonjsimportdefault",
26363         importName: "__importDefault",
26364         scoped: false,
26365         text: "\n            var __importDefault = (this && this.__importDefault) || function (mod) {\n                return (mod && mod.__esModule) ? mod : { \"default\": mod };\n            };"
26366     };
26367     // emit output for the __export helper function
26368     ts.exportStarHelper = {
26369         name: "typescript:export-star",
26370         importName: "__exportStar",
26371         scoped: false,
26372         dependencies: [ts.createBindingHelper],
26373         priority: 2,
26374         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            };"
26375     };
26376     // Class fields helpers
26377     ts.classPrivateFieldGetHelper = {
26378         name: "typescript:classPrivateFieldGet",
26379         importName: "__classPrivateFieldGet",
26380         scoped: false,
26381         text: "\n            var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, privateMap) {\n                if (!privateMap.has(receiver)) {\n                    throw new TypeError(\"attempted to get private field on non-instance\");\n                }\n                return privateMap.get(receiver);\n            };"
26382     };
26383     ts.classPrivateFieldSetHelper = {
26384         name: "typescript:classPrivateFieldSet",
26385         importName: "__classPrivateFieldSet",
26386         scoped: false,
26387         text: "\n            var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, privateMap, value) {\n                if (!privateMap.has(receiver)) {\n                    throw new TypeError(\"attempted to set private field on non-instance\");\n                }\n                privateMap.set(receiver, value);\n                return value;\n            };"
26388     };
26389     var allUnscopedEmitHelpers;
26390     function getAllUnscopedEmitHelpers() {
26391         return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
26392             ts.decorateHelper,
26393             ts.metadataHelper,
26394             ts.paramHelper,
26395             ts.assignHelper,
26396             ts.awaitHelper,
26397             ts.asyncGeneratorHelper,
26398             ts.asyncDelegator,
26399             ts.asyncValues,
26400             ts.restHelper,
26401             ts.awaiterHelper,
26402             ts.extendsHelper,
26403             ts.templateObjectHelper,
26404             ts.spreadArrayHelper,
26405             ts.valuesHelper,
26406             ts.readHelper,
26407             ts.generatorHelper,
26408             ts.importStarHelper,
26409             ts.importDefaultHelper,
26410             ts.exportStarHelper,
26411             ts.classPrivateFieldGetHelper,
26412             ts.classPrivateFieldSetHelper,
26413             ts.createBindingHelper,
26414             ts.setModuleDefaultHelper
26415         ], function (helper) { return helper.name; }));
26416     }
26417     ts.getAllUnscopedEmitHelpers = getAllUnscopedEmitHelpers;
26418     ts.asyncSuperHelper = {
26419         name: "typescript:async-super",
26420         scoped: true,
26421         text: helperString(__makeTemplateObject(["\n            const ", " = name => super[name];"], ["\n            const ", " = name => super[name];"]), "_superIndex")
26422     };
26423     ts.advancedAsyncSuperHelper = {
26424         name: "typescript:advanced-async-super",
26425         scoped: true,
26426         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")
26427     };
26428     function isCallToHelper(firstSegment, helperName) {
26429         return ts.isCallExpression(firstSegment)
26430             && ts.isIdentifier(firstSegment.expression)
26431             && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
26432             && firstSegment.expression.escapedText === helperName;
26433     }
26434     ts.isCallToHelper = isCallToHelper;
26435 })(ts || (ts = {}));
26436 var ts;
26437 (function (ts) {
26438     // Literals
26439     function isNumericLiteral(node) {
26440         return node.kind === 8 /* NumericLiteral */;
26441     }
26442     ts.isNumericLiteral = isNumericLiteral;
26443     function isBigIntLiteral(node) {
26444         return node.kind === 9 /* BigIntLiteral */;
26445     }
26446     ts.isBigIntLiteral = isBigIntLiteral;
26447     function isStringLiteral(node) {
26448         return node.kind === 10 /* StringLiteral */;
26449     }
26450     ts.isStringLiteral = isStringLiteral;
26451     function isJsxText(node) {
26452         return node.kind === 11 /* JsxText */;
26453     }
26454     ts.isJsxText = isJsxText;
26455     function isRegularExpressionLiteral(node) {
26456         return node.kind === 13 /* RegularExpressionLiteral */;
26457     }
26458     ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
26459     function isNoSubstitutionTemplateLiteral(node) {
26460         return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
26461     }
26462     ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
26463     // Pseudo-literals
26464     function isTemplateHead(node) {
26465         return node.kind === 15 /* TemplateHead */;
26466     }
26467     ts.isTemplateHead = isTemplateHead;
26468     function isTemplateMiddle(node) {
26469         return node.kind === 16 /* TemplateMiddle */;
26470     }
26471     ts.isTemplateMiddle = isTemplateMiddle;
26472     function isTemplateTail(node) {
26473         return node.kind === 17 /* TemplateTail */;
26474     }
26475     ts.isTemplateTail = isTemplateTail;
26476     // Identifiers
26477     function isIdentifier(node) {
26478         return node.kind === 78 /* Identifier */;
26479     }
26480     ts.isIdentifier = isIdentifier;
26481     // Names
26482     function isQualifiedName(node) {
26483         return node.kind === 157 /* QualifiedName */;
26484     }
26485     ts.isQualifiedName = isQualifiedName;
26486     function isComputedPropertyName(node) {
26487         return node.kind === 158 /* ComputedPropertyName */;
26488     }
26489     ts.isComputedPropertyName = isComputedPropertyName;
26490     function isPrivateIdentifier(node) {
26491         return node.kind === 79 /* PrivateIdentifier */;
26492     }
26493     ts.isPrivateIdentifier = isPrivateIdentifier;
26494     // Tokens
26495     /*@internal*/
26496     function isSuperKeyword(node) {
26497         return node.kind === 105 /* SuperKeyword */;
26498     }
26499     ts.isSuperKeyword = isSuperKeyword;
26500     /*@internal*/
26501     function isImportKeyword(node) {
26502         return node.kind === 99 /* ImportKeyword */;
26503     }
26504     ts.isImportKeyword = isImportKeyword;
26505     /*@internal*/
26506     function isCommaToken(node) {
26507         return node.kind === 27 /* CommaToken */;
26508     }
26509     ts.isCommaToken = isCommaToken;
26510     /*@internal*/
26511     function isQuestionToken(node) {
26512         return node.kind === 57 /* QuestionToken */;
26513     }
26514     ts.isQuestionToken = isQuestionToken;
26515     /*@internal*/
26516     function isExclamationToken(node) {
26517         return node.kind === 53 /* ExclamationToken */;
26518     }
26519     ts.isExclamationToken = isExclamationToken;
26520     // Signature elements
26521     function isTypeParameterDeclaration(node) {
26522         return node.kind === 159 /* TypeParameter */;
26523     }
26524     ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
26525     // TODO(rbuckton): Rename to 'isParameterDeclaration'
26526     function isParameter(node) {
26527         return node.kind === 160 /* Parameter */;
26528     }
26529     ts.isParameter = isParameter;
26530     function isDecorator(node) {
26531         return node.kind === 161 /* Decorator */;
26532     }
26533     ts.isDecorator = isDecorator;
26534     // TypeMember
26535     function isPropertySignature(node) {
26536         return node.kind === 162 /* PropertySignature */;
26537     }
26538     ts.isPropertySignature = isPropertySignature;
26539     function isPropertyDeclaration(node) {
26540         return node.kind === 163 /* PropertyDeclaration */;
26541     }
26542     ts.isPropertyDeclaration = isPropertyDeclaration;
26543     function isMethodSignature(node) {
26544         return node.kind === 164 /* MethodSignature */;
26545     }
26546     ts.isMethodSignature = isMethodSignature;
26547     function isMethodDeclaration(node) {
26548         return node.kind === 165 /* MethodDeclaration */;
26549     }
26550     ts.isMethodDeclaration = isMethodDeclaration;
26551     function isConstructorDeclaration(node) {
26552         return node.kind === 166 /* Constructor */;
26553     }
26554     ts.isConstructorDeclaration = isConstructorDeclaration;
26555     function isGetAccessorDeclaration(node) {
26556         return node.kind === 167 /* GetAccessor */;
26557     }
26558     ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
26559     function isSetAccessorDeclaration(node) {
26560         return node.kind === 168 /* SetAccessor */;
26561     }
26562     ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
26563     function isCallSignatureDeclaration(node) {
26564         return node.kind === 169 /* CallSignature */;
26565     }
26566     ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
26567     function isConstructSignatureDeclaration(node) {
26568         return node.kind === 170 /* ConstructSignature */;
26569     }
26570     ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
26571     function isIndexSignatureDeclaration(node) {
26572         return node.kind === 171 /* IndexSignature */;
26573     }
26574     ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
26575     // Type
26576     function isTypePredicateNode(node) {
26577         return node.kind === 172 /* TypePredicate */;
26578     }
26579     ts.isTypePredicateNode = isTypePredicateNode;
26580     function isTypeReferenceNode(node) {
26581         return node.kind === 173 /* TypeReference */;
26582     }
26583     ts.isTypeReferenceNode = isTypeReferenceNode;
26584     function isFunctionTypeNode(node) {
26585         return node.kind === 174 /* FunctionType */;
26586     }
26587     ts.isFunctionTypeNode = isFunctionTypeNode;
26588     function isConstructorTypeNode(node) {
26589         return node.kind === 175 /* ConstructorType */;
26590     }
26591     ts.isConstructorTypeNode = isConstructorTypeNode;
26592     function isTypeQueryNode(node) {
26593         return node.kind === 176 /* TypeQuery */;
26594     }
26595     ts.isTypeQueryNode = isTypeQueryNode;
26596     function isTypeLiteralNode(node) {
26597         return node.kind === 177 /* TypeLiteral */;
26598     }
26599     ts.isTypeLiteralNode = isTypeLiteralNode;
26600     function isArrayTypeNode(node) {
26601         return node.kind === 178 /* ArrayType */;
26602     }
26603     ts.isArrayTypeNode = isArrayTypeNode;
26604     function isTupleTypeNode(node) {
26605         return node.kind === 179 /* TupleType */;
26606     }
26607     ts.isTupleTypeNode = isTupleTypeNode;
26608     function isNamedTupleMember(node) {
26609         return node.kind === 192 /* NamedTupleMember */;
26610     }
26611     ts.isNamedTupleMember = isNamedTupleMember;
26612     function isOptionalTypeNode(node) {
26613         return node.kind === 180 /* OptionalType */;
26614     }
26615     ts.isOptionalTypeNode = isOptionalTypeNode;
26616     function isRestTypeNode(node) {
26617         return node.kind === 181 /* RestType */;
26618     }
26619     ts.isRestTypeNode = isRestTypeNode;
26620     function isUnionTypeNode(node) {
26621         return node.kind === 182 /* UnionType */;
26622     }
26623     ts.isUnionTypeNode = isUnionTypeNode;
26624     function isIntersectionTypeNode(node) {
26625         return node.kind === 183 /* IntersectionType */;
26626     }
26627     ts.isIntersectionTypeNode = isIntersectionTypeNode;
26628     function isConditionalTypeNode(node) {
26629         return node.kind === 184 /* ConditionalType */;
26630     }
26631     ts.isConditionalTypeNode = isConditionalTypeNode;
26632     function isInferTypeNode(node) {
26633         return node.kind === 185 /* InferType */;
26634     }
26635     ts.isInferTypeNode = isInferTypeNode;
26636     function isParenthesizedTypeNode(node) {
26637         return node.kind === 186 /* ParenthesizedType */;
26638     }
26639     ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
26640     function isThisTypeNode(node) {
26641         return node.kind === 187 /* ThisType */;
26642     }
26643     ts.isThisTypeNode = isThisTypeNode;
26644     function isTypeOperatorNode(node) {
26645         return node.kind === 188 /* TypeOperator */;
26646     }
26647     ts.isTypeOperatorNode = isTypeOperatorNode;
26648     function isIndexedAccessTypeNode(node) {
26649         return node.kind === 189 /* IndexedAccessType */;
26650     }
26651     ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
26652     function isMappedTypeNode(node) {
26653         return node.kind === 190 /* MappedType */;
26654     }
26655     ts.isMappedTypeNode = isMappedTypeNode;
26656     function isLiteralTypeNode(node) {
26657         return node.kind === 191 /* LiteralType */;
26658     }
26659     ts.isLiteralTypeNode = isLiteralTypeNode;
26660     function isImportTypeNode(node) {
26661         return node.kind === 195 /* ImportType */;
26662     }
26663     ts.isImportTypeNode = isImportTypeNode;
26664     function isTemplateLiteralTypeSpan(node) {
26665         return node.kind === 194 /* TemplateLiteralTypeSpan */;
26666     }
26667     ts.isTemplateLiteralTypeSpan = isTemplateLiteralTypeSpan;
26668     function isTemplateLiteralTypeNode(node) {
26669         return node.kind === 193 /* TemplateLiteralType */;
26670     }
26671     ts.isTemplateLiteralTypeNode = isTemplateLiteralTypeNode;
26672     // Binding patterns
26673     function isObjectBindingPattern(node) {
26674         return node.kind === 196 /* ObjectBindingPattern */;
26675     }
26676     ts.isObjectBindingPattern = isObjectBindingPattern;
26677     function isArrayBindingPattern(node) {
26678         return node.kind === 197 /* ArrayBindingPattern */;
26679     }
26680     ts.isArrayBindingPattern = isArrayBindingPattern;
26681     function isBindingElement(node) {
26682         return node.kind === 198 /* BindingElement */;
26683     }
26684     ts.isBindingElement = isBindingElement;
26685     // Expression
26686     function isArrayLiteralExpression(node) {
26687         return node.kind === 199 /* ArrayLiteralExpression */;
26688     }
26689     ts.isArrayLiteralExpression = isArrayLiteralExpression;
26690     function isObjectLiteralExpression(node) {
26691         return node.kind === 200 /* ObjectLiteralExpression */;
26692     }
26693     ts.isObjectLiteralExpression = isObjectLiteralExpression;
26694     function isPropertyAccessExpression(node) {
26695         return node.kind === 201 /* PropertyAccessExpression */;
26696     }
26697     ts.isPropertyAccessExpression = isPropertyAccessExpression;
26698     function isElementAccessExpression(node) {
26699         return node.kind === 202 /* ElementAccessExpression */;
26700     }
26701     ts.isElementAccessExpression = isElementAccessExpression;
26702     function isCallExpression(node) {
26703         return node.kind === 203 /* CallExpression */;
26704     }
26705     ts.isCallExpression = isCallExpression;
26706     function isNewExpression(node) {
26707         return node.kind === 204 /* NewExpression */;
26708     }
26709     ts.isNewExpression = isNewExpression;
26710     function isTaggedTemplateExpression(node) {
26711         return node.kind === 205 /* TaggedTemplateExpression */;
26712     }
26713     ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
26714     function isTypeAssertionExpression(node) {
26715         return node.kind === 206 /* TypeAssertionExpression */;
26716     }
26717     ts.isTypeAssertionExpression = isTypeAssertionExpression;
26718     function isParenthesizedExpression(node) {
26719         return node.kind === 207 /* ParenthesizedExpression */;
26720     }
26721     ts.isParenthesizedExpression = isParenthesizedExpression;
26722     function isFunctionExpression(node) {
26723         return node.kind === 208 /* FunctionExpression */;
26724     }
26725     ts.isFunctionExpression = isFunctionExpression;
26726     function isArrowFunction(node) {
26727         return node.kind === 209 /* ArrowFunction */;
26728     }
26729     ts.isArrowFunction = isArrowFunction;
26730     function isDeleteExpression(node) {
26731         return node.kind === 210 /* DeleteExpression */;
26732     }
26733     ts.isDeleteExpression = isDeleteExpression;
26734     function isTypeOfExpression(node) {
26735         return node.kind === 211 /* TypeOfExpression */;
26736     }
26737     ts.isTypeOfExpression = isTypeOfExpression;
26738     function isVoidExpression(node) {
26739         return node.kind === 212 /* VoidExpression */;
26740     }
26741     ts.isVoidExpression = isVoidExpression;
26742     function isAwaitExpression(node) {
26743         return node.kind === 213 /* AwaitExpression */;
26744     }
26745     ts.isAwaitExpression = isAwaitExpression;
26746     function isPrefixUnaryExpression(node) {
26747         return node.kind === 214 /* PrefixUnaryExpression */;
26748     }
26749     ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
26750     function isPostfixUnaryExpression(node) {
26751         return node.kind === 215 /* PostfixUnaryExpression */;
26752     }
26753     ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
26754     function isBinaryExpression(node) {
26755         return node.kind === 216 /* BinaryExpression */;
26756     }
26757     ts.isBinaryExpression = isBinaryExpression;
26758     function isConditionalExpression(node) {
26759         return node.kind === 217 /* ConditionalExpression */;
26760     }
26761     ts.isConditionalExpression = isConditionalExpression;
26762     function isTemplateExpression(node) {
26763         return node.kind === 218 /* TemplateExpression */;
26764     }
26765     ts.isTemplateExpression = isTemplateExpression;
26766     function isYieldExpression(node) {
26767         return node.kind === 219 /* YieldExpression */;
26768     }
26769     ts.isYieldExpression = isYieldExpression;
26770     function isSpreadElement(node) {
26771         return node.kind === 220 /* SpreadElement */;
26772     }
26773     ts.isSpreadElement = isSpreadElement;
26774     function isClassExpression(node) {
26775         return node.kind === 221 /* ClassExpression */;
26776     }
26777     ts.isClassExpression = isClassExpression;
26778     function isOmittedExpression(node) {
26779         return node.kind === 222 /* OmittedExpression */;
26780     }
26781     ts.isOmittedExpression = isOmittedExpression;
26782     function isExpressionWithTypeArguments(node) {
26783         return node.kind === 223 /* ExpressionWithTypeArguments */;
26784     }
26785     ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
26786     function isAsExpression(node) {
26787         return node.kind === 224 /* AsExpression */;
26788     }
26789     ts.isAsExpression = isAsExpression;
26790     function isNonNullExpression(node) {
26791         return node.kind === 225 /* NonNullExpression */;
26792     }
26793     ts.isNonNullExpression = isNonNullExpression;
26794     function isMetaProperty(node) {
26795         return node.kind === 226 /* MetaProperty */;
26796     }
26797     ts.isMetaProperty = isMetaProperty;
26798     function isSyntheticExpression(node) {
26799         return node.kind === 227 /* SyntheticExpression */;
26800     }
26801     ts.isSyntheticExpression = isSyntheticExpression;
26802     function isPartiallyEmittedExpression(node) {
26803         return node.kind === 336 /* PartiallyEmittedExpression */;
26804     }
26805     ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
26806     function isCommaListExpression(node) {
26807         return node.kind === 337 /* CommaListExpression */;
26808     }
26809     ts.isCommaListExpression = isCommaListExpression;
26810     // Misc
26811     function isTemplateSpan(node) {
26812         return node.kind === 228 /* TemplateSpan */;
26813     }
26814     ts.isTemplateSpan = isTemplateSpan;
26815     function isSemicolonClassElement(node) {
26816         return node.kind === 229 /* SemicolonClassElement */;
26817     }
26818     ts.isSemicolonClassElement = isSemicolonClassElement;
26819     // Elements
26820     function isBlock(node) {
26821         return node.kind === 230 /* Block */;
26822     }
26823     ts.isBlock = isBlock;
26824     function isVariableStatement(node) {
26825         return node.kind === 232 /* VariableStatement */;
26826     }
26827     ts.isVariableStatement = isVariableStatement;
26828     function isEmptyStatement(node) {
26829         return node.kind === 231 /* EmptyStatement */;
26830     }
26831     ts.isEmptyStatement = isEmptyStatement;
26832     function isExpressionStatement(node) {
26833         return node.kind === 233 /* ExpressionStatement */;
26834     }
26835     ts.isExpressionStatement = isExpressionStatement;
26836     function isIfStatement(node) {
26837         return node.kind === 234 /* IfStatement */;
26838     }
26839     ts.isIfStatement = isIfStatement;
26840     function isDoStatement(node) {
26841         return node.kind === 235 /* DoStatement */;
26842     }
26843     ts.isDoStatement = isDoStatement;
26844     function isWhileStatement(node) {
26845         return node.kind === 236 /* WhileStatement */;
26846     }
26847     ts.isWhileStatement = isWhileStatement;
26848     function isForStatement(node) {
26849         return node.kind === 237 /* ForStatement */;
26850     }
26851     ts.isForStatement = isForStatement;
26852     function isForInStatement(node) {
26853         return node.kind === 238 /* ForInStatement */;
26854     }
26855     ts.isForInStatement = isForInStatement;
26856     function isForOfStatement(node) {
26857         return node.kind === 239 /* ForOfStatement */;
26858     }
26859     ts.isForOfStatement = isForOfStatement;
26860     function isContinueStatement(node) {
26861         return node.kind === 240 /* ContinueStatement */;
26862     }
26863     ts.isContinueStatement = isContinueStatement;
26864     function isBreakStatement(node) {
26865         return node.kind === 241 /* BreakStatement */;
26866     }
26867     ts.isBreakStatement = isBreakStatement;
26868     function isReturnStatement(node) {
26869         return node.kind === 242 /* ReturnStatement */;
26870     }
26871     ts.isReturnStatement = isReturnStatement;
26872     function isWithStatement(node) {
26873         return node.kind === 243 /* WithStatement */;
26874     }
26875     ts.isWithStatement = isWithStatement;
26876     function isSwitchStatement(node) {
26877         return node.kind === 244 /* SwitchStatement */;
26878     }
26879     ts.isSwitchStatement = isSwitchStatement;
26880     function isLabeledStatement(node) {
26881         return node.kind === 245 /* LabeledStatement */;
26882     }
26883     ts.isLabeledStatement = isLabeledStatement;
26884     function isThrowStatement(node) {
26885         return node.kind === 246 /* ThrowStatement */;
26886     }
26887     ts.isThrowStatement = isThrowStatement;
26888     function isTryStatement(node) {
26889         return node.kind === 247 /* TryStatement */;
26890     }
26891     ts.isTryStatement = isTryStatement;
26892     function isDebuggerStatement(node) {
26893         return node.kind === 248 /* DebuggerStatement */;
26894     }
26895     ts.isDebuggerStatement = isDebuggerStatement;
26896     function isVariableDeclaration(node) {
26897         return node.kind === 249 /* VariableDeclaration */;
26898     }
26899     ts.isVariableDeclaration = isVariableDeclaration;
26900     function isVariableDeclarationList(node) {
26901         return node.kind === 250 /* VariableDeclarationList */;
26902     }
26903     ts.isVariableDeclarationList = isVariableDeclarationList;
26904     function isFunctionDeclaration(node) {
26905         return node.kind === 251 /* FunctionDeclaration */;
26906     }
26907     ts.isFunctionDeclaration = isFunctionDeclaration;
26908     function isClassDeclaration(node) {
26909         return node.kind === 252 /* ClassDeclaration */;
26910     }
26911     ts.isClassDeclaration = isClassDeclaration;
26912     function isInterfaceDeclaration(node) {
26913         return node.kind === 253 /* InterfaceDeclaration */;
26914     }
26915     ts.isInterfaceDeclaration = isInterfaceDeclaration;
26916     function isTypeAliasDeclaration(node) {
26917         return node.kind === 254 /* TypeAliasDeclaration */;
26918     }
26919     ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
26920     function isEnumDeclaration(node) {
26921         return node.kind === 255 /* EnumDeclaration */;
26922     }
26923     ts.isEnumDeclaration = isEnumDeclaration;
26924     function isModuleDeclaration(node) {
26925         return node.kind === 256 /* ModuleDeclaration */;
26926     }
26927     ts.isModuleDeclaration = isModuleDeclaration;
26928     function isModuleBlock(node) {
26929         return node.kind === 257 /* ModuleBlock */;
26930     }
26931     ts.isModuleBlock = isModuleBlock;
26932     function isCaseBlock(node) {
26933         return node.kind === 258 /* CaseBlock */;
26934     }
26935     ts.isCaseBlock = isCaseBlock;
26936     function isNamespaceExportDeclaration(node) {
26937         return node.kind === 259 /* NamespaceExportDeclaration */;
26938     }
26939     ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
26940     function isImportEqualsDeclaration(node) {
26941         return node.kind === 260 /* ImportEqualsDeclaration */;
26942     }
26943     ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
26944     function isImportDeclaration(node) {
26945         return node.kind === 261 /* ImportDeclaration */;
26946     }
26947     ts.isImportDeclaration = isImportDeclaration;
26948     function isImportClause(node) {
26949         return node.kind === 262 /* ImportClause */;
26950     }
26951     ts.isImportClause = isImportClause;
26952     function isNamespaceImport(node) {
26953         return node.kind === 263 /* NamespaceImport */;
26954     }
26955     ts.isNamespaceImport = isNamespaceImport;
26956     function isNamespaceExport(node) {
26957         return node.kind === 269 /* NamespaceExport */;
26958     }
26959     ts.isNamespaceExport = isNamespaceExport;
26960     function isNamedImports(node) {
26961         return node.kind === 264 /* NamedImports */;
26962     }
26963     ts.isNamedImports = isNamedImports;
26964     function isImportSpecifier(node) {
26965         return node.kind === 265 /* ImportSpecifier */;
26966     }
26967     ts.isImportSpecifier = isImportSpecifier;
26968     function isExportAssignment(node) {
26969         return node.kind === 266 /* ExportAssignment */;
26970     }
26971     ts.isExportAssignment = isExportAssignment;
26972     function isExportDeclaration(node) {
26973         return node.kind === 267 /* ExportDeclaration */;
26974     }
26975     ts.isExportDeclaration = isExportDeclaration;
26976     function isNamedExports(node) {
26977         return node.kind === 268 /* NamedExports */;
26978     }
26979     ts.isNamedExports = isNamedExports;
26980     function isExportSpecifier(node) {
26981         return node.kind === 270 /* ExportSpecifier */;
26982     }
26983     ts.isExportSpecifier = isExportSpecifier;
26984     function isMissingDeclaration(node) {
26985         return node.kind === 271 /* MissingDeclaration */;
26986     }
26987     ts.isMissingDeclaration = isMissingDeclaration;
26988     function isNotEmittedStatement(node) {
26989         return node.kind === 335 /* NotEmittedStatement */;
26990     }
26991     ts.isNotEmittedStatement = isNotEmittedStatement;
26992     /* @internal */
26993     function isSyntheticReference(node) {
26994         return node.kind === 340 /* SyntheticReferenceExpression */;
26995     }
26996     ts.isSyntheticReference = isSyntheticReference;
26997     /* @internal */
26998     function isMergeDeclarationMarker(node) {
26999         return node.kind === 338 /* MergeDeclarationMarker */;
27000     }
27001     ts.isMergeDeclarationMarker = isMergeDeclarationMarker;
27002     /* @internal */
27003     function isEndOfDeclarationMarker(node) {
27004         return node.kind === 339 /* EndOfDeclarationMarker */;
27005     }
27006     ts.isEndOfDeclarationMarker = isEndOfDeclarationMarker;
27007     // Module References
27008     function isExternalModuleReference(node) {
27009         return node.kind === 272 /* ExternalModuleReference */;
27010     }
27011     ts.isExternalModuleReference = isExternalModuleReference;
27012     // JSX
27013     function isJsxElement(node) {
27014         return node.kind === 273 /* JsxElement */;
27015     }
27016     ts.isJsxElement = isJsxElement;
27017     function isJsxSelfClosingElement(node) {
27018         return node.kind === 274 /* JsxSelfClosingElement */;
27019     }
27020     ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
27021     function isJsxOpeningElement(node) {
27022         return node.kind === 275 /* JsxOpeningElement */;
27023     }
27024     ts.isJsxOpeningElement = isJsxOpeningElement;
27025     function isJsxClosingElement(node) {
27026         return node.kind === 276 /* JsxClosingElement */;
27027     }
27028     ts.isJsxClosingElement = isJsxClosingElement;
27029     function isJsxFragment(node) {
27030         return node.kind === 277 /* JsxFragment */;
27031     }
27032     ts.isJsxFragment = isJsxFragment;
27033     function isJsxOpeningFragment(node) {
27034         return node.kind === 278 /* JsxOpeningFragment */;
27035     }
27036     ts.isJsxOpeningFragment = isJsxOpeningFragment;
27037     function isJsxClosingFragment(node) {
27038         return node.kind === 279 /* JsxClosingFragment */;
27039     }
27040     ts.isJsxClosingFragment = isJsxClosingFragment;
27041     function isJsxAttribute(node) {
27042         return node.kind === 280 /* JsxAttribute */;
27043     }
27044     ts.isJsxAttribute = isJsxAttribute;
27045     function isJsxAttributes(node) {
27046         return node.kind === 281 /* JsxAttributes */;
27047     }
27048     ts.isJsxAttributes = isJsxAttributes;
27049     function isJsxSpreadAttribute(node) {
27050         return node.kind === 282 /* JsxSpreadAttribute */;
27051     }
27052     ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
27053     function isJsxExpression(node) {
27054         return node.kind === 283 /* JsxExpression */;
27055     }
27056     ts.isJsxExpression = isJsxExpression;
27057     // Clauses
27058     function isCaseClause(node) {
27059         return node.kind === 284 /* CaseClause */;
27060     }
27061     ts.isCaseClause = isCaseClause;
27062     function isDefaultClause(node) {
27063         return node.kind === 285 /* DefaultClause */;
27064     }
27065     ts.isDefaultClause = isDefaultClause;
27066     function isHeritageClause(node) {
27067         return node.kind === 286 /* HeritageClause */;
27068     }
27069     ts.isHeritageClause = isHeritageClause;
27070     function isCatchClause(node) {
27071         return node.kind === 287 /* CatchClause */;
27072     }
27073     ts.isCatchClause = isCatchClause;
27074     // Property assignments
27075     function isPropertyAssignment(node) {
27076         return node.kind === 288 /* PropertyAssignment */;
27077     }
27078     ts.isPropertyAssignment = isPropertyAssignment;
27079     function isShorthandPropertyAssignment(node) {
27080         return node.kind === 289 /* ShorthandPropertyAssignment */;
27081     }
27082     ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
27083     function isSpreadAssignment(node) {
27084         return node.kind === 290 /* SpreadAssignment */;
27085     }
27086     ts.isSpreadAssignment = isSpreadAssignment;
27087     // Enum
27088     function isEnumMember(node) {
27089         return node.kind === 291 /* EnumMember */;
27090     }
27091     ts.isEnumMember = isEnumMember;
27092     // Unparsed
27093     // TODO(rbuckton): isUnparsedPrologue
27094     function isUnparsedPrepend(node) {
27095         return node.kind === 293 /* UnparsedPrepend */;
27096     }
27097     ts.isUnparsedPrepend = isUnparsedPrepend;
27098     // TODO(rbuckton): isUnparsedText
27099     // TODO(rbuckton): isUnparsedInternalText
27100     // TODO(rbuckton): isUnparsedSyntheticReference
27101     // Top-level nodes
27102     function isSourceFile(node) {
27103         return node.kind === 297 /* SourceFile */;
27104     }
27105     ts.isSourceFile = isSourceFile;
27106     function isBundle(node) {
27107         return node.kind === 298 /* Bundle */;
27108     }
27109     ts.isBundle = isBundle;
27110     function isUnparsedSource(node) {
27111         return node.kind === 299 /* UnparsedSource */;
27112     }
27113     ts.isUnparsedSource = isUnparsedSource;
27114     // TODO(rbuckton): isInputFiles
27115     // JSDoc Elements
27116     function isJSDocTypeExpression(node) {
27117         return node.kind === 301 /* JSDocTypeExpression */;
27118     }
27119     ts.isJSDocTypeExpression = isJSDocTypeExpression;
27120     function isJSDocNameReference(node) {
27121         return node.kind === 302 /* JSDocNameReference */;
27122     }
27123     ts.isJSDocNameReference = isJSDocNameReference;
27124     function isJSDocAllType(node) {
27125         return node.kind === 303 /* JSDocAllType */;
27126     }
27127     ts.isJSDocAllType = isJSDocAllType;
27128     function isJSDocUnknownType(node) {
27129         return node.kind === 304 /* JSDocUnknownType */;
27130     }
27131     ts.isJSDocUnknownType = isJSDocUnknownType;
27132     function isJSDocNullableType(node) {
27133         return node.kind === 305 /* JSDocNullableType */;
27134     }
27135     ts.isJSDocNullableType = isJSDocNullableType;
27136     function isJSDocNonNullableType(node) {
27137         return node.kind === 306 /* JSDocNonNullableType */;
27138     }
27139     ts.isJSDocNonNullableType = isJSDocNonNullableType;
27140     function isJSDocOptionalType(node) {
27141         return node.kind === 307 /* JSDocOptionalType */;
27142     }
27143     ts.isJSDocOptionalType = isJSDocOptionalType;
27144     function isJSDocFunctionType(node) {
27145         return node.kind === 308 /* JSDocFunctionType */;
27146     }
27147     ts.isJSDocFunctionType = isJSDocFunctionType;
27148     function isJSDocVariadicType(node) {
27149         return node.kind === 309 /* JSDocVariadicType */;
27150     }
27151     ts.isJSDocVariadicType = isJSDocVariadicType;
27152     function isJSDocNamepathType(node) {
27153         return node.kind === 310 /* JSDocNamepathType */;
27154     }
27155     ts.isJSDocNamepathType = isJSDocNamepathType;
27156     function isJSDoc(node) {
27157         return node.kind === 311 /* JSDocComment */;
27158     }
27159     ts.isJSDoc = isJSDoc;
27160     function isJSDocTypeLiteral(node) {
27161         return node.kind === 312 /* JSDocTypeLiteral */;
27162     }
27163     ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
27164     function isJSDocSignature(node) {
27165         return node.kind === 313 /* JSDocSignature */;
27166     }
27167     ts.isJSDocSignature = isJSDocSignature;
27168     // JSDoc Tags
27169     function isJSDocAugmentsTag(node) {
27170         return node.kind === 315 /* JSDocAugmentsTag */;
27171     }
27172     ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
27173     function isJSDocAuthorTag(node) {
27174         return node.kind === 317 /* JSDocAuthorTag */;
27175     }
27176     ts.isJSDocAuthorTag = isJSDocAuthorTag;
27177     function isJSDocClassTag(node) {
27178         return node.kind === 319 /* JSDocClassTag */;
27179     }
27180     ts.isJSDocClassTag = isJSDocClassTag;
27181     function isJSDocCallbackTag(node) {
27182         return node.kind === 324 /* JSDocCallbackTag */;
27183     }
27184     ts.isJSDocCallbackTag = isJSDocCallbackTag;
27185     function isJSDocPublicTag(node) {
27186         return node.kind === 320 /* JSDocPublicTag */;
27187     }
27188     ts.isJSDocPublicTag = isJSDocPublicTag;
27189     function isJSDocPrivateTag(node) {
27190         return node.kind === 321 /* JSDocPrivateTag */;
27191     }
27192     ts.isJSDocPrivateTag = isJSDocPrivateTag;
27193     function isJSDocProtectedTag(node) {
27194         return node.kind === 322 /* JSDocProtectedTag */;
27195     }
27196     ts.isJSDocProtectedTag = isJSDocProtectedTag;
27197     function isJSDocReadonlyTag(node) {
27198         return node.kind === 323 /* JSDocReadonlyTag */;
27199     }
27200     ts.isJSDocReadonlyTag = isJSDocReadonlyTag;
27201     function isJSDocDeprecatedTag(node) {
27202         return node.kind === 318 /* JSDocDeprecatedTag */;
27203     }
27204     ts.isJSDocDeprecatedTag = isJSDocDeprecatedTag;
27205     function isJSDocSeeTag(node) {
27206         return node.kind === 332 /* JSDocSeeTag */;
27207     }
27208     ts.isJSDocSeeTag = isJSDocSeeTag;
27209     function isJSDocEnumTag(node) {
27210         return node.kind === 325 /* JSDocEnumTag */;
27211     }
27212     ts.isJSDocEnumTag = isJSDocEnumTag;
27213     function isJSDocParameterTag(node) {
27214         return node.kind === 326 /* JSDocParameterTag */;
27215     }
27216     ts.isJSDocParameterTag = isJSDocParameterTag;
27217     function isJSDocReturnTag(node) {
27218         return node.kind === 327 /* JSDocReturnTag */;
27219     }
27220     ts.isJSDocReturnTag = isJSDocReturnTag;
27221     function isJSDocThisTag(node) {
27222         return node.kind === 328 /* JSDocThisTag */;
27223     }
27224     ts.isJSDocThisTag = isJSDocThisTag;
27225     function isJSDocTypeTag(node) {
27226         return node.kind === 329 /* JSDocTypeTag */;
27227     }
27228     ts.isJSDocTypeTag = isJSDocTypeTag;
27229     function isJSDocTemplateTag(node) {
27230         return node.kind === 330 /* JSDocTemplateTag */;
27231     }
27232     ts.isJSDocTemplateTag = isJSDocTemplateTag;
27233     function isJSDocTypedefTag(node) {
27234         return node.kind === 331 /* JSDocTypedefTag */;
27235     }
27236     ts.isJSDocTypedefTag = isJSDocTypedefTag;
27237     function isJSDocUnknownTag(node) {
27238         return node.kind === 314 /* JSDocTag */;
27239     }
27240     ts.isJSDocUnknownTag = isJSDocUnknownTag;
27241     function isJSDocPropertyTag(node) {
27242         return node.kind === 333 /* JSDocPropertyTag */;
27243     }
27244     ts.isJSDocPropertyTag = isJSDocPropertyTag;
27245     function isJSDocImplementsTag(node) {
27246         return node.kind === 316 /* JSDocImplementsTag */;
27247     }
27248     ts.isJSDocImplementsTag = isJSDocImplementsTag;
27249     // Synthesized list
27250     /* @internal */
27251     function isSyntaxList(n) {
27252         return n.kind === 334 /* SyntaxList */;
27253     }
27254     ts.isSyntaxList = isSyntaxList;
27255 })(ts || (ts = {}));
27256 /* @internal */
27257 var ts;
27258 (function (ts) {
27259     // Compound nodes
27260     function createEmptyExports(factory) {
27261         return factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined);
27262     }
27263     ts.createEmptyExports = createEmptyExports;
27264     function createMemberAccessForPropertyName(factory, target, memberName, location) {
27265         if (ts.isComputedPropertyName(memberName)) {
27266             return ts.setTextRange(factory.createElementAccessExpression(target, memberName.expression), location);
27267         }
27268         else {
27269             var expression = ts.setTextRange(ts.isIdentifierOrPrivateIdentifier(memberName)
27270                 ? factory.createPropertyAccessExpression(target, memberName)
27271                 : factory.createElementAccessExpression(target, memberName), memberName);
27272             ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
27273             return expression;
27274         }
27275     }
27276     ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
27277     function createReactNamespace(reactNamespace, parent) {
27278         // To ensure the emit resolver can properly resolve the namespace, we need to
27279         // treat this identifier as if it were a source tree node by clearing the `Synthesized`
27280         // flag and setting a parent node.
27281         var react = ts.parseNodeFactory.createIdentifier(reactNamespace || "React");
27282         // Set the parent that is in parse tree
27283         // this makes sure that parent chain is intact for checker to traverse complete scope tree
27284         ts.setParent(react, ts.getParseTreeNode(parent));
27285         return react;
27286     }
27287     function createJsxFactoryExpressionFromEntityName(factory, jsxFactory, parent) {
27288         if (ts.isQualifiedName(jsxFactory)) {
27289             var left = createJsxFactoryExpressionFromEntityName(factory, jsxFactory.left, parent);
27290             var right = factory.createIdentifier(ts.idText(jsxFactory.right));
27291             right.escapedText = jsxFactory.right.escapedText;
27292             return factory.createPropertyAccessExpression(left, right);
27293         }
27294         else {
27295             return createReactNamespace(ts.idText(jsxFactory), parent);
27296         }
27297     }
27298     function createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parent) {
27299         return jsxFactoryEntity ?
27300             createJsxFactoryExpressionFromEntityName(factory, jsxFactoryEntity, parent) :
27301             factory.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent), "createElement");
27302     }
27303     ts.createJsxFactoryExpression = createJsxFactoryExpression;
27304     function createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parent) {
27305         return jsxFragmentFactoryEntity ?
27306             createJsxFactoryExpressionFromEntityName(factory, jsxFragmentFactoryEntity, parent) :
27307             factory.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent), "Fragment");
27308     }
27309     function createExpressionForJsxElement(factory, callee, tagName, props, children, location) {
27310         var argumentsList = [tagName];
27311         if (props) {
27312             argumentsList.push(props);
27313         }
27314         if (children && children.length > 0) {
27315             if (!props) {
27316                 argumentsList.push(factory.createNull());
27317             }
27318             if (children.length > 1) {
27319                 for (var _i = 0, children_3 = children; _i < children_3.length; _i++) {
27320                     var child = children_3[_i];
27321                     startOnNewLine(child);
27322                     argumentsList.push(child);
27323                 }
27324             }
27325             else {
27326                 argumentsList.push(children[0]);
27327             }
27328         }
27329         return ts.setTextRange(factory.createCallExpression(callee, 
27330         /*typeArguments*/ undefined, argumentsList), location);
27331     }
27332     ts.createExpressionForJsxElement = createExpressionForJsxElement;
27333     function createExpressionForJsxFragment(factory, jsxFactoryEntity, jsxFragmentFactoryEntity, reactNamespace, children, parentElement, location) {
27334         var tagName = createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parentElement);
27335         var argumentsList = [tagName, factory.createNull()];
27336         if (children && children.length > 0) {
27337             if (children.length > 1) {
27338                 for (var _i = 0, children_4 = children; _i < children_4.length; _i++) {
27339                     var child = children_4[_i];
27340                     startOnNewLine(child);
27341                     argumentsList.push(child);
27342                 }
27343             }
27344             else {
27345                 argumentsList.push(children[0]);
27346             }
27347         }
27348         return ts.setTextRange(factory.createCallExpression(createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parentElement), 
27349         /*typeArguments*/ undefined, argumentsList), location);
27350     }
27351     ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
27352     // Utilities
27353     function createForOfBindingStatement(factory, node, boundValue) {
27354         if (ts.isVariableDeclarationList(node)) {
27355             var firstDeclaration = ts.first(node.declarations);
27356             var updatedDeclaration = factory.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, 
27357             /*exclamationToken*/ undefined, 
27358             /*type*/ undefined, boundValue);
27359             return ts.setTextRange(factory.createVariableStatement(
27360             /*modifiers*/ undefined, factory.updateVariableDeclarationList(node, [updatedDeclaration])), 
27361             /*location*/ node);
27362         }
27363         else {
27364             var updatedExpression = ts.setTextRange(factory.createAssignment(node, boundValue), /*location*/ node);
27365             return ts.setTextRange(factory.createExpressionStatement(updatedExpression), /*location*/ node);
27366         }
27367     }
27368     ts.createForOfBindingStatement = createForOfBindingStatement;
27369     function insertLeadingStatement(factory, dest, source) {
27370         if (ts.isBlock(dest)) {
27371             return factory.updateBlock(dest, ts.setTextRange(factory.createNodeArray(__spreadArray([source], dest.statements)), dest.statements));
27372         }
27373         else {
27374             return factory.createBlock(factory.createNodeArray([dest, source]), /*multiLine*/ true);
27375         }
27376     }
27377     ts.insertLeadingStatement = insertLeadingStatement;
27378     function createExpressionFromEntityName(factory, node) {
27379         if (ts.isQualifiedName(node)) {
27380             var left = createExpressionFromEntityName(factory, node.left);
27381             // TODO(rbuckton): Does this need to be parented?
27382             var right = ts.setParent(ts.setTextRange(factory.cloneNode(node.right), node.right), node.right.parent);
27383             return ts.setTextRange(factory.createPropertyAccessExpression(left, right), node);
27384         }
27385         else {
27386             // TODO(rbuckton): Does this need to be parented?
27387             return ts.setParent(ts.setTextRange(factory.cloneNode(node), node), node.parent);
27388         }
27389     }
27390     ts.createExpressionFromEntityName = createExpressionFromEntityName;
27391     function createExpressionForPropertyName(factory, memberName) {
27392         if (ts.isIdentifier(memberName)) {
27393             return factory.createStringLiteralFromNode(memberName);
27394         }
27395         else if (ts.isComputedPropertyName(memberName)) {
27396             // TODO(rbuckton): Does this need to be parented?
27397             return ts.setParent(ts.setTextRange(factory.cloneNode(memberName.expression), memberName.expression), memberName.expression.parent);
27398         }
27399         else {
27400             // TODO(rbuckton): Does this need to be parented?
27401             return ts.setParent(ts.setTextRange(factory.cloneNode(memberName), memberName), memberName.parent);
27402         }
27403     }
27404     ts.createExpressionForPropertyName = createExpressionForPropertyName;
27405     function createExpressionForAccessorDeclaration(factory, properties, property, receiver, multiLine) {
27406         var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
27407         if (property === firstAccessor) {
27408             return ts.setTextRange(factory.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory, property.name), factory.createPropertyDescriptor({
27409                 enumerable: factory.createFalse(),
27410                 configurable: true,
27411                 get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(getAccessor.modifiers, 
27412                 /*asteriskToken*/ undefined, 
27413                 /*name*/ undefined, 
27414                 /*typeParameters*/ undefined, getAccessor.parameters, 
27415                 /*type*/ undefined, getAccessor.body // TODO: GH#18217
27416                 ), getAccessor), getAccessor),
27417                 set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(setAccessor.modifiers, 
27418                 /*asteriskToken*/ undefined, 
27419                 /*name*/ undefined, 
27420                 /*typeParameters*/ undefined, setAccessor.parameters, 
27421                 /*type*/ undefined, setAccessor.body // TODO: GH#18217
27422                 ), setAccessor), setAccessor)
27423             }, !multiLine)), firstAccessor);
27424         }
27425         return undefined;
27426     }
27427     function createExpressionForPropertyAssignment(factory, property, receiver) {
27428         return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), property.initializer), property), property);
27429     }
27430     function createExpressionForShorthandPropertyAssignment(factory, property, receiver) {
27431         return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), factory.cloneNode(property.name)), 
27432         /*location*/ property), 
27433         /*original*/ property);
27434     }
27435     function createExpressionForMethodDeclaration(factory, method, receiver) {
27436         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, 
27437         /*name*/ undefined, 
27438         /*typeParameters*/ undefined, method.parameters, 
27439         /*type*/ undefined, method.body // TODO: GH#18217
27440         ), 
27441         /*location*/ method), 
27442         /*original*/ method)), 
27443         /*location*/ method), 
27444         /*original*/ method);
27445     }
27446     function createExpressionForObjectLiteralElementLike(factory, node, property, receiver) {
27447         if (property.name && ts.isPrivateIdentifier(property.name)) {
27448             ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals.");
27449         }
27450         switch (property.kind) {
27451             case 167 /* GetAccessor */:
27452             case 168 /* SetAccessor */:
27453                 return createExpressionForAccessorDeclaration(factory, node.properties, property, receiver, !!node.multiLine);
27454             case 288 /* PropertyAssignment */:
27455                 return createExpressionForPropertyAssignment(factory, property, receiver);
27456             case 289 /* ShorthandPropertyAssignment */:
27457                 return createExpressionForShorthandPropertyAssignment(factory, property, receiver);
27458             case 165 /* MethodDeclaration */:
27459                 return createExpressionForMethodDeclaration(factory, property, receiver);
27460         }
27461     }
27462     ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
27463     /**
27464      * Gets whether an identifier should only be referred to by its internal name.
27465      */
27466     function isInternalName(node) {
27467         return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
27468     }
27469     ts.isInternalName = isInternalName;
27470     /**
27471      * Gets whether an identifier should only be referred to by its local name.
27472      */
27473     function isLocalName(node) {
27474         return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
27475     }
27476     ts.isLocalName = isLocalName;
27477     /**
27478      * Gets whether an identifier should only be referred to by its export representation if the
27479      * name points to an exported symbol.
27480      */
27481     function isExportName(node) {
27482         return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
27483     }
27484     ts.isExportName = isExportName;
27485     function isUseStrictPrologue(node) {
27486         return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
27487     }
27488     function findUseStrictPrologue(statements) {
27489         for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
27490             var statement = statements_1[_i];
27491             if (ts.isPrologueDirective(statement)) {
27492                 if (isUseStrictPrologue(statement)) {
27493                     return statement;
27494                 }
27495             }
27496             else {
27497                 break;
27498             }
27499         }
27500         return undefined;
27501     }
27502     ts.findUseStrictPrologue = findUseStrictPrologue;
27503     function startsWithUseStrict(statements) {
27504         var firstStatement = ts.firstOrUndefined(statements);
27505         return firstStatement !== undefined
27506             && ts.isPrologueDirective(firstStatement)
27507             && isUseStrictPrologue(firstStatement);
27508     }
27509     ts.startsWithUseStrict = startsWithUseStrict;
27510     function isCommaSequence(node) {
27511         return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
27512             node.kind === 337 /* CommaListExpression */;
27513     }
27514     ts.isCommaSequence = isCommaSequence;
27515     function isOuterExpression(node, kinds) {
27516         if (kinds === void 0) { kinds = 15 /* All */; }
27517         switch (node.kind) {
27518             case 207 /* ParenthesizedExpression */:
27519                 return (kinds & 1 /* Parentheses */) !== 0;
27520             case 206 /* TypeAssertionExpression */:
27521             case 224 /* AsExpression */:
27522                 return (kinds & 2 /* TypeAssertions */) !== 0;
27523             case 225 /* NonNullExpression */:
27524                 return (kinds & 4 /* NonNullAssertions */) !== 0;
27525             case 336 /* PartiallyEmittedExpression */:
27526                 return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0;
27527         }
27528         return false;
27529     }
27530     ts.isOuterExpression = isOuterExpression;
27531     function skipOuterExpressions(node, kinds) {
27532         if (kinds === void 0) { kinds = 15 /* All */; }
27533         while (isOuterExpression(node, kinds)) {
27534             node = node.expression;
27535         }
27536         return node;
27537     }
27538     ts.skipOuterExpressions = skipOuterExpressions;
27539     function skipAssertions(node) {
27540         return skipOuterExpressions(node, 6 /* Assertions */);
27541     }
27542     ts.skipAssertions = skipAssertions;
27543     function startOnNewLine(node) {
27544         return ts.setStartsOnNewLine(node, /*newLine*/ true);
27545     }
27546     ts.startOnNewLine = startOnNewLine;
27547     function getExternalHelpersModuleName(node) {
27548         var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
27549         var emitNode = parseNode && parseNode.emitNode;
27550         return emitNode && emitNode.externalHelpersModuleName;
27551     }
27552     ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
27553     function hasRecordedExternalHelpers(sourceFile) {
27554         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
27555         var emitNode = parseNode && parseNode.emitNode;
27556         return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers);
27557     }
27558     ts.hasRecordedExternalHelpers = hasRecordedExternalHelpers;
27559     function createExternalHelpersImportDeclarationIfNeeded(nodeFactory, helperFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) {
27560         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
27561             var namedBindings = void 0;
27562             var moduleKind = ts.getEmitModuleKind(compilerOptions);
27563             if (moduleKind >= ts.ModuleKind.ES2015 && moduleKind <= ts.ModuleKind.ESNext) {
27564                 // use named imports
27565                 var helpers = ts.getEmitHelpers(sourceFile);
27566                 if (helpers) {
27567                     var helperNames = [];
27568                     for (var _i = 0, helpers_3 = helpers; _i < helpers_3.length; _i++) {
27569                         var helper = helpers_3[_i];
27570                         if (!helper.scoped) {
27571                             var importName = helper.importName;
27572                             if (importName) {
27573                                 ts.pushIfUnique(helperNames, importName);
27574                             }
27575                         }
27576                     }
27577                     if (ts.some(helperNames)) {
27578                         helperNames.sort(ts.compareStringsCaseSensitive);
27579                         // Alias the imports if the names are used somewhere in the file.
27580                         // NOTE: We don't need to care about global import collisions as this is a module.
27581                         namedBindings = nodeFactory.createNamedImports(ts.map(helperNames, function (name) { return ts.isFileLevelUniqueName(sourceFile, name)
27582                             ? nodeFactory.createImportSpecifier(/*propertyName*/ undefined, nodeFactory.createIdentifier(name))
27583                             : nodeFactory.createImportSpecifier(nodeFactory.createIdentifier(name), helperFactory.getUnscopedHelperName(name)); }));
27584                         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
27585                         var emitNode = ts.getOrCreateEmitNode(parseNode);
27586                         emitNode.externalHelpers = true;
27587                     }
27588                 }
27589             }
27590             else {
27591                 // use a namespace import
27592                 var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(nodeFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault);
27593                 if (externalHelpersModuleName) {
27594                     namedBindings = nodeFactory.createNamespaceImport(externalHelpersModuleName);
27595                 }
27596             }
27597             if (namedBindings) {
27598                 var externalHelpersImportDeclaration = nodeFactory.createImportDeclaration(
27599                 /*decorators*/ undefined, 
27600                 /*modifiers*/ undefined, nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), nodeFactory.createStringLiteral(ts.externalHelpersModuleNameText));
27601                 ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
27602                 return externalHelpersImportDeclaration;
27603             }
27604         }
27605     }
27606     ts.createExternalHelpersImportDeclarationIfNeeded = createExternalHelpersImportDeclarationIfNeeded;
27607     function getOrCreateExternalHelpersModuleNameIfNeeded(factory, node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
27608         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
27609             var externalHelpersModuleName = getExternalHelpersModuleName(node);
27610             if (externalHelpersModuleName) {
27611                 return externalHelpersModuleName;
27612             }
27613             var moduleKind = ts.getEmitModuleKind(compilerOptions);
27614             var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
27615                 && moduleKind !== ts.ModuleKind.System
27616                 && moduleKind < ts.ModuleKind.ES2015;
27617             if (!create) {
27618                 var helpers = ts.getEmitHelpers(node);
27619                 if (helpers) {
27620                     for (var _i = 0, helpers_4 = helpers; _i < helpers_4.length; _i++) {
27621                         var helper = helpers_4[_i];
27622                         if (!helper.scoped) {
27623                             create = true;
27624                             break;
27625                         }
27626                     }
27627                 }
27628             }
27629             if (create) {
27630                 var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
27631                 var emitNode = ts.getOrCreateEmitNode(parseNode);
27632                 return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = factory.createUniqueName(ts.externalHelpersModuleNameText));
27633             }
27634         }
27635     }
27636     ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
27637     /**
27638      * Get the name of that target module from an import or export declaration
27639      */
27640     function getLocalNameForExternalImport(factory, node, sourceFile) {
27641         var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
27642         if (namespaceDeclaration && !ts.isDefaultImport(node) && !ts.isExportNamespaceAsDefaultDeclaration(node)) {
27643             var name = namespaceDeclaration.name;
27644             return ts.isGeneratedIdentifier(name) ? name : factory.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
27645         }
27646         if (node.kind === 261 /* ImportDeclaration */ && node.importClause) {
27647             return factory.getGeneratedNameForNode(node);
27648         }
27649         if (node.kind === 267 /* ExportDeclaration */ && node.moduleSpecifier) {
27650             return factory.getGeneratedNameForNode(node);
27651         }
27652         return undefined;
27653     }
27654     ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
27655     /**
27656      * Get the name of a target module from an import/export declaration as should be written in the emitted output.
27657      * The emitted output name can be different from the input if:
27658      *  1. The module has a /// <amd-module name="<new name>" />
27659      *  2. --out or --outFile is used, making the name relative to the rootDir
27660      *  3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
27661      * Otherwise, a new StringLiteral node representing the module name will be returned.
27662      */
27663     function getExternalModuleNameLiteral(factory, importNode, sourceFile, host, resolver, compilerOptions) {
27664         var moduleName = ts.getExternalModuleName(importNode);
27665         if (moduleName && ts.isStringLiteral(moduleName)) {
27666             return tryGetModuleNameFromDeclaration(importNode, host, factory, resolver, compilerOptions)
27667                 || tryRenameExternalModule(factory, moduleName, sourceFile)
27668                 || factory.cloneNode(moduleName);
27669         }
27670         return undefined;
27671     }
27672     ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
27673     /**
27674      * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
27675      * Here we check if alternative name was provided for a given moduleName and return it if possible.
27676      */
27677     function tryRenameExternalModule(factory, moduleName, sourceFile) {
27678         var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
27679         return rename ? factory.createStringLiteral(rename) : undefined;
27680     }
27681     /**
27682      * Get the name of a module as should be written in the emitted output.
27683      * The emitted output name can be different from the input if:
27684      *  1. The module has a /// <amd-module name="<new name>" />
27685      *  2. --out or --outFile is used, making the name relative to the rootDir
27686      * Otherwise, a new StringLiteral node representing the module name will be returned.
27687      */
27688     function tryGetModuleNameFromFile(factory, file, host, options) {
27689         if (!file) {
27690             return undefined;
27691         }
27692         if (file.moduleName) {
27693             return factory.createStringLiteral(file.moduleName);
27694         }
27695         if (!file.isDeclarationFile && ts.outFile(options)) {
27696             return factory.createStringLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
27697         }
27698         return undefined;
27699     }
27700     ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
27701     function tryGetModuleNameFromDeclaration(declaration, host, factory, resolver, compilerOptions) {
27702         return tryGetModuleNameFromFile(factory, resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
27703     }
27704     /**
27705      * Gets the initializer of an BindingOrAssignmentElement.
27706      */
27707     function getInitializerOfBindingOrAssignmentElement(bindingElement) {
27708         if (ts.isDeclarationBindingElement(bindingElement)) {
27709             // `1` in `let { a = 1 } = ...`
27710             // `1` in `let { a: b = 1 } = ...`
27711             // `1` in `let { a: {b} = 1 } = ...`
27712             // `1` in `let { a: [b] = 1 } = ...`
27713             // `1` in `let [a = 1] = ...`
27714             // `1` in `let [{a} = 1] = ...`
27715             // `1` in `let [[a] = 1] = ...`
27716             return bindingElement.initializer;
27717         }
27718         if (ts.isPropertyAssignment(bindingElement)) {
27719             // `1` in `({ a: b = 1 } = ...)`
27720             // `1` in `({ a: {b} = 1 } = ...)`
27721             // `1` in `({ a: [b] = 1 } = ...)`
27722             var initializer = bindingElement.initializer;
27723             return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
27724                 ? initializer.right
27725                 : undefined;
27726         }
27727         if (ts.isShorthandPropertyAssignment(bindingElement)) {
27728             // `1` in `({ a = 1 } = ...)`
27729             return bindingElement.objectAssignmentInitializer;
27730         }
27731         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
27732             // `1` in `[a = 1] = ...`
27733             // `1` in `[{a} = 1] = ...`
27734             // `1` in `[[a] = 1] = ...`
27735             return bindingElement.right;
27736         }
27737         if (ts.isSpreadElement(bindingElement)) {
27738             // Recovery consistent with existing emit.
27739             return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
27740         }
27741     }
27742     ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
27743     /**
27744      * Gets the name of an BindingOrAssignmentElement.
27745      */
27746     function getTargetOfBindingOrAssignmentElement(bindingElement) {
27747         if (ts.isDeclarationBindingElement(bindingElement)) {
27748             // `a` in `let { a } = ...`
27749             // `a` in `let { a = 1 } = ...`
27750             // `b` in `let { a: b } = ...`
27751             // `b` in `let { a: b = 1 } = ...`
27752             // `a` in `let { ...a } = ...`
27753             // `{b}` in `let { a: {b} } = ...`
27754             // `{b}` in `let { a: {b} = 1 } = ...`
27755             // `[b]` in `let { a: [b] } = ...`
27756             // `[b]` in `let { a: [b] = 1 } = ...`
27757             // `a` in `let [a] = ...`
27758             // `a` in `let [a = 1] = ...`
27759             // `a` in `let [...a] = ...`
27760             // `{a}` in `let [{a}] = ...`
27761             // `{a}` in `let [{a} = 1] = ...`
27762             // `[a]` in `let [[a]] = ...`
27763             // `[a]` in `let [[a] = 1] = ...`
27764             return bindingElement.name;
27765         }
27766         if (ts.isObjectLiteralElementLike(bindingElement)) {
27767             switch (bindingElement.kind) {
27768                 case 288 /* PropertyAssignment */:
27769                     // `b` in `({ a: b } = ...)`
27770                     // `b` in `({ a: b = 1 } = ...)`
27771                     // `{b}` in `({ a: {b} } = ...)`
27772                     // `{b}` in `({ a: {b} = 1 } = ...)`
27773                     // `[b]` in `({ a: [b] } = ...)`
27774                     // `[b]` in `({ a: [b] = 1 } = ...)`
27775                     // `b.c` in `({ a: b.c } = ...)`
27776                     // `b.c` in `({ a: b.c = 1 } = ...)`
27777                     // `b[0]` in `({ a: b[0] } = ...)`
27778                     // `b[0]` in `({ a: b[0] = 1 } = ...)`
27779                     return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
27780                 case 289 /* ShorthandPropertyAssignment */:
27781                     // `a` in `({ a } = ...)`
27782                     // `a` in `({ a = 1 } = ...)`
27783                     return bindingElement.name;
27784                 case 290 /* SpreadAssignment */:
27785                     // `a` in `({ ...a } = ...)`
27786                     return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
27787             }
27788             // no target
27789             return undefined;
27790         }
27791         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
27792             // `a` in `[a = 1] = ...`
27793             // `{a}` in `[{a} = 1] = ...`
27794             // `[a]` in `[[a] = 1] = ...`
27795             // `a.b` in `[a.b = 1] = ...`
27796             // `a[0]` in `[a[0] = 1] = ...`
27797             return getTargetOfBindingOrAssignmentElement(bindingElement.left);
27798         }
27799         if (ts.isSpreadElement(bindingElement)) {
27800             // `a` in `[...a] = ...`
27801             return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
27802         }
27803         // `a` in `[a] = ...`
27804         // `{a}` in `[{a}] = ...`
27805         // `[a]` in `[[a]] = ...`
27806         // `a.b` in `[a.b] = ...`
27807         // `a[0]` in `[a[0]] = ...`
27808         return bindingElement;
27809     }
27810     ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
27811     /**
27812      * Determines whether an BindingOrAssignmentElement is a rest element.
27813      */
27814     function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
27815         switch (bindingElement.kind) {
27816             case 160 /* Parameter */:
27817             case 198 /* BindingElement */:
27818                 // `...` in `let [...a] = ...`
27819                 return bindingElement.dotDotDotToken;
27820             case 220 /* SpreadElement */:
27821             case 290 /* SpreadAssignment */:
27822                 // `...` in `[...a] = ...`
27823                 return bindingElement;
27824         }
27825         return undefined;
27826     }
27827     ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
27828     /**
27829      * Gets the property name of a BindingOrAssignmentElement
27830      */
27831     function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
27832         var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement);
27833         ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element.");
27834         return propertyName;
27835     }
27836     ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
27837     function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) {
27838         switch (bindingElement.kind) {
27839             case 198 /* BindingElement */:
27840                 // `a` in `let { a: b } = ...`
27841                 // `[a]` in `let { [a]: b } = ...`
27842                 // `"a"` in `let { "a": b } = ...`
27843                 // `1` in `let { 1: b } = ...`
27844                 if (bindingElement.propertyName) {
27845                     var propertyName = bindingElement.propertyName;
27846                     if (ts.isPrivateIdentifier(propertyName)) {
27847                         return ts.Debug.failBadSyntaxKind(propertyName);
27848                     }
27849                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
27850                         ? propertyName.expression
27851                         : propertyName;
27852                 }
27853                 break;
27854             case 288 /* PropertyAssignment */:
27855                 // `a` in `({ a: b } = ...)`
27856                 // `[a]` in `({ [a]: b } = ...)`
27857                 // `"a"` in `({ "a": b } = ...)`
27858                 // `1` in `({ 1: b } = ...)`
27859                 if (bindingElement.name) {
27860                     var propertyName = bindingElement.name;
27861                     if (ts.isPrivateIdentifier(propertyName)) {
27862                         return ts.Debug.failBadSyntaxKind(propertyName);
27863                     }
27864                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
27865                         ? propertyName.expression
27866                         : propertyName;
27867                 }
27868                 break;
27869             case 290 /* SpreadAssignment */:
27870                 // `a` in `({ ...a } = ...)`
27871                 if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) {
27872                     return ts.Debug.failBadSyntaxKind(bindingElement.name);
27873                 }
27874                 return bindingElement.name;
27875         }
27876         var target = getTargetOfBindingOrAssignmentElement(bindingElement);
27877         if (target && ts.isPropertyName(target)) {
27878             return target;
27879         }
27880     }
27881     ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement;
27882     function isStringOrNumericLiteral(node) {
27883         var kind = node.kind;
27884         return kind === 10 /* StringLiteral */
27885             || kind === 8 /* NumericLiteral */;
27886     }
27887     /**
27888      * Gets the elements of a BindingOrAssignmentPattern
27889      */
27890     function getElementsOfBindingOrAssignmentPattern(name) {
27891         switch (name.kind) {
27892             case 196 /* ObjectBindingPattern */:
27893             case 197 /* ArrayBindingPattern */:
27894             case 199 /* ArrayLiteralExpression */:
27895                 // `a` in `{a}`
27896                 // `a` in `[a]`
27897                 return name.elements;
27898             case 200 /* ObjectLiteralExpression */:
27899                 // `a` in `{a}`
27900                 return name.properties;
27901         }
27902     }
27903     ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;
27904     /* @internal */
27905     function getJSDocTypeAliasName(fullName) {
27906         if (fullName) {
27907             var rightNode = fullName;
27908             while (true) {
27909                 if (ts.isIdentifier(rightNode) || !rightNode.body) {
27910                     return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
27911                 }
27912                 rightNode = rightNode.body;
27913             }
27914         }
27915     }
27916     ts.getJSDocTypeAliasName = getJSDocTypeAliasName;
27917     function canHaveModifiers(node) {
27918         var kind = node.kind;
27919         return kind === 160 /* Parameter */
27920             || kind === 162 /* PropertySignature */
27921             || kind === 163 /* PropertyDeclaration */
27922             || kind === 164 /* MethodSignature */
27923             || kind === 165 /* MethodDeclaration */
27924             || kind === 166 /* Constructor */
27925             || kind === 167 /* GetAccessor */
27926             || kind === 168 /* SetAccessor */
27927             || kind === 171 /* IndexSignature */
27928             || kind === 208 /* FunctionExpression */
27929             || kind === 209 /* ArrowFunction */
27930             || kind === 221 /* ClassExpression */
27931             || kind === 232 /* VariableStatement */
27932             || kind === 251 /* FunctionDeclaration */
27933             || kind === 252 /* ClassDeclaration */
27934             || kind === 253 /* InterfaceDeclaration */
27935             || kind === 254 /* TypeAliasDeclaration */
27936             || kind === 255 /* EnumDeclaration */
27937             || kind === 256 /* ModuleDeclaration */
27938             || kind === 260 /* ImportEqualsDeclaration */
27939             || kind === 261 /* ImportDeclaration */
27940             || kind === 266 /* ExportAssignment */
27941             || kind === 267 /* ExportDeclaration */;
27942     }
27943     ts.canHaveModifiers = canHaveModifiers;
27944     /* @internal */
27945     function isExportModifier(node) {
27946         return node.kind === 92 /* ExportKeyword */;
27947     }
27948     ts.isExportModifier = isExportModifier;
27949     /* @internal */
27950     function isAsyncModifier(node) {
27951         return node.kind === 129 /* AsyncKeyword */;
27952     }
27953     ts.isAsyncModifier = isAsyncModifier;
27954     /* @internal */
27955     function isStaticModifier(node) {
27956         return node.kind === 123 /* StaticKeyword */;
27957     }
27958     ts.isStaticModifier = isStaticModifier;
27959 })(ts || (ts = {}));
27960 var ts;
27961 (function (ts) {
27962     function setTextRange(range, location) {
27963         return location ? ts.setTextRangePosEnd(range, location.pos, location.end) : range;
27964     }
27965     ts.setTextRange = setTextRange;
27966 })(ts || (ts = {}));
27967 var ts;
27968 (function (ts) {
27969     var SignatureFlags;
27970     (function (SignatureFlags) {
27971         SignatureFlags[SignatureFlags["None"] = 0] = "None";
27972         SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
27973         SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
27974         SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
27975         SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
27976         SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
27977     })(SignatureFlags || (SignatureFlags = {}));
27978     var SpeculationKind;
27979     (function (SpeculationKind) {
27980         SpeculationKind[SpeculationKind["TryParse"] = 0] = "TryParse";
27981         SpeculationKind[SpeculationKind["Lookahead"] = 1] = "Lookahead";
27982         SpeculationKind[SpeculationKind["Reparse"] = 2] = "Reparse";
27983     })(SpeculationKind || (SpeculationKind = {}));
27984     var NodeConstructor;
27985     var TokenConstructor;
27986     var IdentifierConstructor;
27987     var PrivateIdentifierConstructor;
27988     var SourceFileConstructor;
27989     /**
27990      * NOTE: You should not use this, it is only exported to support `createNode` in `~/src/deprecatedCompat/deprecations.ts`.
27991      */
27992     /* @internal */
27993     ts.parseBaseNodeFactory = {
27994         createBaseSourceFileNode: function (kind) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, -1, -1); },
27995         createBaseIdentifierNode: function (kind) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, -1, -1); },
27996         createBasePrivateIdentifierNode: function (kind) { return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, -1, -1); },
27997         createBaseTokenNode: function (kind) { return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, -1, -1); },
27998         createBaseNode: function (kind) { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, -1, -1); },
27999     };
28000     /* @internal */
28001     ts.parseNodeFactory = ts.createNodeFactory(1 /* NoParenthesizerRules */, ts.parseBaseNodeFactory);
28002     function visitNode(cbNode, node) {
28003         return node && cbNode(node);
28004     }
28005     function visitNodes(cbNode, cbNodes, nodes) {
28006         if (nodes) {
28007             if (cbNodes) {
28008                 return cbNodes(nodes);
28009             }
28010             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
28011                 var node = nodes_1[_i];
28012                 var result = cbNode(node);
28013                 if (result) {
28014                     return result;
28015                 }
28016             }
28017         }
28018     }
28019     /*@internal*/
28020     function isJSDocLikeText(text, start) {
28021         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
28022             text.charCodeAt(start + 2) === 42 /* asterisk */ &&
28023             text.charCodeAt(start + 3) !== 47 /* slash */;
28024     }
28025     ts.isJSDocLikeText = isJSDocLikeText;
28026     /**
28027      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
28028      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
28029      * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
28030      * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
28031      *
28032      * @param node a given node to visit its children
28033      * @param cbNode a callback to be invoked for all child nodes
28034      * @param cbNodes a callback to be invoked for embedded array
28035      *
28036      * @remarks `forEachChild` must visit the children of a node in the order
28037      * that they appear in the source code. The language service depends on this property to locate nodes by position.
28038      */
28039     function forEachChild(node, cbNode, cbNodes) {
28040         if (!node || node.kind <= 156 /* LastToken */) {
28041             return;
28042         }
28043         switch (node.kind) {
28044             case 157 /* QualifiedName */:
28045                 return visitNode(cbNode, node.left) ||
28046                     visitNode(cbNode, node.right);
28047             case 159 /* TypeParameter */:
28048                 return visitNode(cbNode, node.name) ||
28049                     visitNode(cbNode, node.constraint) ||
28050                     visitNode(cbNode, node.default) ||
28051                     visitNode(cbNode, node.expression);
28052             case 289 /* ShorthandPropertyAssignment */:
28053                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28054                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28055                     visitNode(cbNode, node.name) ||
28056                     visitNode(cbNode, node.questionToken) ||
28057                     visitNode(cbNode, node.exclamationToken) ||
28058                     visitNode(cbNode, node.equalsToken) ||
28059                     visitNode(cbNode, node.objectAssignmentInitializer);
28060             case 290 /* SpreadAssignment */:
28061                 return visitNode(cbNode, node.expression);
28062             case 160 /* Parameter */:
28063                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28064                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28065                     visitNode(cbNode, node.dotDotDotToken) ||
28066                     visitNode(cbNode, node.name) ||
28067                     visitNode(cbNode, node.questionToken) ||
28068                     visitNode(cbNode, node.type) ||
28069                     visitNode(cbNode, node.initializer);
28070             case 163 /* PropertyDeclaration */:
28071                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28072                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28073                     visitNode(cbNode, node.name) ||
28074                     visitNode(cbNode, node.questionToken) ||
28075                     visitNode(cbNode, node.exclamationToken) ||
28076                     visitNode(cbNode, node.type) ||
28077                     visitNode(cbNode, node.initializer);
28078             case 162 /* PropertySignature */:
28079                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28080                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28081                     visitNode(cbNode, node.name) ||
28082                     visitNode(cbNode, node.questionToken) ||
28083                     visitNode(cbNode, node.type) ||
28084                     visitNode(cbNode, node.initializer);
28085             case 288 /* PropertyAssignment */:
28086                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28087                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28088                     visitNode(cbNode, node.name) ||
28089                     visitNode(cbNode, node.questionToken) ||
28090                     visitNode(cbNode, node.initializer);
28091             case 249 /* VariableDeclaration */:
28092                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28093                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28094                     visitNode(cbNode, node.name) ||
28095                     visitNode(cbNode, node.exclamationToken) ||
28096                     visitNode(cbNode, node.type) ||
28097                     visitNode(cbNode, node.initializer);
28098             case 198 /* BindingElement */:
28099                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28100                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28101                     visitNode(cbNode, node.dotDotDotToken) ||
28102                     visitNode(cbNode, node.propertyName) ||
28103                     visitNode(cbNode, node.name) ||
28104                     visitNode(cbNode, node.initializer);
28105             case 174 /* FunctionType */:
28106             case 175 /* ConstructorType */:
28107             case 169 /* CallSignature */:
28108             case 170 /* ConstructSignature */:
28109             case 171 /* IndexSignature */:
28110                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28111                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28112                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
28113                     visitNodes(cbNode, cbNodes, node.parameters) ||
28114                     visitNode(cbNode, node.type);
28115             case 165 /* MethodDeclaration */:
28116             case 164 /* MethodSignature */:
28117             case 166 /* Constructor */:
28118             case 167 /* GetAccessor */:
28119             case 168 /* SetAccessor */:
28120             case 208 /* FunctionExpression */:
28121             case 251 /* FunctionDeclaration */:
28122             case 209 /* ArrowFunction */:
28123                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28124                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28125                     visitNode(cbNode, node.asteriskToken) ||
28126                     visitNode(cbNode, node.name) ||
28127                     visitNode(cbNode, node.questionToken) ||
28128                     visitNode(cbNode, node.exclamationToken) ||
28129                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
28130                     visitNodes(cbNode, cbNodes, node.parameters) ||
28131                     visitNode(cbNode, node.type) ||
28132                     visitNode(cbNode, node.equalsGreaterThanToken) ||
28133                     visitNode(cbNode, node.body);
28134             case 173 /* TypeReference */:
28135                 return visitNode(cbNode, node.typeName) ||
28136                     visitNodes(cbNode, cbNodes, node.typeArguments);
28137             case 172 /* TypePredicate */:
28138                 return visitNode(cbNode, node.assertsModifier) ||
28139                     visitNode(cbNode, node.parameterName) ||
28140                     visitNode(cbNode, node.type);
28141             case 176 /* TypeQuery */:
28142                 return visitNode(cbNode, node.exprName);
28143             case 177 /* TypeLiteral */:
28144                 return visitNodes(cbNode, cbNodes, node.members);
28145             case 178 /* ArrayType */:
28146                 return visitNode(cbNode, node.elementType);
28147             case 179 /* TupleType */:
28148                 return visitNodes(cbNode, cbNodes, node.elements);
28149             case 182 /* UnionType */:
28150             case 183 /* IntersectionType */:
28151                 return visitNodes(cbNode, cbNodes, node.types);
28152             case 184 /* ConditionalType */:
28153                 return visitNode(cbNode, node.checkType) ||
28154                     visitNode(cbNode, node.extendsType) ||
28155                     visitNode(cbNode, node.trueType) ||
28156                     visitNode(cbNode, node.falseType);
28157             case 185 /* InferType */:
28158                 return visitNode(cbNode, node.typeParameter);
28159             case 195 /* ImportType */:
28160                 return visitNode(cbNode, node.argument) ||
28161                     visitNode(cbNode, node.qualifier) ||
28162                     visitNodes(cbNode, cbNodes, node.typeArguments);
28163             case 186 /* ParenthesizedType */:
28164             case 188 /* TypeOperator */:
28165                 return visitNode(cbNode, node.type);
28166             case 189 /* IndexedAccessType */:
28167                 return visitNode(cbNode, node.objectType) ||
28168                     visitNode(cbNode, node.indexType);
28169             case 190 /* MappedType */:
28170                 return visitNode(cbNode, node.readonlyToken) ||
28171                     visitNode(cbNode, node.typeParameter) ||
28172                     visitNode(cbNode, node.nameType) ||
28173                     visitNode(cbNode, node.questionToken) ||
28174                     visitNode(cbNode, node.type);
28175             case 191 /* LiteralType */:
28176                 return visitNode(cbNode, node.literal);
28177             case 192 /* NamedTupleMember */:
28178                 return visitNode(cbNode, node.dotDotDotToken) ||
28179                     visitNode(cbNode, node.name) ||
28180                     visitNode(cbNode, node.questionToken) ||
28181                     visitNode(cbNode, node.type);
28182             case 196 /* ObjectBindingPattern */:
28183             case 197 /* ArrayBindingPattern */:
28184                 return visitNodes(cbNode, cbNodes, node.elements);
28185             case 199 /* ArrayLiteralExpression */:
28186                 return visitNodes(cbNode, cbNodes, node.elements);
28187             case 200 /* ObjectLiteralExpression */:
28188                 return visitNodes(cbNode, cbNodes, node.properties);
28189             case 201 /* PropertyAccessExpression */:
28190                 return visitNode(cbNode, node.expression) ||
28191                     visitNode(cbNode, node.questionDotToken) ||
28192                     visitNode(cbNode, node.name);
28193             case 202 /* ElementAccessExpression */:
28194                 return visitNode(cbNode, node.expression) ||
28195                     visitNode(cbNode, node.questionDotToken) ||
28196                     visitNode(cbNode, node.argumentExpression);
28197             case 203 /* CallExpression */:
28198             case 204 /* NewExpression */:
28199                 return visitNode(cbNode, node.expression) ||
28200                     visitNode(cbNode, node.questionDotToken) ||
28201                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
28202                     visitNodes(cbNode, cbNodes, node.arguments);
28203             case 205 /* TaggedTemplateExpression */:
28204                 return visitNode(cbNode, node.tag) ||
28205                     visitNode(cbNode, node.questionDotToken) ||
28206                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
28207                     visitNode(cbNode, node.template);
28208             case 206 /* TypeAssertionExpression */:
28209                 return visitNode(cbNode, node.type) ||
28210                     visitNode(cbNode, node.expression);
28211             case 207 /* ParenthesizedExpression */:
28212                 return visitNode(cbNode, node.expression);
28213             case 210 /* DeleteExpression */:
28214                 return visitNode(cbNode, node.expression);
28215             case 211 /* TypeOfExpression */:
28216                 return visitNode(cbNode, node.expression);
28217             case 212 /* VoidExpression */:
28218                 return visitNode(cbNode, node.expression);
28219             case 214 /* PrefixUnaryExpression */:
28220                 return visitNode(cbNode, node.operand);
28221             case 219 /* YieldExpression */:
28222                 return visitNode(cbNode, node.asteriskToken) ||
28223                     visitNode(cbNode, node.expression);
28224             case 213 /* AwaitExpression */:
28225                 return visitNode(cbNode, node.expression);
28226             case 215 /* PostfixUnaryExpression */:
28227                 return visitNode(cbNode, node.operand);
28228             case 216 /* BinaryExpression */:
28229                 return visitNode(cbNode, node.left) ||
28230                     visitNode(cbNode, node.operatorToken) ||
28231                     visitNode(cbNode, node.right);
28232             case 224 /* AsExpression */:
28233                 return visitNode(cbNode, node.expression) ||
28234                     visitNode(cbNode, node.type);
28235             case 225 /* NonNullExpression */:
28236                 return visitNode(cbNode, node.expression);
28237             case 226 /* MetaProperty */:
28238                 return visitNode(cbNode, node.name);
28239             case 217 /* ConditionalExpression */:
28240                 return visitNode(cbNode, node.condition) ||
28241                     visitNode(cbNode, node.questionToken) ||
28242                     visitNode(cbNode, node.whenTrue) ||
28243                     visitNode(cbNode, node.colonToken) ||
28244                     visitNode(cbNode, node.whenFalse);
28245             case 220 /* SpreadElement */:
28246                 return visitNode(cbNode, node.expression);
28247             case 230 /* Block */:
28248             case 257 /* ModuleBlock */:
28249                 return visitNodes(cbNode, cbNodes, node.statements);
28250             case 297 /* SourceFile */:
28251                 return visitNodes(cbNode, cbNodes, node.statements) ||
28252                     visitNode(cbNode, node.endOfFileToken);
28253             case 232 /* VariableStatement */:
28254                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28255                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28256                     visitNode(cbNode, node.declarationList);
28257             case 250 /* VariableDeclarationList */:
28258                 return visitNodes(cbNode, cbNodes, node.declarations);
28259             case 233 /* ExpressionStatement */:
28260                 return visitNode(cbNode, node.expression);
28261             case 234 /* IfStatement */:
28262                 return visitNode(cbNode, node.expression) ||
28263                     visitNode(cbNode, node.thenStatement) ||
28264                     visitNode(cbNode, node.elseStatement);
28265             case 235 /* DoStatement */:
28266                 return visitNode(cbNode, node.statement) ||
28267                     visitNode(cbNode, node.expression);
28268             case 236 /* WhileStatement */:
28269                 return visitNode(cbNode, node.expression) ||
28270                     visitNode(cbNode, node.statement);
28271             case 237 /* ForStatement */:
28272                 return visitNode(cbNode, node.initializer) ||
28273                     visitNode(cbNode, node.condition) ||
28274                     visitNode(cbNode, node.incrementor) ||
28275                     visitNode(cbNode, node.statement);
28276             case 238 /* ForInStatement */:
28277                 return visitNode(cbNode, node.initializer) ||
28278                     visitNode(cbNode, node.expression) ||
28279                     visitNode(cbNode, node.statement);
28280             case 239 /* ForOfStatement */:
28281                 return visitNode(cbNode, node.awaitModifier) ||
28282                     visitNode(cbNode, node.initializer) ||
28283                     visitNode(cbNode, node.expression) ||
28284                     visitNode(cbNode, node.statement);
28285             case 240 /* ContinueStatement */:
28286             case 241 /* BreakStatement */:
28287                 return visitNode(cbNode, node.label);
28288             case 242 /* ReturnStatement */:
28289                 return visitNode(cbNode, node.expression);
28290             case 243 /* WithStatement */:
28291                 return visitNode(cbNode, node.expression) ||
28292                     visitNode(cbNode, node.statement);
28293             case 244 /* SwitchStatement */:
28294                 return visitNode(cbNode, node.expression) ||
28295                     visitNode(cbNode, node.caseBlock);
28296             case 258 /* CaseBlock */:
28297                 return visitNodes(cbNode, cbNodes, node.clauses);
28298             case 284 /* CaseClause */:
28299                 return visitNode(cbNode, node.expression) ||
28300                     visitNodes(cbNode, cbNodes, node.statements);
28301             case 285 /* DefaultClause */:
28302                 return visitNodes(cbNode, cbNodes, node.statements);
28303             case 245 /* LabeledStatement */:
28304                 return visitNode(cbNode, node.label) ||
28305                     visitNode(cbNode, node.statement);
28306             case 246 /* ThrowStatement */:
28307                 return visitNode(cbNode, node.expression);
28308             case 247 /* TryStatement */:
28309                 return visitNode(cbNode, node.tryBlock) ||
28310                     visitNode(cbNode, node.catchClause) ||
28311                     visitNode(cbNode, node.finallyBlock);
28312             case 287 /* CatchClause */:
28313                 return visitNode(cbNode, node.variableDeclaration) ||
28314                     visitNode(cbNode, node.block);
28315             case 161 /* Decorator */:
28316                 return visitNode(cbNode, node.expression);
28317             case 252 /* ClassDeclaration */:
28318             case 221 /* ClassExpression */:
28319                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28320                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28321                     visitNode(cbNode, node.name) ||
28322                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
28323                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
28324                     visitNodes(cbNode, cbNodes, node.members);
28325             case 253 /* InterfaceDeclaration */:
28326                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28327                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28328                     visitNode(cbNode, node.name) ||
28329                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
28330                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
28331                     visitNodes(cbNode, cbNodes, node.members);
28332             case 254 /* TypeAliasDeclaration */:
28333                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28334                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28335                     visitNode(cbNode, node.name) ||
28336                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
28337                     visitNode(cbNode, node.type);
28338             case 255 /* EnumDeclaration */:
28339                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28340                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28341                     visitNode(cbNode, node.name) ||
28342                     visitNodes(cbNode, cbNodes, node.members);
28343             case 291 /* EnumMember */:
28344                 return visitNode(cbNode, node.name) ||
28345                     visitNode(cbNode, node.initializer);
28346             case 256 /* ModuleDeclaration */:
28347                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28348                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28349                     visitNode(cbNode, node.name) ||
28350                     visitNode(cbNode, node.body);
28351             case 260 /* ImportEqualsDeclaration */:
28352                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28353                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28354                     visitNode(cbNode, node.name) ||
28355                     visitNode(cbNode, node.moduleReference);
28356             case 261 /* ImportDeclaration */:
28357                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28358                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28359                     visitNode(cbNode, node.importClause) ||
28360                     visitNode(cbNode, node.moduleSpecifier);
28361             case 262 /* ImportClause */:
28362                 return visitNode(cbNode, node.name) ||
28363                     visitNode(cbNode, node.namedBindings);
28364             case 259 /* NamespaceExportDeclaration */:
28365                 return visitNode(cbNode, node.name);
28366             case 263 /* NamespaceImport */:
28367                 return visitNode(cbNode, node.name);
28368             case 269 /* NamespaceExport */:
28369                 return visitNode(cbNode, node.name);
28370             case 264 /* NamedImports */:
28371             case 268 /* NamedExports */:
28372                 return visitNodes(cbNode, cbNodes, node.elements);
28373             case 267 /* ExportDeclaration */:
28374                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28375                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28376                     visitNode(cbNode, node.exportClause) ||
28377                     visitNode(cbNode, node.moduleSpecifier);
28378             case 265 /* ImportSpecifier */:
28379             case 270 /* ExportSpecifier */:
28380                 return visitNode(cbNode, node.propertyName) ||
28381                     visitNode(cbNode, node.name);
28382             case 266 /* ExportAssignment */:
28383                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28384                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28385                     visitNode(cbNode, node.expression);
28386             case 218 /* TemplateExpression */:
28387                 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
28388             case 228 /* TemplateSpan */:
28389                 return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
28390             case 193 /* TemplateLiteralType */:
28391                 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
28392             case 194 /* TemplateLiteralTypeSpan */:
28393                 return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal);
28394             case 158 /* ComputedPropertyName */:
28395                 return visitNode(cbNode, node.expression);
28396             case 286 /* HeritageClause */:
28397                 return visitNodes(cbNode, cbNodes, node.types);
28398             case 223 /* ExpressionWithTypeArguments */:
28399                 return visitNode(cbNode, node.expression) ||
28400                     visitNodes(cbNode, cbNodes, node.typeArguments);
28401             case 272 /* ExternalModuleReference */:
28402                 return visitNode(cbNode, node.expression);
28403             case 271 /* MissingDeclaration */:
28404                 return visitNodes(cbNode, cbNodes, node.decorators);
28405             case 337 /* CommaListExpression */:
28406                 return visitNodes(cbNode, cbNodes, node.elements);
28407             case 273 /* JsxElement */:
28408                 return visitNode(cbNode, node.openingElement) ||
28409                     visitNodes(cbNode, cbNodes, node.children) ||
28410                     visitNode(cbNode, node.closingElement);
28411             case 277 /* JsxFragment */:
28412                 return visitNode(cbNode, node.openingFragment) ||
28413                     visitNodes(cbNode, cbNodes, node.children) ||
28414                     visitNode(cbNode, node.closingFragment);
28415             case 274 /* JsxSelfClosingElement */:
28416             case 275 /* JsxOpeningElement */:
28417                 return visitNode(cbNode, node.tagName) ||
28418                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
28419                     visitNode(cbNode, node.attributes);
28420             case 281 /* JsxAttributes */:
28421                 return visitNodes(cbNode, cbNodes, node.properties);
28422             case 280 /* JsxAttribute */:
28423                 return visitNode(cbNode, node.name) ||
28424                     visitNode(cbNode, node.initializer);
28425             case 282 /* JsxSpreadAttribute */:
28426                 return visitNode(cbNode, node.expression);
28427             case 283 /* JsxExpression */:
28428                 return visitNode(cbNode, node.dotDotDotToken) ||
28429                     visitNode(cbNode, node.expression);
28430             case 276 /* JsxClosingElement */:
28431                 return visitNode(cbNode, node.tagName);
28432             case 180 /* OptionalType */:
28433             case 181 /* RestType */:
28434             case 301 /* JSDocTypeExpression */:
28435             case 306 /* JSDocNonNullableType */:
28436             case 305 /* JSDocNullableType */:
28437             case 307 /* JSDocOptionalType */:
28438             case 309 /* JSDocVariadicType */:
28439                 return visitNode(cbNode, node.type);
28440             case 308 /* JSDocFunctionType */:
28441                 return visitNodes(cbNode, cbNodes, node.parameters) ||
28442                     visitNode(cbNode, node.type);
28443             case 311 /* JSDocComment */:
28444                 return visitNodes(cbNode, cbNodes, node.tags);
28445             case 332 /* JSDocSeeTag */:
28446                 return visitNode(cbNode, node.tagName) ||
28447                     visitNode(cbNode, node.name);
28448             case 302 /* JSDocNameReference */:
28449                 return visitNode(cbNode, node.name);
28450             case 326 /* JSDocParameterTag */:
28451             case 333 /* JSDocPropertyTag */:
28452                 return visitNode(cbNode, node.tagName) ||
28453                     (node.isNameFirst
28454                         ? visitNode(cbNode, node.name) ||
28455                             visitNode(cbNode, node.typeExpression)
28456                         : visitNode(cbNode, node.typeExpression) ||
28457                             visitNode(cbNode, node.name));
28458             case 317 /* JSDocAuthorTag */:
28459                 return visitNode(cbNode, node.tagName);
28460             case 316 /* JSDocImplementsTag */:
28461                 return visitNode(cbNode, node.tagName) ||
28462                     visitNode(cbNode, node.class);
28463             case 315 /* JSDocAugmentsTag */:
28464                 return visitNode(cbNode, node.tagName) ||
28465                     visitNode(cbNode, node.class);
28466             case 330 /* JSDocTemplateTag */:
28467                 return visitNode(cbNode, node.tagName) ||
28468                     visitNode(cbNode, node.constraint) ||
28469                     visitNodes(cbNode, cbNodes, node.typeParameters);
28470             case 331 /* JSDocTypedefTag */:
28471                 return visitNode(cbNode, node.tagName) ||
28472                     (node.typeExpression &&
28473                         node.typeExpression.kind === 301 /* JSDocTypeExpression */
28474                         ? visitNode(cbNode, node.typeExpression) ||
28475                             visitNode(cbNode, node.fullName)
28476                         : visitNode(cbNode, node.fullName) ||
28477                             visitNode(cbNode, node.typeExpression));
28478             case 324 /* JSDocCallbackTag */:
28479                 return visitNode(cbNode, node.tagName) ||
28480                     visitNode(cbNode, node.fullName) ||
28481                     visitNode(cbNode, node.typeExpression);
28482             case 327 /* JSDocReturnTag */:
28483             case 329 /* JSDocTypeTag */:
28484             case 328 /* JSDocThisTag */:
28485             case 325 /* JSDocEnumTag */:
28486                 return visitNode(cbNode, node.tagName) ||
28487                     visitNode(cbNode, node.typeExpression);
28488             case 313 /* JSDocSignature */:
28489                 return ts.forEach(node.typeParameters, cbNode) ||
28490                     ts.forEach(node.parameters, cbNode) ||
28491                     visitNode(cbNode, node.type);
28492             case 312 /* JSDocTypeLiteral */:
28493                 return ts.forEach(node.jsDocPropertyTags, cbNode);
28494             case 314 /* JSDocTag */:
28495             case 319 /* JSDocClassTag */:
28496             case 320 /* JSDocPublicTag */:
28497             case 321 /* JSDocPrivateTag */:
28498             case 322 /* JSDocProtectedTag */:
28499             case 323 /* JSDocReadonlyTag */:
28500                 return visitNode(cbNode, node.tagName);
28501             case 336 /* PartiallyEmittedExpression */:
28502                 return visitNode(cbNode, node.expression);
28503         }
28504     }
28505     ts.forEachChild = forEachChild;
28506     /** @internal */
28507     /**
28508      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
28509      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; additionally,
28510      * unlike `forEachChild`, embedded arrays are flattened and the 'cbNode' callback is invoked for each element.
28511      *  If a callback returns a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
28512      *
28513      * @param node a given node to visit its children
28514      * @param cbNode a callback to be invoked for all child nodes
28515      * @param cbNodes a callback to be invoked for embedded array
28516      *
28517      * @remarks Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found,
28518      * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
28519      */
28520     function forEachChildRecursively(rootNode, cbNode, cbNodes) {
28521         var queue = gatherPossibleChildren(rootNode);
28522         var parents = []; // tracks parent references for elements in queue
28523         while (parents.length < queue.length) {
28524             parents.push(rootNode);
28525         }
28526         while (queue.length !== 0) {
28527             var current = queue.pop();
28528             var parent = parents.pop();
28529             if (ts.isArray(current)) {
28530                 if (cbNodes) {
28531                     var res = cbNodes(current, parent);
28532                     if (res) {
28533                         if (res === "skip")
28534                             continue;
28535                         return res;
28536                     }
28537                 }
28538                 for (var i = current.length - 1; i >= 0; --i) {
28539                     queue.push(current[i]);
28540                     parents.push(parent);
28541                 }
28542             }
28543             else {
28544                 var res = cbNode(current, parent);
28545                 if (res) {
28546                     if (res === "skip")
28547                         continue;
28548                     return res;
28549                 }
28550                 if (current.kind >= 157 /* FirstNode */) {
28551                     // add children in reverse order to the queue, so popping gives the first child
28552                     for (var _i = 0, _a = gatherPossibleChildren(current); _i < _a.length; _i++) {
28553                         var child = _a[_i];
28554                         queue.push(child);
28555                         parents.push(current);
28556                     }
28557                 }
28558             }
28559         }
28560     }
28561     ts.forEachChildRecursively = forEachChildRecursively;
28562     function gatherPossibleChildren(node) {
28563         var children = [];
28564         forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
28565         return children;
28566         function addWorkItem(n) {
28567             children.unshift(n);
28568         }
28569     }
28570     function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
28571         if (setParentNodes === void 0) { setParentNodes = false; }
28572         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true);
28573         ts.performance.mark("beforeParse");
28574         var result;
28575         ts.perfLogger.logStartParseSourceFile(fileName);
28576         if (languageVersion === 100 /* JSON */) {
28577             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
28578         }
28579         else {
28580             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
28581         }
28582         ts.perfLogger.logStopParseSourceFile();
28583         ts.performance.mark("afterParse");
28584         ts.performance.measure("Parse", "beforeParse", "afterParse");
28585         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
28586         return result;
28587     }
28588     ts.createSourceFile = createSourceFile;
28589     function parseIsolatedEntityName(text, languageVersion) {
28590         return Parser.parseIsolatedEntityName(text, languageVersion);
28591     }
28592     ts.parseIsolatedEntityName = parseIsolatedEntityName;
28593     /**
28594      * Parse json text into SyntaxTree and return node and parse errors if any
28595      * @param fileName
28596      * @param sourceText
28597      */
28598     function parseJsonText(fileName, sourceText) {
28599         return Parser.parseJsonText(fileName, sourceText);
28600     }
28601     ts.parseJsonText = parseJsonText;
28602     // See also `isExternalOrCommonJsModule` in utilities.ts
28603     function isExternalModule(file) {
28604         return file.externalModuleIndicator !== undefined;
28605     }
28606     ts.isExternalModule = isExternalModule;
28607     // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
28608     // indicates what changed between the 'text' that this SourceFile has and the 'newText'.
28609     // The SourceFile will be created with the compiler attempting to reuse as many nodes from
28610     // this file as possible.
28611     //
28612     // Note: this function mutates nodes from this SourceFile. That means any existing nodes
28613     // from this SourceFile that are being held onto may change as a result (including
28614     // becoming detached from any SourceFile).  It is recommended that this SourceFile not
28615     // be used once 'update' is called on it.
28616     function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
28617         if (aggressiveChecks === void 0) { aggressiveChecks = false; }
28618         var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
28619         // 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.
28620         // We will manually port the flag to the new source file.
28621         newSourceFile.flags |= (sourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */);
28622         return newSourceFile;
28623     }
28624     ts.updateSourceFile = updateSourceFile;
28625     /* @internal */
28626     function parseIsolatedJSDocComment(content, start, length) {
28627         var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
28628         if (result && result.jsDoc) {
28629             // because the jsDocComment was parsed out of the source file, it might
28630             // not be covered by the fixupParentReferences.
28631             Parser.fixupParentReferences(result.jsDoc);
28632         }
28633         return result;
28634     }
28635     ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
28636     /* @internal */
28637     // Exposed only for testing.
28638     function parseJSDocTypeExpressionForTests(content, start, length) {
28639         return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
28640     }
28641     ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
28642     // Implement the parser as a singleton module.  We do this for perf reasons because creating
28643     // parser instances can actually be expensive enough to impact us on projects with many source
28644     // files.
28645     var Parser;
28646     (function (Parser) {
28647         // Share a single scanner across all calls to parse a source file.  This helps speed things
28648         // up by avoiding the cost of creating/compiling scanners over and over again.
28649         var scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ true);
28650         var disallowInAndDecoratorContext = 4096 /* DisallowInContext */ | 16384 /* DecoratorContext */;
28651         // capture constructors in 'initializeState' to avoid null checks
28652         // tslint:disable variable-name
28653         var NodeConstructor;
28654         var TokenConstructor;
28655         var IdentifierConstructor;
28656         var PrivateIdentifierConstructor;
28657         var SourceFileConstructor;
28658         // tslint:enable variable-name
28659         function countNode(node) {
28660             nodeCount++;
28661             return node;
28662         }
28663         // Rather than using `createBaseNodeFactory` here, we establish a `BaseNodeFactory` that closes over the
28664         // constructors above, which are reset each time `initializeState` is called.
28665         var baseNodeFactory = {
28666             createBaseSourceFileNode: function (kind) { return countNode(new SourceFileConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
28667             createBaseIdentifierNode: function (kind) { return countNode(new IdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
28668             createBasePrivateIdentifierNode: function (kind) { return countNode(new PrivateIdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
28669             createBaseTokenNode: function (kind) { return countNode(new TokenConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
28670             createBaseNode: function (kind) { return countNode(new NodeConstructor(kind, /*pos*/ 0, /*end*/ 0)); }
28671         };
28672         var factory = ts.createNodeFactory(1 /* NoParenthesizerRules */ | 2 /* NoNodeConverters */ | 8 /* NoOriginalNode */, baseNodeFactory);
28673         var fileName;
28674         var sourceFlags;
28675         var sourceText;
28676         var languageVersion;
28677         var scriptKind;
28678         var languageVariant;
28679         var parseDiagnostics;
28680         var jsDocDiagnostics;
28681         var syntaxCursor;
28682         var currentToken;
28683         var nodeCount;
28684         var identifiers;
28685         var privateIdentifiers;
28686         var identifierCount;
28687         var parsingContext;
28688         var notParenthesizedArrow;
28689         // Flags that dictate what parsing context we're in.  For example:
28690         // Whether or not we are in strict parsing mode.  All that changes in strict parsing mode is
28691         // that some tokens that would be considered identifiers may be considered keywords.
28692         //
28693         // When adding more parser context flags, consider which is the more common case that the
28694         // flag will be in.  This should be the 'false' state for that flag.  The reason for this is
28695         // that we don't store data in our nodes unless the value is in the *non-default* state.  So,
28696         // for example, more often than code 'allows-in' (or doesn't 'disallow-in').  We opt for
28697         // 'disallow-in' set to 'false'.  Otherwise, if we had 'allowsIn' set to 'true', then almost
28698         // all nodes would need extra state on them to store this info.
28699         //
28700         // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
28701         // grammar specification.
28702         //
28703         // An important thing about these context concepts.  By default they are effectively inherited
28704         // while parsing through every grammar production.  i.e. if you don't change them, then when
28705         // you parse a sub-production, it will have the same context values as the parent production.
28706         // This is great most of the time.  After all, consider all the 'expression' grammar productions
28707         // and how nearly all of them pass along the 'in' and 'yield' context values:
28708         //
28709         // EqualityExpression[In, Yield] :
28710         //      RelationalExpression[?In, ?Yield]
28711         //      EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
28712         //      EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
28713         //      EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
28714         //      EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
28715         //
28716         // Where you have to be careful is then understanding what the points are in the grammar
28717         // where the values are *not* passed along.  For example:
28718         //
28719         // SingleNameBinding[Yield,GeneratorParameter]
28720         //      [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
28721         //      [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
28722         //
28723         // Here this is saying that if the GeneratorParameter context flag is set, that we should
28724         // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
28725         // and we should explicitly unset the 'yield' context flag before calling into the Initializer.
28726         // production.  Conversely, if the GeneratorParameter context flag is not set, then we
28727         // should leave the 'yield' context flag alone.
28728         //
28729         // Getting this all correct is tricky and requires careful reading of the grammar to
28730         // understand when these values should be changed versus when they should be inherited.
28731         //
28732         // Note: it should not be necessary to save/restore these flags during speculative/lookahead
28733         // parsing.  These context flags are naturally stored and restored through normal recursive
28734         // descent parsing and unwinding.
28735         var contextFlags;
28736         // Indicates whether we are currently parsing top-level statements.
28737         var topLevel = true;
28738         // Whether or not we've had a parse error since creating the last AST node.  If we have
28739         // encountered an error, it will be stored on the next AST node we create.  Parse errors
28740         // can be broken down into three categories:
28741         //
28742         // 1) An error that occurred during scanning.  For example, an unterminated literal, or a
28743         //    character that was completely not understood.
28744         //
28745         // 2) A token was expected, but was not present.  This type of error is commonly produced
28746         //    by the 'parseExpected' function.
28747         //
28748         // 3) A token was present that no parsing function was able to consume.  This type of error
28749         //    only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
28750         //    decides to skip the token.
28751         //
28752         // In all of these cases, we want to mark the next node as having had an error before it.
28753         // With this mark, we can know in incremental settings if this node can be reused, or if
28754         // we have to reparse it.  If we don't keep this information around, we may just reuse the
28755         // node.  in that event we would then not produce the same errors as we did before, causing
28756         // significant confusion problems.
28757         //
28758         // Note: it is necessary that this value be saved/restored during speculative/lookahead
28759         // parsing.  During lookahead parsing, we will often create a node.  That node will have
28760         // this value attached, and then this value will be set back to 'false'.  If we decide to
28761         // rewind, we must get back to the same value we had prior to the lookahead.
28762         //
28763         // Note: any errors at the end of the file that do not precede a regular node, should get
28764         // attached to the EOF token.
28765         var parseErrorBeforeNextFinishedNode = false;
28766         function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
28767             if (setParentNodes === void 0) { setParentNodes = false; }
28768             scriptKind = ts.ensureScriptKind(fileName, scriptKind);
28769             if (scriptKind === 6 /* JSON */) {
28770                 var result_3 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
28771                 ts.convertToObjectWorker(result_3, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
28772                 result_3.referencedFiles = ts.emptyArray;
28773                 result_3.typeReferenceDirectives = ts.emptyArray;
28774                 result_3.libReferenceDirectives = ts.emptyArray;
28775                 result_3.amdDependencies = ts.emptyArray;
28776                 result_3.hasNoDefaultLib = false;
28777                 result_3.pragmas = ts.emptyMap;
28778                 return result_3;
28779             }
28780             initializeState(fileName, sourceText, languageVersion, syntaxCursor, scriptKind);
28781             var result = parseSourceFileWorker(languageVersion, setParentNodes, scriptKind);
28782             clearState();
28783             return result;
28784         }
28785         Parser.parseSourceFile = parseSourceFile;
28786         function parseIsolatedEntityName(content, languageVersion) {
28787             // Choice of `isDeclarationFile` should be arbitrary
28788             initializeState("", content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
28789             // Prime the scanner.
28790             nextToken();
28791             var entityName = parseEntityName(/*allowReservedWords*/ true);
28792             var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
28793             clearState();
28794             return isInvalid ? entityName : undefined;
28795         }
28796         Parser.parseIsolatedEntityName = parseIsolatedEntityName;
28797         function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
28798             if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
28799             if (setParentNodes === void 0) { setParentNodes = false; }
28800             initializeState(fileName, sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
28801             sourceFlags = contextFlags;
28802             // Prime the scanner.
28803             nextToken();
28804             var pos = getNodePos();
28805             var statements, endOfFileToken;
28806             if (token() === 1 /* EndOfFileToken */) {
28807                 statements = createNodeArray([], pos, pos);
28808                 endOfFileToken = parseTokenNode();
28809             }
28810             else {
28811                 var expression = void 0;
28812                 switch (token()) {
28813                     case 22 /* OpenBracketToken */:
28814                         expression = parseArrayLiteralExpression();
28815                         break;
28816                     case 109 /* TrueKeyword */:
28817                     case 94 /* FalseKeyword */:
28818                     case 103 /* NullKeyword */:
28819                         expression = parseTokenNode();
28820                         break;
28821                     case 40 /* MinusToken */:
28822                         if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) {
28823                             expression = parsePrefixUnaryExpression();
28824                         }
28825                         else {
28826                             expression = parseObjectLiteralExpression();
28827                         }
28828                         break;
28829                     case 8 /* NumericLiteral */:
28830                     case 10 /* StringLiteral */:
28831                         if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) {
28832                             expression = parseLiteralNode();
28833                             break;
28834                         }
28835                     // falls through
28836                     default:
28837                         expression = parseObjectLiteralExpression();
28838                         break;
28839                 }
28840                 var statement = factory.createExpressionStatement(expression);
28841                 finishNode(statement, pos);
28842                 statements = createNodeArray([statement], pos);
28843                 endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
28844             }
28845             // Set source file so that errors will be reported with this file name
28846             var sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false, statements, endOfFileToken, sourceFlags);
28847             if (setParentNodes) {
28848                 fixupParentReferences(sourceFile);
28849             }
28850             sourceFile.nodeCount = nodeCount;
28851             sourceFile.identifierCount = identifierCount;
28852             sourceFile.identifiers = identifiers;
28853             sourceFile.parseDiagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
28854             if (jsDocDiagnostics) {
28855                 sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
28856             }
28857             var result = sourceFile;
28858             clearState();
28859             return result;
28860         }
28861         Parser.parseJsonText = parseJsonText;
28862         function initializeState(_fileName, _sourceText, _languageVersion, _syntaxCursor, _scriptKind) {
28863             NodeConstructor = ts.objectAllocator.getNodeConstructor();
28864             TokenConstructor = ts.objectAllocator.getTokenConstructor();
28865             IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
28866             PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor();
28867             SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
28868             fileName = ts.normalizePath(_fileName);
28869             sourceText = _sourceText;
28870             languageVersion = _languageVersion;
28871             syntaxCursor = _syntaxCursor;
28872             scriptKind = _scriptKind;
28873             languageVariant = ts.getLanguageVariant(_scriptKind);
28874             parseDiagnostics = [];
28875             parsingContext = 0;
28876             identifiers = new ts.Map();
28877             privateIdentifiers = new ts.Map();
28878             identifierCount = 0;
28879             nodeCount = 0;
28880             sourceFlags = 0;
28881             topLevel = true;
28882             switch (scriptKind) {
28883                 case 1 /* JS */:
28884                 case 2 /* JSX */:
28885                     contextFlags = 131072 /* JavaScriptFile */;
28886                     break;
28887                 case 6 /* JSON */:
28888                     contextFlags = 131072 /* JavaScriptFile */ | 33554432 /* JsonFile */;
28889                     break;
28890                 default:
28891                     contextFlags = 0 /* None */;
28892                     break;
28893             }
28894             parseErrorBeforeNextFinishedNode = false;
28895             // Initialize and prime the scanner before parsing the source elements.
28896             scanner.setText(sourceText);
28897             scanner.setOnError(scanError);
28898             scanner.setScriptTarget(languageVersion);
28899             scanner.setLanguageVariant(languageVariant);
28900         }
28901         function clearState() {
28902             // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
28903             scanner.clearCommentDirectives();
28904             scanner.setText("");
28905             scanner.setOnError(undefined);
28906             // Clear any data.  We don't want to accidentally hold onto it for too long.
28907             sourceText = undefined;
28908             languageVersion = undefined;
28909             syntaxCursor = undefined;
28910             scriptKind = undefined;
28911             languageVariant = undefined;
28912             sourceFlags = 0;
28913             parseDiagnostics = undefined;
28914             jsDocDiagnostics = undefined;
28915             parsingContext = 0;
28916             identifiers = undefined;
28917             notParenthesizedArrow = undefined;
28918             topLevel = true;
28919         }
28920         function parseSourceFileWorker(languageVersion, setParentNodes, scriptKind) {
28921             var isDeclarationFile = isDeclarationFileName(fileName);
28922             if (isDeclarationFile) {
28923                 contextFlags |= 8388608 /* Ambient */;
28924             }
28925             sourceFlags = contextFlags;
28926             // Prime the scanner.
28927             nextToken();
28928             var statements = parseList(0 /* SourceElements */, parseStatement);
28929             ts.Debug.assert(token() === 1 /* EndOfFileToken */);
28930             var endOfFileToken = addJSDocComment(parseTokenNode());
28931             var sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile, statements, endOfFileToken, sourceFlags);
28932             // 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
28933             processCommentPragmas(sourceFile, sourceText);
28934             processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
28935             sourceFile.commentDirectives = scanner.getCommentDirectives();
28936             sourceFile.nodeCount = nodeCount;
28937             sourceFile.identifierCount = identifierCount;
28938             sourceFile.identifiers = identifiers;
28939             sourceFile.parseDiagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
28940             if (jsDocDiagnostics) {
28941                 sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
28942             }
28943             if (setParentNodes) {
28944                 fixupParentReferences(sourceFile);
28945             }
28946             return sourceFile;
28947             function reportPragmaDiagnostic(pos, end, diagnostic) {
28948                 parseDiagnostics.push(ts.createDetachedDiagnostic(fileName, pos, end, diagnostic));
28949             }
28950         }
28951         function withJSDoc(node, hasJSDoc) {
28952             return hasJSDoc ? addJSDocComment(node) : node;
28953         }
28954         var hasDeprecatedTag = false;
28955         function addJSDocComment(node) {
28956             ts.Debug.assert(!node.jsDoc); // Should only be called once per node
28957             var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceText), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
28958             if (jsDoc.length)
28959                 node.jsDoc = jsDoc;
28960             if (hasDeprecatedTag) {
28961                 hasDeprecatedTag = false;
28962                 node.flags |= 134217728 /* Deprecated */;
28963             }
28964             return node;
28965         }
28966         function reparseTopLevelAwait(sourceFile) {
28967             var savedSyntaxCursor = syntaxCursor;
28968             var baseSyntaxCursor = IncrementalParser.createSyntaxCursor(sourceFile);
28969             syntaxCursor = { currentNode: currentNode };
28970             var statements = [];
28971             var savedParseDiagnostics = parseDiagnostics;
28972             parseDiagnostics = [];
28973             var pos = 0;
28974             var start = findNextStatementWithAwait(sourceFile.statements, 0);
28975             var _loop_3 = function () {
28976                 // append all statements between pos and start
28977                 var prevStatement = sourceFile.statements[pos];
28978                 var nextStatement = sourceFile.statements[start];
28979                 ts.addRange(statements, sourceFile.statements, pos, start);
28980                 pos = findNextStatementWithoutAwait(sourceFile.statements, start);
28981                 // append all diagnostics associated with the copied range
28982                 var diagnosticStart = ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= prevStatement.pos; });
28983                 var diagnosticEnd = diagnosticStart >= 0 ? ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= nextStatement.pos; }, diagnosticStart) : -1;
28984                 if (diagnosticStart >= 0) {
28985                     ts.addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart, diagnosticEnd >= 0 ? diagnosticEnd : undefined);
28986                 }
28987                 // reparse all statements between start and pos. We skip existing diagnostics for the same range and allow the parser to generate new ones.
28988                 speculationHelper(function () {
28989                     var savedContextFlags = contextFlags;
28990                     contextFlags |= 32768 /* AwaitContext */;
28991                     scanner.setTextPos(nextStatement.pos);
28992                     nextToken();
28993                     while (token() !== 1 /* EndOfFileToken */) {
28994                         var startPos = scanner.getStartPos();
28995                         var statement = parseListElement(0 /* SourceElements */, parseStatement);
28996                         statements.push(statement);
28997                         if (startPos === scanner.getStartPos()) {
28998                             nextToken();
28999                         }
29000                         if (pos >= 0) {
29001                             var nonAwaitStatement = sourceFile.statements[pos];
29002                             if (statement.end === nonAwaitStatement.pos) {
29003                                 // done reparsing this section
29004                                 break;
29005                             }
29006                             if (statement.end > nonAwaitStatement.pos) {
29007                                 // we ate into the next statement, so we must reparse it.
29008                                 pos = findNextStatementWithoutAwait(sourceFile.statements, pos + 1);
29009                             }
29010                         }
29011                     }
29012                     contextFlags = savedContextFlags;
29013                 }, 2 /* Reparse */);
29014                 // find the next statement containing an `await`
29015                 start = pos >= 0 ? findNextStatementWithAwait(sourceFile.statements, pos) : -1;
29016             };
29017             while (start !== -1) {
29018                 _loop_3();
29019             }
29020             // append all statements between pos and the end of the list
29021             if (pos >= 0) {
29022                 var prevStatement_1 = sourceFile.statements[pos];
29023                 ts.addRange(statements, sourceFile.statements, pos);
29024                 // append all diagnostics associated with the copied range
29025                 var diagnosticStart = ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= prevStatement_1.pos; });
29026                 if (diagnosticStart >= 0) {
29027                     ts.addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart);
29028                 }
29029             }
29030             syntaxCursor = savedSyntaxCursor;
29031             return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements));
29032             function containsPossibleTopLevelAwait(node) {
29033                 return !(node.flags & 32768 /* AwaitContext */)
29034                     && !!(node.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */);
29035             }
29036             function findNextStatementWithAwait(statements, start) {
29037                 for (var i = start; i < statements.length; i++) {
29038                     if (containsPossibleTopLevelAwait(statements[i])) {
29039                         return i;
29040                     }
29041                 }
29042                 return -1;
29043             }
29044             function findNextStatementWithoutAwait(statements, start) {
29045                 for (var i = start; i < statements.length; i++) {
29046                     if (!containsPossibleTopLevelAwait(statements[i])) {
29047                         return i;
29048                     }
29049                 }
29050                 return -1;
29051             }
29052             function currentNode(position) {
29053                 var node = baseSyntaxCursor.currentNode(position);
29054                 if (topLevel && node && containsPossibleTopLevelAwait(node)) {
29055                     node.intersectsChange = true;
29056                 }
29057                 return node;
29058             }
29059         }
29060         function fixupParentReferences(rootNode) {
29061             // normally parent references are set during binding. However, for clients that only need
29062             // a syntax tree, and no semantic features, then the binding process is an unnecessary
29063             // overhead.  This functions allows us to set all the parents, without all the expense of
29064             // binding.
29065             ts.setParentRecursive(rootNode, /*incremental*/ true);
29066         }
29067         Parser.fixupParentReferences = fixupParentReferences;
29068         function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile, statements, endOfFileToken, flags) {
29069             // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
29070             // this is quite rare comparing to other nodes and createNode should be as fast as possible
29071             var sourceFile = factory.createSourceFile(statements, endOfFileToken, flags);
29072             ts.setTextRangePosWidth(sourceFile, 0, sourceText.length);
29073             setExternalModuleIndicator(sourceFile);
29074             // If we parsed this as an external module, it may contain top-level await
29075             if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */) {
29076                 sourceFile = reparseTopLevelAwait(sourceFile);
29077             }
29078             sourceFile.text = sourceText;
29079             sourceFile.bindDiagnostics = [];
29080             sourceFile.bindSuggestionDiagnostics = undefined;
29081             sourceFile.languageVersion = languageVersion;
29082             sourceFile.fileName = fileName;
29083             sourceFile.languageVariant = ts.getLanguageVariant(scriptKind);
29084             sourceFile.isDeclarationFile = isDeclarationFile;
29085             sourceFile.scriptKind = scriptKind;
29086             return sourceFile;
29087         }
29088         function setContextFlag(val, flag) {
29089             if (val) {
29090                 contextFlags |= flag;
29091             }
29092             else {
29093                 contextFlags &= ~flag;
29094             }
29095         }
29096         function setDisallowInContext(val) {
29097             setContextFlag(val, 4096 /* DisallowInContext */);
29098         }
29099         function setYieldContext(val) {
29100             setContextFlag(val, 8192 /* YieldContext */);
29101         }
29102         function setDecoratorContext(val) {
29103             setContextFlag(val, 16384 /* DecoratorContext */);
29104         }
29105         function setAwaitContext(val) {
29106             setContextFlag(val, 32768 /* AwaitContext */);
29107         }
29108         function doOutsideOfContext(context, func) {
29109             // contextFlagsToClear will contain only the context flags that are
29110             // currently set that we need to temporarily clear
29111             // We don't just blindly reset to the previous flags to ensure
29112             // that we do not mutate cached flags for the incremental
29113             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
29114             // HasAggregatedChildData).
29115             var contextFlagsToClear = context & contextFlags;
29116             if (contextFlagsToClear) {
29117                 // clear the requested context flags
29118                 setContextFlag(/*val*/ false, contextFlagsToClear);
29119                 var result = func();
29120                 // restore the context flags we just cleared
29121                 setContextFlag(/*val*/ true, contextFlagsToClear);
29122                 return result;
29123             }
29124             // no need to do anything special as we are not in any of the requested contexts
29125             return func();
29126         }
29127         function doInsideOfContext(context, func) {
29128             // contextFlagsToSet will contain only the context flags that
29129             // are not currently set that we need to temporarily enable.
29130             // We don't just blindly reset to the previous flags to ensure
29131             // that we do not mutate cached flags for the incremental
29132             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
29133             // HasAggregatedChildData).
29134             var contextFlagsToSet = context & ~contextFlags;
29135             if (contextFlagsToSet) {
29136                 // set the requested context flags
29137                 setContextFlag(/*val*/ true, contextFlagsToSet);
29138                 var result = func();
29139                 // reset the context flags we just set
29140                 setContextFlag(/*val*/ false, contextFlagsToSet);
29141                 return result;
29142             }
29143             // no need to do anything special as we are already in all of the requested contexts
29144             return func();
29145         }
29146         function allowInAnd(func) {
29147             return doOutsideOfContext(4096 /* DisallowInContext */, func);
29148         }
29149         function disallowInAnd(func) {
29150             return doInsideOfContext(4096 /* DisallowInContext */, func);
29151         }
29152         function doInYieldContext(func) {
29153             return doInsideOfContext(8192 /* YieldContext */, func);
29154         }
29155         function doInDecoratorContext(func) {
29156             return doInsideOfContext(16384 /* DecoratorContext */, func);
29157         }
29158         function doInAwaitContext(func) {
29159             return doInsideOfContext(32768 /* AwaitContext */, func);
29160         }
29161         function doOutsideOfAwaitContext(func) {
29162             return doOutsideOfContext(32768 /* AwaitContext */, func);
29163         }
29164         function doInYieldAndAwaitContext(func) {
29165             return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
29166         }
29167         function doOutsideOfYieldAndAwaitContext(func) {
29168             return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
29169         }
29170         function inContext(flags) {
29171             return (contextFlags & flags) !== 0;
29172         }
29173         function inYieldContext() {
29174             return inContext(8192 /* YieldContext */);
29175         }
29176         function inDisallowInContext() {
29177             return inContext(4096 /* DisallowInContext */);
29178         }
29179         function inDecoratorContext() {
29180             return inContext(16384 /* DecoratorContext */);
29181         }
29182         function inAwaitContext() {
29183             return inContext(32768 /* AwaitContext */);
29184         }
29185         function parseErrorAtCurrentToken(message, arg0) {
29186             parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0);
29187         }
29188         function parseErrorAtPosition(start, length, message, arg0) {
29189             // Don't report another error if it would just be at the same position as the last error.
29190             var lastError = ts.lastOrUndefined(parseDiagnostics);
29191             if (!lastError || start !== lastError.start) {
29192                 parseDiagnostics.push(ts.createDetachedDiagnostic(fileName, start, length, message, arg0));
29193             }
29194             // Mark that we've encountered an error.  We'll set an appropriate bit on the next
29195             // node we finish so that it can't be reused incrementally.
29196             parseErrorBeforeNextFinishedNode = true;
29197         }
29198         function parseErrorAt(start, end, message, arg0) {
29199             parseErrorAtPosition(start, end - start, message, arg0);
29200         }
29201         function parseErrorAtRange(range, message, arg0) {
29202             parseErrorAt(range.pos, range.end, message, arg0);
29203         }
29204         function scanError(message, length) {
29205             parseErrorAtPosition(scanner.getTextPos(), length, message);
29206         }
29207         function getNodePos() {
29208             return scanner.getStartPos();
29209         }
29210         function hasPrecedingJSDocComment() {
29211             return scanner.hasPrecedingJSDocComment();
29212         }
29213         // Use this function to access the current token instead of reading the currentToken
29214         // variable. Since function results aren't narrowed in control flow analysis, this ensures
29215         // that the type checker doesn't make wrong assumptions about the type of the current
29216         // token (e.g. a call to nextToken() changes the current token but the checker doesn't
29217         // reason about this side effect).  Mainstream VMs inline simple functions like this, so
29218         // there is no performance penalty.
29219         function token() {
29220             return currentToken;
29221         }
29222         function nextTokenWithoutCheck() {
29223             return currentToken = scanner.scan();
29224         }
29225         function nextTokenAnd(func) {
29226             nextToken();
29227             return func();
29228         }
29229         function nextToken() {
29230             // if the keyword had an escape
29231             if (ts.isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) {
29232                 // issue a parse error for the escape
29233                 parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), ts.Diagnostics.Keywords_cannot_contain_escape_characters);
29234             }
29235             return nextTokenWithoutCheck();
29236         }
29237         function nextTokenJSDoc() {
29238             return currentToken = scanner.scanJsDocToken();
29239         }
29240         function reScanGreaterToken() {
29241             return currentToken = scanner.reScanGreaterToken();
29242         }
29243         function reScanSlashToken() {
29244             return currentToken = scanner.reScanSlashToken();
29245         }
29246         function reScanTemplateToken(isTaggedTemplate) {
29247             return currentToken = scanner.reScanTemplateToken(isTaggedTemplate);
29248         }
29249         function reScanTemplateHeadOrNoSubstitutionTemplate() {
29250             return currentToken = scanner.reScanTemplateHeadOrNoSubstitutionTemplate();
29251         }
29252         function reScanLessThanToken() {
29253             return currentToken = scanner.reScanLessThanToken();
29254         }
29255         function scanJsxIdentifier() {
29256             return currentToken = scanner.scanJsxIdentifier();
29257         }
29258         function scanJsxText() {
29259             return currentToken = scanner.scanJsxToken();
29260         }
29261         function scanJsxAttributeValue() {
29262             return currentToken = scanner.scanJsxAttributeValue();
29263         }
29264         function speculationHelper(callback, speculationKind) {
29265             // Keep track of the state we'll need to rollback to if lookahead fails (or if the
29266             // caller asked us to always reset our state).
29267             var saveToken = currentToken;
29268             var saveParseDiagnosticsLength = parseDiagnostics.length;
29269             var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
29270             // Note: it is not actually necessary to save/restore the context flags here.  That's
29271             // because the saving/restoring of these flags happens naturally through the recursive
29272             // descent nature of our parser.  However, we still store this here just so we can
29273             // assert that invariant holds.
29274             var saveContextFlags = contextFlags;
29275             // If we're only looking ahead, then tell the scanner to only lookahead as well.
29276             // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
29277             // same.
29278             var result = speculationKind !== 0 /* TryParse */
29279                 ? scanner.lookAhead(callback)
29280                 : scanner.tryScan(callback);
29281             ts.Debug.assert(saveContextFlags === contextFlags);
29282             // If our callback returned something 'falsy' or we're just looking ahead,
29283             // then unconditionally restore us to where we were.
29284             if (!result || speculationKind !== 0 /* TryParse */) {
29285                 currentToken = saveToken;
29286                 if (speculationKind !== 2 /* Reparse */) {
29287                     parseDiagnostics.length = saveParseDiagnosticsLength;
29288                 }
29289                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
29290             }
29291             return result;
29292         }
29293         /** Invokes the provided callback then unconditionally restores the parser to the state it
29294          * was in immediately prior to invoking the callback.  The result of invoking the callback
29295          * is returned from this function.
29296          */
29297         function lookAhead(callback) {
29298             return speculationHelper(callback, 1 /* Lookahead */);
29299         }
29300         /** Invokes the provided callback.  If the callback returns something falsy, then it restores
29301          * the parser to the state it was in immediately prior to invoking the callback.  If the
29302          * callback returns something truthy, then the parser state is not rolled back.  The result
29303          * of invoking the callback is returned from this function.
29304          */
29305         function tryParse(callback) {
29306             return speculationHelper(callback, 0 /* TryParse */);
29307         }
29308         function isBindingIdentifier() {
29309             if (token() === 78 /* Identifier */) {
29310                 return true;
29311             }
29312             return token() > 115 /* LastReservedWord */;
29313         }
29314         // Ignore strict mode flag because we will report an error in type checker instead.
29315         function isIdentifier() {
29316             if (token() === 78 /* Identifier */) {
29317                 return true;
29318             }
29319             // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
29320             // considered a keyword and is not an identifier.
29321             if (token() === 124 /* YieldKeyword */ && inYieldContext()) {
29322                 return false;
29323             }
29324             // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
29325             // considered a keyword and is not an identifier.
29326             if (token() === 130 /* AwaitKeyword */ && inAwaitContext()) {
29327                 return false;
29328             }
29329             return token() > 115 /* LastReservedWord */;
29330         }
29331         function parseExpected(kind, diagnosticMessage, shouldAdvance) {
29332             if (shouldAdvance === void 0) { shouldAdvance = true; }
29333             if (token() === kind) {
29334                 if (shouldAdvance) {
29335                     nextToken();
29336                 }
29337                 return true;
29338             }
29339             // Report specific message if provided with one.  Otherwise, report generic fallback message.
29340             if (diagnosticMessage) {
29341                 parseErrorAtCurrentToken(diagnosticMessage);
29342             }
29343             else {
29344                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
29345             }
29346             return false;
29347         }
29348         function parseExpectedJSDoc(kind) {
29349             if (token() === kind) {
29350                 nextTokenJSDoc();
29351                 return true;
29352             }
29353             parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
29354             return false;
29355         }
29356         function parseOptional(t) {
29357             if (token() === t) {
29358                 nextToken();
29359                 return true;
29360             }
29361             return false;
29362         }
29363         function parseOptionalToken(t) {
29364             if (token() === t) {
29365                 return parseTokenNode();
29366             }
29367             return undefined;
29368         }
29369         function parseOptionalTokenJSDoc(t) {
29370             if (token() === t) {
29371                 return parseTokenNodeJSDoc();
29372             }
29373             return undefined;
29374         }
29375         function parseExpectedToken(t, diagnosticMessage, arg0) {
29376             return parseOptionalToken(t) ||
29377                 createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
29378         }
29379         function parseExpectedTokenJSDoc(t) {
29380             return parseOptionalTokenJSDoc(t) ||
29381                 createMissingNode(t, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(t));
29382         }
29383         function parseTokenNode() {
29384             var pos = getNodePos();
29385             var kind = token();
29386             nextToken();
29387             return finishNode(factory.createToken(kind), pos);
29388         }
29389         function parseTokenNodeJSDoc() {
29390             var pos = getNodePos();
29391             var kind = token();
29392             nextTokenJSDoc();
29393             return finishNode(factory.createToken(kind), pos);
29394         }
29395         function canParseSemicolon() {
29396             // If there's a real semicolon, then we can always parse it out.
29397             if (token() === 26 /* SemicolonToken */) {
29398                 return true;
29399             }
29400             // We can parse out an optional semicolon in ASI cases in the following cases.
29401             return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
29402         }
29403         function parseSemicolon() {
29404             if (canParseSemicolon()) {
29405                 if (token() === 26 /* SemicolonToken */) {
29406                     // consume the semicolon if it was explicitly provided.
29407                     nextToken();
29408                 }
29409                 return true;
29410             }
29411             else {
29412                 return parseExpected(26 /* SemicolonToken */);
29413             }
29414         }
29415         function createNodeArray(elements, pos, end, hasTrailingComma) {
29416             var array = factory.createNodeArray(elements, hasTrailingComma);
29417             ts.setTextRangePosEnd(array, pos, end !== null && end !== void 0 ? end : scanner.getStartPos());
29418             return array;
29419         }
29420         function finishNode(node, pos, end) {
29421             ts.setTextRangePosEnd(node, pos, end !== null && end !== void 0 ? end : scanner.getStartPos());
29422             if (contextFlags) {
29423                 node.flags |= contextFlags;
29424             }
29425             // Keep track on the node if we encountered an error while parsing it.  If we did, then
29426             // we cannot reuse the node incrementally.  Once we've marked this node, clear out the
29427             // flag so that we don't mark any subsequent nodes.
29428             if (parseErrorBeforeNextFinishedNode) {
29429                 parseErrorBeforeNextFinishedNode = false;
29430                 node.flags |= 65536 /* ThisNodeHasError */;
29431             }
29432             return node;
29433         }
29434         function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
29435             if (reportAtCurrentPosition) {
29436                 parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
29437             }
29438             else if (diagnosticMessage) {
29439                 parseErrorAtCurrentToken(diagnosticMessage, arg0);
29440             }
29441             var pos = getNodePos();
29442             var result = kind === 78 /* Identifier */ ? factory.createIdentifier("", /*typeArguments*/ undefined, /*originalKeywordKind*/ undefined) :
29443                 ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ undefined) :
29444                     kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral("", /*numericLiteralFlags*/ undefined) :
29445                         kind === 10 /* StringLiteral */ ? factory.createStringLiteral("", /*isSingleQuote*/ undefined) :
29446                             kind === 271 /* MissingDeclaration */ ? factory.createMissingDeclaration() :
29447                                 factory.createToken(kind);
29448             return finishNode(result, pos);
29449         }
29450         function internIdentifier(text) {
29451             var identifier = identifiers.get(text);
29452             if (identifier === undefined) {
29453                 identifiers.set(text, identifier = text);
29454             }
29455             return identifier;
29456         }
29457         // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
29458         // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
29459         // each identifier in order to reduce memory consumption.
29460         function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) {
29461             if (isIdentifier) {
29462                 identifierCount++;
29463                 var pos = getNodePos();
29464                 // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
29465                 var originalKeywordKind = token();
29466                 var text = internIdentifier(scanner.getTokenValue());
29467                 nextTokenWithoutCheck();
29468                 return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos);
29469             }
29470             if (token() === 79 /* PrivateIdentifier */) {
29471                 parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
29472                 return createIdentifier(/*isIdentifier*/ true);
29473             }
29474             if (token() === 0 /* Unknown */ && scanner.tryScan(function () { return scanner.reScanInvalidIdentifier() === 78 /* Identifier */; })) {
29475                 // Scanner has already recorded an 'Invalid character' error, so no need to add another from the parser.
29476                 return createIdentifier(/*isIdentifier*/ true);
29477             }
29478             identifierCount++;
29479             // Only for end of file because the error gets reported incorrectly on embedded script tags.
29480             var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
29481             var isReservedWord = scanner.isReservedWord();
29482             var msgArg = scanner.getTokenText();
29483             var defaultMessage = isReservedWord ?
29484                 ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here :
29485                 ts.Diagnostics.Identifier_expected;
29486             return createMissingNode(78 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
29487         }
29488         function parseBindingIdentifier(privateIdentifierDiagnosticMessage) {
29489             return createIdentifier(isBindingIdentifier(), /*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
29490         }
29491         function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) {
29492             return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage);
29493         }
29494         function parseIdentifierName(diagnosticMessage) {
29495             return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
29496         }
29497         function isLiteralPropertyName() {
29498             return ts.tokenIsIdentifierOrKeyword(token()) ||
29499                 token() === 10 /* StringLiteral */ ||
29500                 token() === 8 /* NumericLiteral */;
29501         }
29502         function parsePropertyNameWorker(allowComputedPropertyNames) {
29503             if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
29504                 var node = parseLiteralNode();
29505                 node.text = internIdentifier(node.text);
29506                 return node;
29507             }
29508             if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) {
29509                 return parseComputedPropertyName();
29510             }
29511             if (token() === 79 /* PrivateIdentifier */) {
29512                 return parsePrivateIdentifier();
29513             }
29514             return parseIdentifierName();
29515         }
29516         function parsePropertyName() {
29517             return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
29518         }
29519         function parseComputedPropertyName() {
29520             // PropertyName [Yield]:
29521             //      LiteralPropertyName
29522             //      ComputedPropertyName[?Yield]
29523             var pos = getNodePos();
29524             parseExpected(22 /* OpenBracketToken */);
29525             // We parse any expression (including a comma expression). But the grammar
29526             // says that only an assignment expression is allowed, so the grammar checker
29527             // will error if it sees a comma expression.
29528             var expression = allowInAnd(parseExpression);
29529             parseExpected(23 /* CloseBracketToken */);
29530             return finishNode(factory.createComputedPropertyName(expression), pos);
29531         }
29532         function internPrivateIdentifier(text) {
29533             var privateIdentifier = privateIdentifiers.get(text);
29534             if (privateIdentifier === undefined) {
29535                 privateIdentifiers.set(text, privateIdentifier = text);
29536             }
29537             return privateIdentifier;
29538         }
29539         function parsePrivateIdentifier() {
29540             var pos = getNodePos();
29541             var node = factory.createPrivateIdentifier(internPrivateIdentifier(scanner.getTokenText()));
29542             nextToken();
29543             return finishNode(node, pos);
29544         }
29545         function parseContextualModifier(t) {
29546             return token() === t && tryParse(nextTokenCanFollowModifier);
29547         }
29548         function nextTokenIsOnSameLineAndCanFollowModifier() {
29549             nextToken();
29550             if (scanner.hasPrecedingLineBreak()) {
29551                 return false;
29552             }
29553             return canFollowModifier();
29554         }
29555         function nextTokenCanFollowModifier() {
29556             switch (token()) {
29557                 case 84 /* ConstKeyword */:
29558                     // 'const' is only a modifier if followed by 'enum'.
29559                     return nextToken() === 91 /* EnumKeyword */;
29560                 case 92 /* ExportKeyword */:
29561                     nextToken();
29562                     if (token() === 87 /* DefaultKeyword */) {
29563                         return lookAhead(nextTokenCanFollowDefaultKeyword);
29564                     }
29565                     if (token() === 149 /* TypeKeyword */) {
29566                         return lookAhead(nextTokenCanFollowExportModifier);
29567                     }
29568                     return canFollowExportModifier();
29569                 case 87 /* DefaultKeyword */:
29570                     return nextTokenCanFollowDefaultKeyword();
29571                 case 123 /* StaticKeyword */:
29572                     return nextTokenIsOnSameLineAndCanFollowModifier();
29573                 case 134 /* GetKeyword */:
29574                 case 146 /* SetKeyword */:
29575                     nextToken();
29576                     return canFollowModifier();
29577                 default:
29578                     return nextTokenIsOnSameLineAndCanFollowModifier();
29579             }
29580         }
29581         function canFollowExportModifier() {
29582             return token() !== 41 /* AsteriskToken */
29583                 && token() !== 126 /* AsKeyword */
29584                 && token() !== 18 /* OpenBraceToken */
29585                 && canFollowModifier();
29586         }
29587         function nextTokenCanFollowExportModifier() {
29588             nextToken();
29589             return canFollowExportModifier();
29590         }
29591         function parseAnyContextualModifier() {
29592             return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
29593         }
29594         function canFollowModifier() {
29595             return token() === 22 /* OpenBracketToken */
29596                 || token() === 18 /* OpenBraceToken */
29597                 || token() === 41 /* AsteriskToken */
29598                 || token() === 25 /* DotDotDotToken */
29599                 || isLiteralPropertyName();
29600         }
29601         function nextTokenCanFollowDefaultKeyword() {
29602             nextToken();
29603             return token() === 83 /* ClassKeyword */ || token() === 97 /* FunctionKeyword */ ||
29604                 token() === 117 /* InterfaceKeyword */ ||
29605                 (token() === 125 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
29606                 (token() === 129 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
29607         }
29608         // True if positioned at the start of a list element
29609         function isListElement(parsingContext, inErrorRecovery) {
29610             var node = currentNode(parsingContext);
29611             if (node) {
29612                 return true;
29613             }
29614             switch (parsingContext) {
29615                 case 0 /* SourceElements */:
29616                 case 1 /* BlockStatements */:
29617                 case 3 /* SwitchClauseStatements */:
29618                     // If we're in error recovery, then we don't want to treat ';' as an empty statement.
29619                     // The problem is that ';' can show up in far too many contexts, and if we see one
29620                     // and assume it's a statement, then we may bail out inappropriately from whatever
29621                     // we're parsing.  For example, if we have a semicolon in the middle of a class, then
29622                     // we really don't want to assume the class is over and we're on a statement in the
29623                     // outer module.  We just want to consume and move on.
29624                     return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
29625                 case 2 /* SwitchClauses */:
29626                     return token() === 81 /* CaseKeyword */ || token() === 87 /* DefaultKeyword */;
29627                 case 4 /* TypeMembers */:
29628                     return lookAhead(isTypeMemberStart);
29629                 case 5 /* ClassMembers */:
29630                     // We allow semicolons as class elements (as specified by ES6) as long as we're
29631                     // not in error recovery.  If we're in error recovery, we don't want an errant
29632                     // semicolon to be treated as a class member (since they're almost always used
29633                     // for statements.
29634                     return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery);
29635                 case 6 /* EnumMembers */:
29636                     // Include open bracket computed properties. This technically also lets in indexers,
29637                     // which would be a candidate for improved error reporting.
29638                     return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName();
29639                 case 12 /* ObjectLiteralMembers */:
29640                     switch (token()) {
29641                         case 22 /* OpenBracketToken */:
29642                         case 41 /* AsteriskToken */:
29643                         case 25 /* DotDotDotToken */:
29644                         case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
29645                             return true;
29646                         default:
29647                             return isLiteralPropertyName();
29648                     }
29649                 case 18 /* RestProperties */:
29650                     return isLiteralPropertyName();
29651                 case 9 /* ObjectBindingElements */:
29652                     return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName();
29653                 case 7 /* HeritageClauseElement */:
29654                     // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
29655                     // That way we won't consume the body of a class in its heritage clause.
29656                     if (token() === 18 /* OpenBraceToken */) {
29657                         return lookAhead(isValidHeritageClauseObjectLiteral);
29658                     }
29659                     if (!inErrorRecovery) {
29660                         return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
29661                     }
29662                     else {
29663                         // If we're in error recovery we tighten up what we're willing to match.
29664                         // That way we don't treat something like "this" as a valid heritage clause
29665                         // element during recovery.
29666                         return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
29667                     }
29668                 case 8 /* VariableDeclarations */:
29669                     return isBindingIdentifierOrPrivateIdentifierOrPattern();
29670                 case 10 /* ArrayBindingElements */:
29671                     return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern();
29672                 case 19 /* TypeParameters */:
29673                     return isIdentifier();
29674                 case 15 /* ArrayLiteralMembers */:
29675                     switch (token()) {
29676                         case 27 /* CommaToken */:
29677                         case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
29678                             return true;
29679                     }
29680                 // falls through
29681                 case 11 /* ArgumentExpressions */:
29682                     return token() === 25 /* DotDotDotToken */ || isStartOfExpression();
29683                 case 16 /* Parameters */:
29684                     return isStartOfParameter(/*isJSDocParameter*/ false);
29685                 case 17 /* JSDocParameters */:
29686                     return isStartOfParameter(/*isJSDocParameter*/ true);
29687                 case 20 /* TypeArguments */:
29688                 case 21 /* TupleElementTypes */:
29689                     return token() === 27 /* CommaToken */ || isStartOfType();
29690                 case 22 /* HeritageClauses */:
29691                     return isHeritageClause();
29692                 case 23 /* ImportOrExportSpecifiers */:
29693                     return ts.tokenIsIdentifierOrKeyword(token());
29694                 case 13 /* JsxAttributes */:
29695                     return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */;
29696                 case 14 /* JsxChildren */:
29697                     return true;
29698             }
29699             return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
29700         }
29701         function isValidHeritageClauseObjectLiteral() {
29702             ts.Debug.assert(token() === 18 /* OpenBraceToken */);
29703             if (nextToken() === 19 /* CloseBraceToken */) {
29704                 // if we see "extends {}" then only treat the {} as what we're extending (and not
29705                 // the class body) if we have:
29706                 //
29707                 //      extends {} {
29708                 //      extends {},
29709                 //      extends {} extends
29710                 //      extends {} implements
29711                 var next = nextToken();
29712                 return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 93 /* ExtendsKeyword */ || next === 116 /* ImplementsKeyword */;
29713             }
29714             return true;
29715         }
29716         function nextTokenIsIdentifier() {
29717             nextToken();
29718             return isIdentifier();
29719         }
29720         function nextTokenIsIdentifierOrKeyword() {
29721             nextToken();
29722             return ts.tokenIsIdentifierOrKeyword(token());
29723         }
29724         function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
29725             nextToken();
29726             return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
29727         }
29728         function isHeritageClauseExtendsOrImplementsKeyword() {
29729             if (token() === 116 /* ImplementsKeyword */ ||
29730                 token() === 93 /* ExtendsKeyword */) {
29731                 return lookAhead(nextTokenIsStartOfExpression);
29732             }
29733             return false;
29734         }
29735         function nextTokenIsStartOfExpression() {
29736             nextToken();
29737             return isStartOfExpression();
29738         }
29739         function nextTokenIsStartOfType() {
29740             nextToken();
29741             return isStartOfType();
29742         }
29743         // True if positioned at a list terminator
29744         function isListTerminator(kind) {
29745             if (token() === 1 /* EndOfFileToken */) {
29746                 // Being at the end of the file ends all lists.
29747                 return true;
29748             }
29749             switch (kind) {
29750                 case 1 /* BlockStatements */:
29751                 case 2 /* SwitchClauses */:
29752                 case 4 /* TypeMembers */:
29753                 case 5 /* ClassMembers */:
29754                 case 6 /* EnumMembers */:
29755                 case 12 /* ObjectLiteralMembers */:
29756                 case 9 /* ObjectBindingElements */:
29757                 case 23 /* ImportOrExportSpecifiers */:
29758                     return token() === 19 /* CloseBraceToken */;
29759                 case 3 /* SwitchClauseStatements */:
29760                     return token() === 19 /* CloseBraceToken */ || token() === 81 /* CaseKeyword */ || token() === 87 /* DefaultKeyword */;
29761                 case 7 /* HeritageClauseElement */:
29762                     return token() === 18 /* OpenBraceToken */ || token() === 93 /* ExtendsKeyword */ || token() === 116 /* ImplementsKeyword */;
29763                 case 8 /* VariableDeclarations */:
29764                     return isVariableDeclaratorListTerminator();
29765                 case 19 /* TypeParameters */:
29766                     // Tokens other than '>' are here for better error recovery
29767                     return token() === 31 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 93 /* ExtendsKeyword */ || token() === 116 /* ImplementsKeyword */;
29768                 case 11 /* ArgumentExpressions */:
29769                     // Tokens other than ')' are here for better error recovery
29770                     return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */;
29771                 case 15 /* ArrayLiteralMembers */:
29772                 case 21 /* TupleElementTypes */:
29773                 case 10 /* ArrayBindingElements */:
29774                     return token() === 23 /* CloseBracketToken */;
29775                 case 17 /* JSDocParameters */:
29776                 case 16 /* Parameters */:
29777                 case 18 /* RestProperties */:
29778                     // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
29779                     return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
29780                 case 20 /* TypeArguments */:
29781                     // All other tokens should cause the type-argument to terminate except comma token
29782                     return token() !== 27 /* CommaToken */;
29783                 case 22 /* HeritageClauses */:
29784                     return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */;
29785                 case 13 /* JsxAttributes */:
29786                     return token() === 31 /* GreaterThanToken */ || token() === 43 /* SlashToken */;
29787                 case 14 /* JsxChildren */:
29788                     return token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
29789                 default:
29790                     return false;
29791             }
29792         }
29793         function isVariableDeclaratorListTerminator() {
29794             // If we can consume a semicolon (either explicitly, or with ASI), then consider us done
29795             // with parsing the list of variable declarators.
29796             if (canParseSemicolon()) {
29797                 return true;
29798             }
29799             // in the case where we're parsing the variable declarator of a 'for-in' statement, we
29800             // are done if we see an 'in' keyword in front of us. Same with for-of
29801             if (isInOrOfKeyword(token())) {
29802                 return true;
29803             }
29804             // ERROR RECOVERY TWEAK:
29805             // For better error recovery, if we see an '=>' then we just stop immediately.  We've got an
29806             // arrow function here and it's going to be very unlikely that we'll resynchronize and get
29807             // another variable declaration.
29808             if (token() === 38 /* EqualsGreaterThanToken */) {
29809                 return true;
29810             }
29811             // Keep trying to parse out variable declarators.
29812             return false;
29813         }
29814         // True if positioned at element or terminator of the current list or any enclosing list
29815         function isInSomeParsingContext() {
29816             for (var kind = 0; kind < 24 /* Count */; kind++) {
29817                 if (parsingContext & (1 << kind)) {
29818                     if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
29819                         return true;
29820                     }
29821                 }
29822             }
29823             return false;
29824         }
29825         // Parses a list of elements
29826         function parseList(kind, parseElement) {
29827             var saveParsingContext = parsingContext;
29828             parsingContext |= 1 << kind;
29829             var list = [];
29830             var listPos = getNodePos();
29831             while (!isListTerminator(kind)) {
29832                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
29833                     var element = parseListElement(kind, parseElement);
29834                     list.push(element);
29835                     continue;
29836                 }
29837                 if (abortParsingListOrMoveToNextToken(kind)) {
29838                     break;
29839                 }
29840             }
29841             parsingContext = saveParsingContext;
29842             return createNodeArray(list, listPos);
29843         }
29844         function parseListElement(parsingContext, parseElement) {
29845             var node = currentNode(parsingContext);
29846             if (node) {
29847                 return consumeNode(node);
29848             }
29849             return parseElement();
29850         }
29851         function currentNode(parsingContext) {
29852             // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
29853             //
29854             // If there is an outstanding parse error that we've encountered, but not attached to
29855             // some node, then we cannot get a node from the old source tree.  This is because we
29856             // want to mark the next node we encounter as being unusable.
29857             //
29858             // Note: This may be too conservative.  Perhaps we could reuse the node and set the bit
29859             // on it (or its leftmost child) as having the error.  For now though, being conservative
29860             // is nice and likely won't ever affect perf.
29861             if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) {
29862                 return undefined;
29863             }
29864             var node = syntaxCursor.currentNode(scanner.getStartPos());
29865             // Can't reuse a missing node.
29866             // Can't reuse a node that intersected the change range.
29867             // Can't reuse a node that contains a parse error.  This is necessary so that we
29868             // produce the same set of errors again.
29869             if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) {
29870                 return undefined;
29871             }
29872             // We can only reuse a node if it was parsed under the same strict mode that we're
29873             // currently in.  i.e. if we originally parsed a node in non-strict mode, but then
29874             // the user added 'using strict' at the top of the file, then we can't use that node
29875             // again as the presence of strict mode may cause us to parse the tokens in the file
29876             // differently.
29877             //
29878             // Note: we *can* reuse tokens when the strict mode changes.  That's because tokens
29879             // are unaffected by strict mode.  It's just the parser will decide what to do with it
29880             // differently depending on what mode it is in.
29881             //
29882             // This also applies to all our other context flags as well.
29883             var nodeContextFlags = node.flags & 25358336 /* ContextFlags */;
29884             if (nodeContextFlags !== contextFlags) {
29885                 return undefined;
29886             }
29887             // Ok, we have a node that looks like it could be reused.  Now verify that it is valid
29888             // in the current list parsing context that we're currently at.
29889             if (!canReuseNode(node, parsingContext)) {
29890                 return undefined;
29891             }
29892             if (node.jsDocCache) {
29893                 // jsDocCache may include tags from parent nodes, which might have been modified.
29894                 node.jsDocCache = undefined;
29895             }
29896             return node;
29897         }
29898         function consumeNode(node) {
29899             // Move the scanner so it is after the node we just consumed.
29900             scanner.setTextPos(node.end);
29901             nextToken();
29902             return node;
29903         }
29904         function isReusableParsingContext(parsingContext) {
29905             switch (parsingContext) {
29906                 case 5 /* ClassMembers */:
29907                 case 2 /* SwitchClauses */:
29908                 case 0 /* SourceElements */:
29909                 case 1 /* BlockStatements */:
29910                 case 3 /* SwitchClauseStatements */:
29911                 case 6 /* EnumMembers */:
29912                 case 4 /* TypeMembers */:
29913                 case 8 /* VariableDeclarations */:
29914                 case 17 /* JSDocParameters */:
29915                 case 16 /* Parameters */:
29916                     return true;
29917             }
29918             return false;
29919         }
29920         function canReuseNode(node, parsingContext) {
29921             switch (parsingContext) {
29922                 case 5 /* ClassMembers */:
29923                     return isReusableClassMember(node);
29924                 case 2 /* SwitchClauses */:
29925                     return isReusableSwitchClause(node);
29926                 case 0 /* SourceElements */:
29927                 case 1 /* BlockStatements */:
29928                 case 3 /* SwitchClauseStatements */:
29929                     return isReusableStatement(node);
29930                 case 6 /* EnumMembers */:
29931                     return isReusableEnumMember(node);
29932                 case 4 /* TypeMembers */:
29933                     return isReusableTypeMember(node);
29934                 case 8 /* VariableDeclarations */:
29935                     return isReusableVariableDeclaration(node);
29936                 case 17 /* JSDocParameters */:
29937                 case 16 /* Parameters */:
29938                     return isReusableParameter(node);
29939                 // Any other lists we do not care about reusing nodes in.  But feel free to add if
29940                 // you can do so safely.  Danger areas involve nodes that may involve speculative
29941                 // parsing.  If speculative parsing is involved with the node, then the range the
29942                 // parser reached while looking ahead might be in the edited range (see the example
29943                 // in canReuseVariableDeclaratorNode for a good case of this).
29944                 // case ParsingContext.HeritageClauses:
29945                 // This would probably be safe to reuse.  There is no speculative parsing with
29946                 // heritage clauses.
29947                 // case ParsingContext.TypeParameters:
29948                 // This would probably be safe to reuse.  There is no speculative parsing with
29949                 // type parameters.  Note that that's because type *parameters* only occur in
29950                 // unambiguous *type* contexts.  While type *arguments* occur in very ambiguous
29951                 // *expression* contexts.
29952                 // case ParsingContext.TupleElementTypes:
29953                 // This would probably be safe to reuse.  There is no speculative parsing with
29954                 // tuple types.
29955                 // Technically, type argument list types are probably safe to reuse.  While
29956                 // speculative parsing is involved with them (since type argument lists are only
29957                 // produced from speculative parsing a < as a type argument list), we only have
29958                 // the types because speculative parsing succeeded.  Thus, the lookahead never
29959                 // went past the end of the list and rewound.
29960                 // case ParsingContext.TypeArguments:
29961                 // Note: these are almost certainly not safe to ever reuse.  Expressions commonly
29962                 // need a large amount of lookahead, and we should not reuse them as they may
29963                 // have actually intersected the edit.
29964                 // case ParsingContext.ArgumentExpressions:
29965                 // This is not safe to reuse for the same reason as the 'AssignmentExpression'
29966                 // cases.  i.e. a property assignment may end with an expression, and thus might
29967                 // have lookahead far beyond it's old node.
29968                 // case ParsingContext.ObjectLiteralMembers:
29969                 // This is probably not safe to reuse.  There can be speculative parsing with
29970                 // type names in a heritage clause.  There can be generic names in the type
29971                 // name list, and there can be left hand side expressions (which can have type
29972                 // arguments.)
29973                 // case ParsingContext.HeritageClauseElement:
29974                 // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
29975                 // on any given element. Same for children.
29976                 // case ParsingContext.JsxAttributes:
29977                 // case ParsingContext.JsxChildren:
29978             }
29979             return false;
29980         }
29981         function isReusableClassMember(node) {
29982             if (node) {
29983                 switch (node.kind) {
29984                     case 166 /* Constructor */:
29985                     case 171 /* IndexSignature */:
29986                     case 167 /* GetAccessor */:
29987                     case 168 /* SetAccessor */:
29988                     case 163 /* PropertyDeclaration */:
29989                     case 229 /* SemicolonClassElement */:
29990                         return true;
29991                     case 165 /* MethodDeclaration */:
29992                         // Method declarations are not necessarily reusable.  An object-literal
29993                         // may have a method calls "constructor(...)" and we must reparse that
29994                         // into an actual .ConstructorDeclaration.
29995                         var methodDeclaration = node;
29996                         var nameIsConstructor = methodDeclaration.name.kind === 78 /* Identifier */ &&
29997                             methodDeclaration.name.originalKeywordKind === 132 /* ConstructorKeyword */;
29998                         return !nameIsConstructor;
29999                 }
30000             }
30001             return false;
30002         }
30003         function isReusableSwitchClause(node) {
30004             if (node) {
30005                 switch (node.kind) {
30006                     case 284 /* CaseClause */:
30007                     case 285 /* DefaultClause */:
30008                         return true;
30009                 }
30010             }
30011             return false;
30012         }
30013         function isReusableStatement(node) {
30014             if (node) {
30015                 switch (node.kind) {
30016                     case 251 /* FunctionDeclaration */:
30017                     case 232 /* VariableStatement */:
30018                     case 230 /* Block */:
30019                     case 234 /* IfStatement */:
30020                     case 233 /* ExpressionStatement */:
30021                     case 246 /* ThrowStatement */:
30022                     case 242 /* ReturnStatement */:
30023                     case 244 /* SwitchStatement */:
30024                     case 241 /* BreakStatement */:
30025                     case 240 /* ContinueStatement */:
30026                     case 238 /* ForInStatement */:
30027                     case 239 /* ForOfStatement */:
30028                     case 237 /* ForStatement */:
30029                     case 236 /* WhileStatement */:
30030                     case 243 /* WithStatement */:
30031                     case 231 /* EmptyStatement */:
30032                     case 247 /* TryStatement */:
30033                     case 245 /* LabeledStatement */:
30034                     case 235 /* DoStatement */:
30035                     case 248 /* DebuggerStatement */:
30036                     case 261 /* ImportDeclaration */:
30037                     case 260 /* ImportEqualsDeclaration */:
30038                     case 267 /* ExportDeclaration */:
30039                     case 266 /* ExportAssignment */:
30040                     case 256 /* ModuleDeclaration */:
30041                     case 252 /* ClassDeclaration */:
30042                     case 253 /* InterfaceDeclaration */:
30043                     case 255 /* EnumDeclaration */:
30044                     case 254 /* TypeAliasDeclaration */:
30045                         return true;
30046                 }
30047             }
30048             return false;
30049         }
30050         function isReusableEnumMember(node) {
30051             return node.kind === 291 /* EnumMember */;
30052         }
30053         function isReusableTypeMember(node) {
30054             if (node) {
30055                 switch (node.kind) {
30056                     case 170 /* ConstructSignature */:
30057                     case 164 /* MethodSignature */:
30058                     case 171 /* IndexSignature */:
30059                     case 162 /* PropertySignature */:
30060                     case 169 /* CallSignature */:
30061                         return true;
30062                 }
30063             }
30064             return false;
30065         }
30066         function isReusableVariableDeclaration(node) {
30067             if (node.kind !== 249 /* VariableDeclaration */) {
30068                 return false;
30069             }
30070             // Very subtle incremental parsing bug.  Consider the following code:
30071             //
30072             //      let v = new List < A, B
30073             //
30074             // This is actually legal code.  It's a list of variable declarators "v = new List<A"
30075             // on one side and "B" on the other. If you then change that to:
30076             //
30077             //      let v = new List < A, B >()
30078             //
30079             // then we have a problem.  "v = new List<A" doesn't intersect the change range, so we
30080             // start reparsing at "B" and we completely fail to handle this properly.
30081             //
30082             // In order to prevent this, we do not allow a variable declarator to be reused if it
30083             // has an initializer.
30084             var variableDeclarator = node;
30085             return variableDeclarator.initializer === undefined;
30086         }
30087         function isReusableParameter(node) {
30088             if (node.kind !== 160 /* Parameter */) {
30089                 return false;
30090             }
30091             // See the comment in isReusableVariableDeclaration for why we do this.
30092             var parameter = node;
30093             return parameter.initializer === undefined;
30094         }
30095         // Returns true if we should abort parsing.
30096         function abortParsingListOrMoveToNextToken(kind) {
30097             parsingContextErrors(kind);
30098             if (isInSomeParsingContext()) {
30099                 return true;
30100             }
30101             nextToken();
30102             return false;
30103         }
30104         function parsingContextErrors(context) {
30105             switch (context) {
30106                 case 0 /* SourceElements */: return parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected);
30107                 case 1 /* BlockStatements */: return parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected);
30108                 case 2 /* SwitchClauses */: return parseErrorAtCurrentToken(ts.Diagnostics.case_or_default_expected);
30109                 case 3 /* SwitchClauseStatements */: return parseErrorAtCurrentToken(ts.Diagnostics.Statement_expected);
30110                 case 18 /* RestProperties */: // fallthrough
30111                 case 4 /* TypeMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_or_signature_expected);
30112                 case 5 /* ClassMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected);
30113                 case 6 /* EnumMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Enum_member_expected);
30114                 case 7 /* HeritageClauseElement */: return parseErrorAtCurrentToken(ts.Diagnostics.Expression_expected);
30115                 case 8 /* VariableDeclarations */:
30116                     return ts.isKeyword(token())
30117                         ? parseErrorAtCurrentToken(ts.Diagnostics._0_is_not_allowed_as_a_variable_declaration_name, ts.tokenToString(token()))
30118                         : parseErrorAtCurrentToken(ts.Diagnostics.Variable_declaration_expected);
30119                 case 9 /* ObjectBindingElements */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_destructuring_pattern_expected);
30120                 case 10 /* ArrayBindingElements */: return parseErrorAtCurrentToken(ts.Diagnostics.Array_element_destructuring_pattern_expected);
30121                 case 11 /* ArgumentExpressions */: return parseErrorAtCurrentToken(ts.Diagnostics.Argument_expression_expected);
30122                 case 12 /* ObjectLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_assignment_expected);
30123                 case 15 /* ArrayLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Expression_or_comma_expected);
30124                 case 17 /* JSDocParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected);
30125                 case 16 /* Parameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected);
30126                 case 19 /* TypeParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_parameter_declaration_expected);
30127                 case 20 /* TypeArguments */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_argument_expected);
30128                 case 21 /* TupleElementTypes */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_expected);
30129                 case 22 /* HeritageClauses */: return parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token_expected);
30130                 case 23 /* ImportOrExportSpecifiers */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected);
30131                 case 13 /* JsxAttributes */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected);
30132                 case 14 /* JsxChildren */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected);
30133                 default: return [undefined]; // TODO: GH#18217 `default: Debug.assertNever(context);`
30134             }
30135         }
30136         // Parses a comma-delimited list of elements
30137         function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
30138             var saveParsingContext = parsingContext;
30139             parsingContext |= 1 << kind;
30140             var list = [];
30141             var listPos = getNodePos();
30142             var commaStart = -1; // Meaning the previous token was not a comma
30143             while (true) {
30144                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
30145                     var startPos = scanner.getStartPos();
30146                     list.push(parseListElement(kind, parseElement));
30147                     commaStart = scanner.getTokenPos();
30148                     if (parseOptional(27 /* CommaToken */)) {
30149                         // No need to check for a zero length node since we know we parsed a comma
30150                         continue;
30151                     }
30152                     commaStart = -1; // Back to the state where the last token was not a comma
30153                     if (isListTerminator(kind)) {
30154                         break;
30155                     }
30156                     // We didn't get a comma, and the list wasn't terminated, explicitly parse
30157                     // out a comma so we give a good error message.
30158                     parseExpected(27 /* CommaToken */, getExpectedCommaDiagnostic(kind));
30159                     // If the token was a semicolon, and the caller allows that, then skip it and
30160                     // continue.  This ensures we get back on track and don't result in tons of
30161                     // parse errors.  For example, this can happen when people do things like use
30162                     // a semicolon to delimit object literal members.   Note: we'll have already
30163                     // reported an error when we called parseExpected above.
30164                     if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) {
30165                         nextToken();
30166                     }
30167                     if (startPos === scanner.getStartPos()) {
30168                         // What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever
30169                         // Consume a token to advance the parser in some way and avoid an infinite loop
30170                         // This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions,
30171                         // or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied
30172                         nextToken();
30173                     }
30174                     continue;
30175                 }
30176                 if (isListTerminator(kind)) {
30177                     break;
30178                 }
30179                 if (abortParsingListOrMoveToNextToken(kind)) {
30180                     break;
30181                 }
30182             }
30183             parsingContext = saveParsingContext;
30184             // Recording the trailing comma is deliberately done after the previous
30185             // loop, and not just if we see a list terminator. This is because the list
30186             // may have ended incorrectly, but it is still important to know if there
30187             // was a trailing comma.
30188             // Check if the last token was a comma.
30189             // Always preserve a trailing comma by marking it on the NodeArray
30190             return createNodeArray(list, listPos, /*end*/ undefined, commaStart >= 0);
30191         }
30192         function getExpectedCommaDiagnostic(kind) {
30193             return kind === 6 /* EnumMembers */ ? ts.Diagnostics.An_enum_member_name_must_be_followed_by_a_or : undefined;
30194         }
30195         function createMissingList() {
30196             var list = createNodeArray([], getNodePos());
30197             list.isMissingList = true;
30198             return list;
30199         }
30200         function isMissingList(arr) {
30201             return !!arr.isMissingList;
30202         }
30203         function parseBracketedList(kind, parseElement, open, close) {
30204             if (parseExpected(open)) {
30205                 var result = parseDelimitedList(kind, parseElement);
30206                 parseExpected(close);
30207                 return result;
30208             }
30209             return createMissingList();
30210         }
30211         function parseEntityName(allowReservedWords, diagnosticMessage) {
30212             var pos = getNodePos();
30213             var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
30214             var dotPos = getNodePos();
30215             while (parseOptional(24 /* DotToken */)) {
30216                 if (token() === 29 /* LessThanToken */) {
30217                     // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
30218                     entity.jsdocDotPos = dotPos;
30219                     break;
30220                 }
30221                 dotPos = getNodePos();
30222                 entity = finishNode(factory.createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false)), pos);
30223             }
30224             return entity;
30225         }
30226         function createQualifiedName(entity, name) {
30227             return finishNode(factory.createQualifiedName(entity, name), entity.pos);
30228         }
30229         function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) {
30230             // Technically a keyword is valid here as all identifiers and keywords are identifier names.
30231             // However, often we'll encounter this in error situations when the identifier or keyword
30232             // is actually starting another valid construct.
30233             //
30234             // So, we check for the following specific case:
30235             //
30236             //      name.
30237             //      identifierOrKeyword identifierNameOrKeyword
30238             //
30239             // Note: the newlines are important here.  For example, if that above code
30240             // were rewritten into:
30241             //
30242             //      name.identifierOrKeyword
30243             //      identifierNameOrKeyword
30244             //
30245             // Then we would consider it valid.  That's because ASI would take effect and
30246             // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
30247             // In the first case though, ASI will not take effect because there is not a
30248             // line terminator after the identifier or keyword.
30249             if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) {
30250                 var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
30251                 if (matchesPattern) {
30252                     // Report that we need an identifier.  However, report it right after the dot,
30253                     // and not on the next token.  This is because the next token might actually
30254                     // be an identifier and the error would be quite confusing.
30255                     return createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
30256                 }
30257             }
30258             if (token() === 79 /* PrivateIdentifier */) {
30259                 var node = parsePrivateIdentifier();
30260                 return allowPrivateIdentifiers ? node : createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
30261             }
30262             return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
30263         }
30264         function parseTemplateSpans(isTaggedTemplate) {
30265             var pos = getNodePos();
30266             var list = [];
30267             var node;
30268             do {
30269                 node = parseTemplateSpan(isTaggedTemplate);
30270                 list.push(node);
30271             } while (node.literal.kind === 16 /* TemplateMiddle */);
30272             return createNodeArray(list, pos);
30273         }
30274         function parseTemplateExpression(isTaggedTemplate) {
30275             var pos = getNodePos();
30276             return finishNode(factory.createTemplateExpression(parseTemplateHead(isTaggedTemplate), parseTemplateSpans(isTaggedTemplate)), pos);
30277         }
30278         function parseTemplateType() {
30279             var pos = getNodePos();
30280             return finishNode(factory.createTemplateLiteralType(parseTemplateHead(/*isTaggedTemplate*/ false), parseTemplateTypeSpans()), pos);
30281         }
30282         function parseTemplateTypeSpans() {
30283             var pos = getNodePos();
30284             var list = [];
30285             var node;
30286             do {
30287                 node = parseTemplateTypeSpan();
30288                 list.push(node);
30289             } while (node.literal.kind === 16 /* TemplateMiddle */);
30290             return createNodeArray(list, pos);
30291         }
30292         function parseTemplateTypeSpan() {
30293             var pos = getNodePos();
30294             return finishNode(factory.createTemplateLiteralTypeSpan(parseType(), parseLiteralOfTemplateSpan(/*isTaggedTemplate*/ false)), pos);
30295         }
30296         function parseLiteralOfTemplateSpan(isTaggedTemplate) {
30297             if (token() === 19 /* CloseBraceToken */) {
30298                 reScanTemplateToken(isTaggedTemplate);
30299                 return parseTemplateMiddleOrTemplateTail();
30300             }
30301             else {
30302                 // TODO(rbuckton): Do we need to call `parseExpectedToken` or can we just call `createMissingNode` directly?
30303                 return parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */));
30304             }
30305         }
30306         function parseTemplateSpan(isTaggedTemplate) {
30307             var pos = getNodePos();
30308             return finishNode(factory.createTemplateSpan(allowInAnd(parseExpression), parseLiteralOfTemplateSpan(isTaggedTemplate)), pos);
30309         }
30310         function parseLiteralNode() {
30311             return parseLiteralLikeNode(token());
30312         }
30313         function parseTemplateHead(isTaggedTemplate) {
30314             if (isTaggedTemplate) {
30315                 reScanTemplateHeadOrNoSubstitutionTemplate();
30316             }
30317             var fragment = parseLiteralLikeNode(token());
30318             ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
30319             return fragment;
30320         }
30321         function parseTemplateMiddleOrTemplateTail() {
30322             var fragment = parseLiteralLikeNode(token());
30323             ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind");
30324             return fragment;
30325         }
30326         function getTemplateLiteralRawText(kind) {
30327             var isLast = kind === 14 /* NoSubstitutionTemplateLiteral */ || kind === 17 /* TemplateTail */;
30328             var tokenText = scanner.getTokenText();
30329             return tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2));
30330         }
30331         function parseLiteralLikeNode(kind) {
30332             var pos = getNodePos();
30333             var node = ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, scanner.getTokenValue(), getTemplateLiteralRawText(kind), scanner.getTokenFlags() & 2048 /* TemplateLiteralLikeFlags */) :
30334                 // Octal literals are not allowed in strict mode or ES5
30335                 // Note that theoretically the following condition would hold true literals like 009,
30336                 // which is not octal. But because of how the scanner separates the tokens, we would
30337                 // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
30338                 // We also do not need to check for negatives because any prefix operator would be part of a
30339                 // parent unary expression.
30340                 kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral(scanner.getTokenValue(), scanner.getNumericLiteralFlags()) :
30341                     kind === 10 /* StringLiteral */ ? factory.createStringLiteral(scanner.getTokenValue(), /*isSingleQuote*/ undefined, scanner.hasExtendedUnicodeEscape()) :
30342                         ts.isLiteralKind(kind) ? factory.createLiteralLikeNode(kind, scanner.getTokenValue()) :
30343                             ts.Debug.fail();
30344             if (scanner.hasExtendedUnicodeEscape()) {
30345                 node.hasExtendedUnicodeEscape = true;
30346             }
30347             if (scanner.isUnterminated()) {
30348                 node.isUnterminated = true;
30349             }
30350             nextToken();
30351             return finishNode(node, pos);
30352         }
30353         // TYPES
30354         function parseEntityNameOfTypeReference() {
30355             return parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
30356         }
30357         function parseTypeArgumentsOfTypeReference() {
30358             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
30359                 return parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
30360             }
30361         }
30362         function parseTypeReference() {
30363             var pos = getNodePos();
30364             return finishNode(factory.createTypeReferenceNode(parseEntityNameOfTypeReference(), parseTypeArgumentsOfTypeReference()), pos);
30365         }
30366         // If true, we should abort parsing an error function.
30367         function typeHasArrowFunctionBlockingParseError(node) {
30368             switch (node.kind) {
30369                 case 173 /* TypeReference */:
30370                     return ts.nodeIsMissing(node.typeName);
30371                 case 174 /* FunctionType */:
30372                 case 175 /* ConstructorType */: {
30373                     var _a = node, parameters = _a.parameters, type = _a.type;
30374                     return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
30375                 }
30376                 case 186 /* ParenthesizedType */:
30377                     return typeHasArrowFunctionBlockingParseError(node.type);
30378                 default:
30379                     return false;
30380             }
30381         }
30382         function parseThisTypePredicate(lhs) {
30383             nextToken();
30384             return finishNode(factory.createTypePredicateNode(/*assertsModifier*/ undefined, lhs, parseType()), lhs.pos);
30385         }
30386         function parseThisTypeNode() {
30387             var pos = getNodePos();
30388             nextToken();
30389             return finishNode(factory.createThisTypeNode(), pos);
30390         }
30391         function parseJSDocAllType() {
30392             var pos = getNodePos();
30393             nextToken();
30394             return finishNode(factory.createJSDocAllType(), pos);
30395         }
30396         function parseJSDocNonNullableType() {
30397             var pos = getNodePos();
30398             nextToken();
30399             return finishNode(factory.createJSDocNonNullableType(parseNonArrayType()), pos);
30400         }
30401         function parseJSDocUnknownOrNullableType() {
30402             var pos = getNodePos();
30403             // skip the ?
30404             nextToken();
30405             // Need to lookahead to decide if this is a nullable or unknown type.
30406             // Here are cases where we'll pick the unknown type:
30407             //
30408             //      Foo(?,
30409             //      { a: ? }
30410             //      Foo(?)
30411             //      Foo<?>
30412             //      Foo(?=
30413             //      (?|
30414             if (token() === 27 /* CommaToken */ ||
30415                 token() === 19 /* CloseBraceToken */ ||
30416                 token() === 21 /* CloseParenToken */ ||
30417                 token() === 31 /* GreaterThanToken */ ||
30418                 token() === 62 /* EqualsToken */ ||
30419                 token() === 51 /* BarToken */) {
30420                 return finishNode(factory.createJSDocUnknownType(), pos);
30421             }
30422             else {
30423                 return finishNode(factory.createJSDocNullableType(parseType()), pos);
30424             }
30425         }
30426         function parseJSDocFunctionType() {
30427             var pos = getNodePos();
30428             var hasJSDoc = hasPrecedingJSDocComment();
30429             if (lookAhead(nextTokenIsOpenParen)) {
30430                 nextToken();
30431                 var parameters = parseParameters(4 /* Type */ | 32 /* JSDoc */);
30432                 var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
30433                 return withJSDoc(finishNode(factory.createJSDocFunctionType(parameters, type), pos), hasJSDoc);
30434             }
30435             return finishNode(factory.createTypeReferenceNode(parseIdentifierName(), /*typeArguments*/ undefined), pos);
30436         }
30437         function parseJSDocParameter() {
30438             var pos = getNodePos();
30439             var name;
30440             if (token() === 107 /* ThisKeyword */ || token() === 102 /* NewKeyword */) {
30441                 name = parseIdentifierName();
30442                 parseExpected(58 /* ColonToken */);
30443             }
30444             return finishNode(factory.createParameterDeclaration(
30445             /*decorators*/ undefined, 
30446             /*modifiers*/ undefined, 
30447             /*dotDotDotToken*/ undefined, 
30448             // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier?
30449             name, 
30450             /*questionToken*/ undefined, parseJSDocType(), 
30451             /*initializer*/ undefined), pos);
30452         }
30453         function parseJSDocType() {
30454             scanner.setInJSDocType(true);
30455             var pos = getNodePos();
30456             if (parseOptional(139 /* ModuleKeyword */)) {
30457                 // TODO(rbuckton): We never set the type for a JSDocNamepathType. What should we put here?
30458                 var moduleTag = factory.createJSDocNamepathType(/*type*/ undefined);
30459                 terminate: while (true) {
30460                     switch (token()) {
30461                         case 19 /* CloseBraceToken */:
30462                         case 1 /* EndOfFileToken */:
30463                         case 27 /* CommaToken */:
30464                         case 5 /* WhitespaceTrivia */:
30465                             break terminate;
30466                         default:
30467                             nextTokenJSDoc();
30468                     }
30469                 }
30470                 scanner.setInJSDocType(false);
30471                 return finishNode(moduleTag, pos);
30472             }
30473             var hasDotDotDot = parseOptional(25 /* DotDotDotToken */);
30474             var type = parseTypeOrTypePredicate();
30475             scanner.setInJSDocType(false);
30476             if (hasDotDotDot) {
30477                 type = finishNode(factory.createJSDocVariadicType(type), pos);
30478             }
30479             if (token() === 62 /* EqualsToken */) {
30480                 nextToken();
30481                 return finishNode(factory.createJSDocOptionalType(type), pos);
30482             }
30483             return type;
30484         }
30485         function parseTypeQuery() {
30486             var pos = getNodePos();
30487             parseExpected(111 /* TypeOfKeyword */);
30488             return finishNode(factory.createTypeQueryNode(parseEntityName(/*allowReservedWords*/ true)), pos);
30489         }
30490         function parseTypeParameter() {
30491             var pos = getNodePos();
30492             var name = parseIdentifier();
30493             var constraint;
30494             var expression;
30495             if (parseOptional(93 /* ExtendsKeyword */)) {
30496                 // It's not uncommon for people to write improper constraints to a generic.  If the
30497                 // user writes a constraint that is an expression and not an actual type, then parse
30498                 // it out as an expression (so we can recover well), but report that a type is needed
30499                 // instead.
30500                 if (isStartOfType() || !isStartOfExpression()) {
30501                     constraint = parseType();
30502                 }
30503                 else {
30504                     // It was not a type, and it looked like an expression.  Parse out an expression
30505                     // here so we recover well.  Note: it is important that we call parseUnaryExpression
30506                     // and not parseExpression here.  If the user has:
30507                     //
30508                     //      <T extends "">
30509                     //
30510                     // We do *not* want to consume the `>` as we're consuming the expression for "".
30511                     expression = parseUnaryExpressionOrHigher();
30512                 }
30513             }
30514             var defaultType = parseOptional(62 /* EqualsToken */) ? parseType() : undefined;
30515             var node = factory.createTypeParameterDeclaration(name, constraint, defaultType);
30516             node.expression = expression;
30517             return finishNode(node, pos);
30518         }
30519         function parseTypeParameters() {
30520             if (token() === 29 /* LessThanToken */) {
30521                 return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
30522             }
30523         }
30524         function isStartOfParameter(isJSDocParameter) {
30525             return token() === 25 /* DotDotDotToken */ ||
30526                 isBindingIdentifierOrPrivateIdentifierOrPattern() ||
30527                 ts.isModifierKind(token()) ||
30528                 token() === 59 /* AtToken */ ||
30529                 isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
30530         }
30531         function parseNameOfParameter(modifiers) {
30532             // FormalParameter [Yield,Await]:
30533             //      BindingElement[?Yield,?Await]
30534             var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
30535             if (ts.getFullWidth(name) === 0 && !ts.some(modifiers) && ts.isModifierKind(token())) {
30536                 // in cases like
30537                 // 'use strict'
30538                 // function foo(static)
30539                 // isParameter('static') === true, because of isModifier('static')
30540                 // however 'static' is not a legal identifier in a strict mode.
30541                 // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
30542                 // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
30543                 // to avoid this we'll advance cursor to the next token.
30544                 nextToken();
30545             }
30546             return name;
30547         }
30548         function parseParameterInOuterAwaitContext() {
30549             return parseParameterWorker(/*inOuterAwaitContext*/ true);
30550         }
30551         function parseParameter() {
30552             return parseParameterWorker(/*inOuterAwaitContext*/ false);
30553         }
30554         function parseParameterWorker(inOuterAwaitContext) {
30555             var pos = getNodePos();
30556             var hasJSDoc = hasPrecedingJSDocComment();
30557             if (token() === 107 /* ThisKeyword */) {
30558                 var node_1 = factory.createParameterDeclaration(
30559                 /*decorators*/ undefined, 
30560                 /*modifiers*/ undefined, 
30561                 /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), 
30562                 /*questionToken*/ undefined, parseTypeAnnotation(), 
30563                 /*initializer*/ undefined);
30564                 return withJSDoc(finishNode(node_1, pos), hasJSDoc);
30565             }
30566             // FormalParameter [Yield,Await]:
30567             //      BindingElement[?Yield,?Await]
30568             // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context.
30569             var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators();
30570             var savedTopLevel = topLevel;
30571             topLevel = false;
30572             var modifiers = parseModifiers();
30573             var node = withJSDoc(finishNode(factory.createParameterDeclaration(decorators, modifiers, parseOptionalToken(25 /* DotDotDotToken */), parseNameOfParameter(modifiers), parseOptionalToken(57 /* QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc);
30574             topLevel = savedTopLevel;
30575             return node;
30576         }
30577         function parseReturnType(returnToken, isType) {
30578             if (shouldParseReturnType(returnToken, isType)) {
30579                 return parseTypeOrTypePredicate();
30580             }
30581         }
30582         function shouldParseReturnType(returnToken, isType) {
30583             if (returnToken === 38 /* EqualsGreaterThanToken */) {
30584                 parseExpected(returnToken);
30585                 return true;
30586             }
30587             else if (parseOptional(58 /* ColonToken */)) {
30588                 return true;
30589             }
30590             else if (isType && token() === 38 /* EqualsGreaterThanToken */) {
30591                 // This is easy to get backward, especially in type contexts, so parse the type anyway
30592                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
30593                 nextToken();
30594                 return true;
30595             }
30596             return false;
30597         }
30598         function parseParametersWorker(flags) {
30599             // FormalParameters [Yield,Await]: (modified)
30600             //      [empty]
30601             //      FormalParameterList[?Yield,Await]
30602             //
30603             // FormalParameter[Yield,Await]: (modified)
30604             //      BindingElement[?Yield,Await]
30605             //
30606             // BindingElement [Yield,Await]: (modified)
30607             //      SingleNameBinding[?Yield,?Await]
30608             //      BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
30609             //
30610             // SingleNameBinding [Yield,Await]:
30611             //      BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
30612             var savedYieldContext = inYieldContext();
30613             var savedAwaitContext = inAwaitContext();
30614             setYieldContext(!!(flags & 1 /* Yield */));
30615             setAwaitContext(!!(flags & 2 /* Await */));
30616             var parameters = flags & 32 /* JSDoc */ ?
30617                 parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
30618                 parseDelimitedList(16 /* Parameters */, savedAwaitContext ? parseParameterInOuterAwaitContext : parseParameter);
30619             setYieldContext(savedYieldContext);
30620             setAwaitContext(savedAwaitContext);
30621             return parameters;
30622         }
30623         function parseParameters(flags) {
30624             // FormalParameters [Yield,Await]: (modified)
30625             //      [empty]
30626             //      FormalParameterList[?Yield,Await]
30627             //
30628             // FormalParameter[Yield,Await]: (modified)
30629             //      BindingElement[?Yield,Await]
30630             //
30631             // BindingElement [Yield,Await]: (modified)
30632             //      SingleNameBinding[?Yield,?Await]
30633             //      BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
30634             //
30635             // SingleNameBinding [Yield,Await]:
30636             //      BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
30637             if (!parseExpected(20 /* OpenParenToken */)) {
30638                 return createMissingList();
30639             }
30640             var parameters = parseParametersWorker(flags);
30641             parseExpected(21 /* CloseParenToken */);
30642             return parameters;
30643         }
30644         function parseTypeMemberSemicolon() {
30645             // We allow type members to be separated by commas or (possibly ASI) semicolons.
30646             // First check if it was a comma.  If so, we're done with the member.
30647             if (parseOptional(27 /* CommaToken */)) {
30648                 return;
30649             }
30650             // Didn't have a comma.  We must have a (possible ASI) semicolon.
30651             parseSemicolon();
30652         }
30653         function parseSignatureMember(kind) {
30654             var pos = getNodePos();
30655             var hasJSDoc = hasPrecedingJSDocComment();
30656             if (kind === 170 /* ConstructSignature */) {
30657                 parseExpected(102 /* NewKeyword */);
30658             }
30659             var typeParameters = parseTypeParameters();
30660             var parameters = parseParameters(4 /* Type */);
30661             var type = parseReturnType(58 /* ColonToken */, /*isType*/ true);
30662             parseTypeMemberSemicolon();
30663             var node = kind === 169 /* CallSignature */
30664                 ? factory.createCallSignature(typeParameters, parameters, type)
30665                 : factory.createConstructSignature(typeParameters, parameters, type);
30666             return withJSDoc(finishNode(node, pos), hasJSDoc);
30667         }
30668         function isIndexSignature() {
30669             return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
30670         }
30671         function isUnambiguouslyIndexSignature() {
30672             // The only allowed sequence is:
30673             //
30674             //   [id:
30675             //
30676             // However, for error recovery, we also check the following cases:
30677             //
30678             //   [...
30679             //   [id,
30680             //   [id?,
30681             //   [id?:
30682             //   [id?]
30683             //   [public id
30684             //   [private id
30685             //   [protected id
30686             //   []
30687             //
30688             nextToken();
30689             if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) {
30690                 return true;
30691             }
30692             if (ts.isModifierKind(token())) {
30693                 nextToken();
30694                 if (isIdentifier()) {
30695                     return true;
30696                 }
30697             }
30698             else if (!isIdentifier()) {
30699                 return false;
30700             }
30701             else {
30702                 // Skip the identifier
30703                 nextToken();
30704             }
30705             // A colon signifies a well formed indexer
30706             // A comma should be a badly formed indexer because comma expressions are not allowed
30707             // in computed properties.
30708             if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */) {
30709                 return true;
30710             }
30711             // Question mark could be an indexer with an optional property,
30712             // or it could be a conditional expression in a computed property.
30713             if (token() !== 57 /* QuestionToken */) {
30714                 return false;
30715             }
30716             // If any of the following tokens are after the question mark, it cannot
30717             // be a conditional expression, so treat it as an indexer.
30718             nextToken();
30719             return token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */;
30720         }
30721         function parseIndexSignatureDeclaration(pos, hasJSDoc, decorators, modifiers) {
30722             var parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
30723             var type = parseTypeAnnotation();
30724             parseTypeMemberSemicolon();
30725             var node = factory.createIndexSignature(decorators, modifiers, parameters, type);
30726             return withJSDoc(finishNode(node, pos), hasJSDoc);
30727         }
30728         function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) {
30729             var name = parsePropertyName();
30730             var questionToken = parseOptionalToken(57 /* QuestionToken */);
30731             var node;
30732             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
30733                 // Method signatures don't exist in expression contexts.  So they have neither
30734                 // [Yield] nor [Await]
30735                 var typeParameters = parseTypeParameters();
30736                 var parameters = parseParameters(4 /* Type */);
30737                 var type = parseReturnType(58 /* ColonToken */, /*isType*/ true);
30738                 node = factory.createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type);
30739             }
30740             else {
30741                 var type = parseTypeAnnotation();
30742                 node = factory.createPropertySignature(modifiers, name, questionToken, type);
30743                 // Although type literal properties cannot not have initializers, we attempt
30744                 // to parse an initializer so we can report in the checker that an interface
30745                 // property or type literal property cannot have an initializer.
30746                 if (token() === 62 /* EqualsToken */)
30747                     node.initializer = parseInitializer();
30748             }
30749             parseTypeMemberSemicolon();
30750             return withJSDoc(finishNode(node, pos), hasJSDoc);
30751         }
30752         function isTypeMemberStart() {
30753             // Return true if we have the start of a signature member
30754             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
30755                 return true;
30756             }
30757             var idToken = false;
30758             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier
30759             while (ts.isModifierKind(token())) {
30760                 idToken = true;
30761                 nextToken();
30762             }
30763             // Index signatures and computed property names are type members
30764             if (token() === 22 /* OpenBracketToken */) {
30765                 return true;
30766             }
30767             // Try to get the first property-like token following all modifiers
30768             if (isLiteralPropertyName()) {
30769                 idToken = true;
30770                 nextToken();
30771             }
30772             // If we were able to get any potential identifier, check that it is
30773             // the start of a member declaration
30774             if (idToken) {
30775                 return token() === 20 /* OpenParenToken */ ||
30776                     token() === 29 /* LessThanToken */ ||
30777                     token() === 57 /* QuestionToken */ ||
30778                     token() === 58 /* ColonToken */ ||
30779                     token() === 27 /* CommaToken */ ||
30780                     canParseSemicolon();
30781             }
30782             return false;
30783         }
30784         function parseTypeMember() {
30785             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
30786                 return parseSignatureMember(169 /* CallSignature */);
30787             }
30788             if (token() === 102 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
30789                 return parseSignatureMember(170 /* ConstructSignature */);
30790             }
30791             var pos = getNodePos();
30792             var hasJSDoc = hasPrecedingJSDocComment();
30793             var modifiers = parseModifiers();
30794             if (isIndexSignature()) {
30795                 return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers);
30796             }
30797             return parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers);
30798         }
30799         function nextTokenIsOpenParenOrLessThan() {
30800             nextToken();
30801             return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */;
30802         }
30803         function nextTokenIsDot() {
30804             return nextToken() === 24 /* DotToken */;
30805         }
30806         function nextTokenIsOpenParenOrLessThanOrDot() {
30807             switch (nextToken()) {
30808                 case 20 /* OpenParenToken */:
30809                 case 29 /* LessThanToken */:
30810                 case 24 /* DotToken */:
30811                     return true;
30812             }
30813             return false;
30814         }
30815         function parseTypeLiteral() {
30816             var pos = getNodePos();
30817             return finishNode(factory.createTypeLiteralNode(parseObjectTypeMembers()), pos);
30818         }
30819         function parseObjectTypeMembers() {
30820             var members;
30821             if (parseExpected(18 /* OpenBraceToken */)) {
30822                 members = parseList(4 /* TypeMembers */, parseTypeMember);
30823                 parseExpected(19 /* CloseBraceToken */);
30824             }
30825             else {
30826                 members = createMissingList();
30827             }
30828             return members;
30829         }
30830         function isStartOfMappedType() {
30831             nextToken();
30832             if (token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
30833                 return nextToken() === 142 /* ReadonlyKeyword */;
30834             }
30835             if (token() === 142 /* ReadonlyKeyword */) {
30836                 nextToken();
30837             }
30838             return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 100 /* InKeyword */;
30839         }
30840         function parseMappedTypeParameter() {
30841             var pos = getNodePos();
30842             var name = parseIdentifierName();
30843             parseExpected(100 /* InKeyword */);
30844             var type = parseType();
30845             return finishNode(factory.createTypeParameterDeclaration(name, type, /*defaultType*/ undefined), pos);
30846         }
30847         function parseMappedType() {
30848             var pos = getNodePos();
30849             parseExpected(18 /* OpenBraceToken */);
30850             var readonlyToken;
30851             if (token() === 142 /* ReadonlyKeyword */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
30852                 readonlyToken = parseTokenNode();
30853                 if (readonlyToken.kind !== 142 /* ReadonlyKeyword */) {
30854                     parseExpected(142 /* ReadonlyKeyword */);
30855                 }
30856             }
30857             parseExpected(22 /* OpenBracketToken */);
30858             var typeParameter = parseMappedTypeParameter();
30859             var nameType = parseOptional(126 /* AsKeyword */) ? parseType() : undefined;
30860             parseExpected(23 /* CloseBracketToken */);
30861             var questionToken;
30862             if (token() === 57 /* QuestionToken */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
30863                 questionToken = parseTokenNode();
30864                 if (questionToken.kind !== 57 /* QuestionToken */) {
30865                     parseExpected(57 /* QuestionToken */);
30866                 }
30867             }
30868             var type = parseTypeAnnotation();
30869             parseSemicolon();
30870             parseExpected(19 /* CloseBraceToken */);
30871             return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), pos);
30872         }
30873         function parseTupleElementType() {
30874             var pos = getNodePos();
30875             if (parseOptional(25 /* DotDotDotToken */)) {
30876                 return finishNode(factory.createRestTypeNode(parseType()), pos);
30877             }
30878             var type = parseType();
30879             if (ts.isJSDocNullableType(type) && type.pos === type.type.pos) {
30880                 var node = factory.createOptionalTypeNode(type.type);
30881                 ts.setTextRange(node, type);
30882                 node.flags = type.flags;
30883                 return node;
30884             }
30885             return type;
30886         }
30887         function isNextTokenColonOrQuestionColon() {
30888             return nextToken() === 58 /* ColonToken */ || (token() === 57 /* QuestionToken */ && nextToken() === 58 /* ColonToken */);
30889         }
30890         function isTupleElementName() {
30891             if (token() === 25 /* DotDotDotToken */) {
30892                 return ts.tokenIsIdentifierOrKeyword(nextToken()) && isNextTokenColonOrQuestionColon();
30893             }
30894             return ts.tokenIsIdentifierOrKeyword(token()) && isNextTokenColonOrQuestionColon();
30895         }
30896         function parseTupleElementNameOrTupleElementType() {
30897             if (lookAhead(isTupleElementName)) {
30898                 var pos = getNodePos();
30899                 var hasJSDoc = hasPrecedingJSDocComment();
30900                 var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
30901                 var name = parseIdentifierName();
30902                 var questionToken = parseOptionalToken(57 /* QuestionToken */);
30903                 parseExpected(58 /* ColonToken */);
30904                 var type = parseTupleElementType();
30905                 var node = factory.createNamedTupleMember(dotDotDotToken, name, questionToken, type);
30906                 return withJSDoc(finishNode(node, pos), hasJSDoc);
30907             }
30908             return parseTupleElementType();
30909         }
30910         function parseTupleType() {
30911             var pos = getNodePos();
30912             return finishNode(factory.createTupleTypeNode(parseBracketedList(21 /* TupleElementTypes */, parseTupleElementNameOrTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */)), pos);
30913         }
30914         function parseParenthesizedType() {
30915             var pos = getNodePos();
30916             parseExpected(20 /* OpenParenToken */);
30917             var type = parseType();
30918             parseExpected(21 /* CloseParenToken */);
30919             return finishNode(factory.createParenthesizedType(type), pos);
30920         }
30921         function parseModifiersForConstructorType() {
30922             var modifiers;
30923             if (token() === 125 /* AbstractKeyword */) {
30924                 var pos = getNodePos();
30925                 nextToken();
30926                 var modifier = finishNode(factory.createToken(125 /* AbstractKeyword */), pos);
30927                 modifiers = createNodeArray([modifier], pos);
30928             }
30929             return modifiers;
30930         }
30931         function parseFunctionOrConstructorType() {
30932             var pos = getNodePos();
30933             var hasJSDoc = hasPrecedingJSDocComment();
30934             var modifiers = parseModifiersForConstructorType();
30935             var isConstructorType = parseOptional(102 /* NewKeyword */);
30936             var typeParameters = parseTypeParameters();
30937             var parameters = parseParameters(4 /* Type */);
30938             var type = parseReturnType(38 /* EqualsGreaterThanToken */, /*isType*/ false);
30939             var node = isConstructorType
30940                 ? factory.createConstructorTypeNode(modifiers, typeParameters, parameters, type)
30941                 : factory.createFunctionTypeNode(typeParameters, parameters, type);
30942             if (!isConstructorType)
30943                 node.modifiers = modifiers;
30944             return withJSDoc(finishNode(node, pos), hasJSDoc);
30945         }
30946         function parseKeywordAndNoDot() {
30947             var node = parseTokenNode();
30948             return token() === 24 /* DotToken */ ? undefined : node;
30949         }
30950         function parseLiteralTypeNode(negative) {
30951             var pos = getNodePos();
30952             if (negative) {
30953                 nextToken();
30954             }
30955             var expression = token() === 109 /* TrueKeyword */ || token() === 94 /* FalseKeyword */ || token() === 103 /* NullKeyword */ ?
30956                 parseTokenNode() :
30957                 parseLiteralLikeNode(token());
30958             if (negative) {
30959                 expression = finishNode(factory.createPrefixUnaryExpression(40 /* MinusToken */, expression), pos);
30960             }
30961             return finishNode(factory.createLiteralTypeNode(expression), pos);
30962         }
30963         function isStartOfTypeOfImportType() {
30964             nextToken();
30965             return token() === 99 /* ImportKeyword */;
30966         }
30967         function parseImportType() {
30968             sourceFlags |= 1048576 /* PossiblyContainsDynamicImport */;
30969             var pos = getNodePos();
30970             var isTypeOf = parseOptional(111 /* TypeOfKeyword */);
30971             parseExpected(99 /* ImportKeyword */);
30972             parseExpected(20 /* OpenParenToken */);
30973             var type = parseType();
30974             parseExpected(21 /* CloseParenToken */);
30975             var qualifier = parseOptional(24 /* DotToken */) ? parseEntityNameOfTypeReference() : undefined;
30976             var typeArguments = parseTypeArgumentsOfTypeReference();
30977             return finishNode(factory.createImportTypeNode(type, qualifier, typeArguments, isTypeOf), pos);
30978         }
30979         function nextTokenIsNumericOrBigIntLiteral() {
30980             nextToken();
30981             return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */;
30982         }
30983         function parseNonArrayType() {
30984             switch (token()) {
30985                 case 128 /* AnyKeyword */:
30986                 case 152 /* UnknownKeyword */:
30987                 case 147 /* StringKeyword */:
30988                 case 144 /* NumberKeyword */:
30989                 case 155 /* BigIntKeyword */:
30990                 case 148 /* SymbolKeyword */:
30991                 case 131 /* BooleanKeyword */:
30992                 case 150 /* UndefinedKeyword */:
30993                 case 141 /* NeverKeyword */:
30994                 case 145 /* ObjectKeyword */:
30995                     // If these are followed by a dot, then parse these out as a dotted type reference instead.
30996                     return tryParse(parseKeywordAndNoDot) || parseTypeReference();
30997                 case 65 /* AsteriskEqualsToken */:
30998                     // If there is '*=', treat it as * followed by postfix =
30999                     scanner.reScanAsteriskEqualsToken();
31000                 // falls through
31001                 case 41 /* AsteriskToken */:
31002                     return parseJSDocAllType();
31003                 case 60 /* QuestionQuestionToken */:
31004                     // If there is '??', treat it as prefix-'?' in JSDoc type.
31005                     scanner.reScanQuestionToken();
31006                 // falls through
31007                 case 57 /* QuestionToken */:
31008                     return parseJSDocUnknownOrNullableType();
31009                 case 97 /* FunctionKeyword */:
31010                     return parseJSDocFunctionType();
31011                 case 53 /* ExclamationToken */:
31012                     return parseJSDocNonNullableType();
31013                 case 14 /* NoSubstitutionTemplateLiteral */:
31014                 case 10 /* StringLiteral */:
31015                 case 8 /* NumericLiteral */:
31016                 case 9 /* BigIntLiteral */:
31017                 case 109 /* TrueKeyword */:
31018                 case 94 /* FalseKeyword */:
31019                 case 103 /* NullKeyword */:
31020                     return parseLiteralTypeNode();
31021                 case 40 /* MinusToken */:
31022                     return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
31023                 case 113 /* VoidKeyword */:
31024                     return parseTokenNode();
31025                 case 107 /* ThisKeyword */: {
31026                     var thisKeyword = parseThisTypeNode();
31027                     if (token() === 137 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
31028                         return parseThisTypePredicate(thisKeyword);
31029                     }
31030                     else {
31031                         return thisKeyword;
31032                     }
31033                 }
31034                 case 111 /* TypeOfKeyword */:
31035                     return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
31036                 case 18 /* OpenBraceToken */:
31037                     return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
31038                 case 22 /* OpenBracketToken */:
31039                     return parseTupleType();
31040                 case 20 /* OpenParenToken */:
31041                     return parseParenthesizedType();
31042                 case 99 /* ImportKeyword */:
31043                     return parseImportType();
31044                 case 127 /* AssertsKeyword */:
31045                     return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
31046                 case 15 /* TemplateHead */:
31047                     return parseTemplateType();
31048                 default:
31049                     return parseTypeReference();
31050             }
31051         }
31052         function isStartOfType(inStartOfParameter) {
31053             switch (token()) {
31054                 case 128 /* AnyKeyword */:
31055                 case 152 /* UnknownKeyword */:
31056                 case 147 /* StringKeyword */:
31057                 case 144 /* NumberKeyword */:
31058                 case 155 /* BigIntKeyword */:
31059                 case 131 /* BooleanKeyword */:
31060                 case 142 /* ReadonlyKeyword */:
31061                 case 148 /* SymbolKeyword */:
31062                 case 151 /* UniqueKeyword */:
31063                 case 113 /* VoidKeyword */:
31064                 case 150 /* UndefinedKeyword */:
31065                 case 103 /* NullKeyword */:
31066                 case 107 /* ThisKeyword */:
31067                 case 111 /* TypeOfKeyword */:
31068                 case 141 /* NeverKeyword */:
31069                 case 18 /* OpenBraceToken */:
31070                 case 22 /* OpenBracketToken */:
31071                 case 29 /* LessThanToken */:
31072                 case 51 /* BarToken */:
31073                 case 50 /* AmpersandToken */:
31074                 case 102 /* NewKeyword */:
31075                 case 10 /* StringLiteral */:
31076                 case 8 /* NumericLiteral */:
31077                 case 9 /* BigIntLiteral */:
31078                 case 109 /* TrueKeyword */:
31079                 case 94 /* FalseKeyword */:
31080                 case 145 /* ObjectKeyword */:
31081                 case 41 /* AsteriskToken */:
31082                 case 57 /* QuestionToken */:
31083                 case 53 /* ExclamationToken */:
31084                 case 25 /* DotDotDotToken */:
31085                 case 135 /* InferKeyword */:
31086                 case 99 /* ImportKeyword */:
31087                 case 127 /* AssertsKeyword */:
31088                 case 14 /* NoSubstitutionTemplateLiteral */:
31089                 case 15 /* TemplateHead */:
31090                     return true;
31091                 case 97 /* FunctionKeyword */:
31092                     return !inStartOfParameter;
31093                 case 40 /* MinusToken */:
31094                     return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
31095                 case 20 /* OpenParenToken */:
31096                     // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
31097                     // or something that starts a type. We don't want to consider things like '(1)' a type.
31098                     return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
31099                 default:
31100                     return isIdentifier();
31101             }
31102         }
31103         function isStartOfParenthesizedOrFunctionType() {
31104             nextToken();
31105             return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
31106         }
31107         function parsePostfixTypeOrHigher() {
31108             var pos = getNodePos();
31109             var type = parseNonArrayType();
31110             while (!scanner.hasPrecedingLineBreak()) {
31111                 switch (token()) {
31112                     case 53 /* ExclamationToken */:
31113                         nextToken();
31114                         type = finishNode(factory.createJSDocNonNullableType(type), pos);
31115                         break;
31116                     case 57 /* QuestionToken */:
31117                         // If next token is start of a type we have a conditional type
31118                         if (lookAhead(nextTokenIsStartOfType)) {
31119                             return type;
31120                         }
31121                         nextToken();
31122                         type = finishNode(factory.createJSDocNullableType(type), pos);
31123                         break;
31124                     case 22 /* OpenBracketToken */:
31125                         parseExpected(22 /* OpenBracketToken */);
31126                         if (isStartOfType()) {
31127                             var indexType = parseType();
31128                             parseExpected(23 /* CloseBracketToken */);
31129                             type = finishNode(factory.createIndexedAccessTypeNode(type, indexType), pos);
31130                         }
31131                         else {
31132                             parseExpected(23 /* CloseBracketToken */);
31133                             type = finishNode(factory.createArrayTypeNode(type), pos);
31134                         }
31135                         break;
31136                     default:
31137                         return type;
31138                 }
31139             }
31140             return type;
31141         }
31142         function parseTypeOperator(operator) {
31143             var pos = getNodePos();
31144             parseExpected(operator);
31145             return finishNode(factory.createTypeOperatorNode(operator, parseTypeOperatorOrHigher()), pos);
31146         }
31147         function parseTypeParameterOfInferType() {
31148             var pos = getNodePos();
31149             return finishNode(factory.createTypeParameterDeclaration(parseIdentifier(), 
31150             /*constraint*/ undefined, 
31151             /*defaultType*/ undefined), pos);
31152         }
31153         function parseInferType() {
31154             var pos = getNodePos();
31155             parseExpected(135 /* InferKeyword */);
31156             return finishNode(factory.createInferTypeNode(parseTypeParameterOfInferType()), pos);
31157         }
31158         function parseTypeOperatorOrHigher() {
31159             var operator = token();
31160             switch (operator) {
31161                 case 138 /* KeyOfKeyword */:
31162                 case 151 /* UniqueKeyword */:
31163                 case 142 /* ReadonlyKeyword */:
31164                     return parseTypeOperator(operator);
31165                 case 135 /* InferKeyword */:
31166                     return parseInferType();
31167             }
31168             return parsePostfixTypeOrHigher();
31169         }
31170         function parseFunctionOrConstructorTypeToError(isInUnionType) {
31171             // the function type and constructor type shorthand notation
31172             // are not allowed directly in unions and intersections, but we'll
31173             // try to parse them gracefully and issue a helpful message.
31174             if (isStartOfFunctionTypeOrConstructorType()) {
31175                 var type = parseFunctionOrConstructorType();
31176                 var diagnostic = void 0;
31177                 if (ts.isFunctionTypeNode(type)) {
31178                     diagnostic = isInUnionType
31179                         ? ts.Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_a_union_type
31180                         : ts.Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type;
31181                 }
31182                 else {
31183                     diagnostic = isInUnionType
31184                         ? ts.Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type
31185                         : ts.Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type;
31186                 }
31187                 parseErrorAtRange(type, diagnostic);
31188                 return type;
31189             }
31190             return undefined;
31191         }
31192         function parseUnionOrIntersectionType(operator, parseConstituentType, createTypeNode) {
31193             var pos = getNodePos();
31194             var isUnionType = operator === 51 /* BarToken */;
31195             var hasLeadingOperator = parseOptional(operator);
31196             var type = hasLeadingOperator && parseFunctionOrConstructorTypeToError(isUnionType)
31197                 || parseConstituentType();
31198             if (token() === operator || hasLeadingOperator) {
31199                 var types = [type];
31200                 while (parseOptional(operator)) {
31201                     types.push(parseFunctionOrConstructorTypeToError(isUnionType) || parseConstituentType());
31202                 }
31203                 type = finishNode(createTypeNode(createNodeArray(types, pos)), pos);
31204             }
31205             return type;
31206         }
31207         function parseIntersectionTypeOrHigher() {
31208             return parseUnionOrIntersectionType(50 /* AmpersandToken */, parseTypeOperatorOrHigher, factory.createIntersectionTypeNode);
31209         }
31210         function parseUnionTypeOrHigher() {
31211             return parseUnionOrIntersectionType(51 /* BarToken */, parseIntersectionTypeOrHigher, factory.createUnionTypeNode);
31212         }
31213         function nextTokenIsNewKeyword() {
31214             nextToken();
31215             return token() === 102 /* NewKeyword */;
31216         }
31217         function isStartOfFunctionTypeOrConstructorType() {
31218             if (token() === 29 /* LessThanToken */) {
31219                 return true;
31220             }
31221             if (token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType)) {
31222                 return true;
31223             }
31224             return token() === 102 /* NewKeyword */ ||
31225                 token() === 125 /* AbstractKeyword */ && lookAhead(nextTokenIsNewKeyword);
31226         }
31227         function skipParameterStart() {
31228             if (ts.isModifierKind(token())) {
31229                 // Skip modifiers
31230                 parseModifiers();
31231             }
31232             if (isIdentifier() || token() === 107 /* ThisKeyword */) {
31233                 nextToken();
31234                 return true;
31235             }
31236             if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) {
31237                 // Return true if we can parse an array or object binding pattern with no errors
31238                 var previousErrorCount = parseDiagnostics.length;
31239                 parseIdentifierOrPattern();
31240                 return previousErrorCount === parseDiagnostics.length;
31241             }
31242             return false;
31243         }
31244         function isUnambiguouslyStartOfFunctionType() {
31245             nextToken();
31246             if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) {
31247                 // ( )
31248                 // ( ...
31249                 return true;
31250             }
31251             if (skipParameterStart()) {
31252                 // We successfully skipped modifiers (if any) and an identifier or binding pattern,
31253                 // now see if we have something that indicates a parameter declaration
31254                 if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ ||
31255                     token() === 57 /* QuestionToken */ || token() === 62 /* EqualsToken */) {
31256                     // ( xxx :
31257                     // ( xxx ,
31258                     // ( xxx ?
31259                     // ( xxx =
31260                     return true;
31261                 }
31262                 if (token() === 21 /* CloseParenToken */) {
31263                     nextToken();
31264                     if (token() === 38 /* EqualsGreaterThanToken */) {
31265                         // ( xxx ) =>
31266                         return true;
31267                     }
31268                 }
31269             }
31270             return false;
31271         }
31272         function parseTypeOrTypePredicate() {
31273             var pos = getNodePos();
31274             var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
31275             var type = parseType();
31276             if (typePredicateVariable) {
31277                 return finishNode(factory.createTypePredicateNode(/*assertsModifier*/ undefined, typePredicateVariable, type), pos);
31278             }
31279             else {
31280                 return type;
31281             }
31282         }
31283         function parseTypePredicatePrefix() {
31284             var id = parseIdentifier();
31285             if (token() === 137 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
31286                 nextToken();
31287                 return id;
31288             }
31289         }
31290         function parseAssertsTypePredicate() {
31291             var pos = getNodePos();
31292             var assertsModifier = parseExpectedToken(127 /* AssertsKeyword */);
31293             var parameterName = token() === 107 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier();
31294             var type = parseOptional(137 /* IsKeyword */) ? parseType() : undefined;
31295             return finishNode(factory.createTypePredicateNode(assertsModifier, parameterName, type), pos);
31296         }
31297         function parseType() {
31298             // The rules about 'yield' only apply to actual code/expression contexts.  They don't
31299             // apply to 'type' contexts.  So we disable these parameters here before moving on.
31300             return doOutsideOfContext(40960 /* TypeExcludesFlags */, parseTypeWorker);
31301         }
31302         function parseTypeWorker(noConditionalTypes) {
31303             if (isStartOfFunctionTypeOrConstructorType()) {
31304                 return parseFunctionOrConstructorType();
31305             }
31306             var pos = getNodePos();
31307             var type = parseUnionTypeOrHigher();
31308             if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(93 /* ExtendsKeyword */)) {
31309                 // The type following 'extends' is not permitted to be another conditional type
31310                 var extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
31311                 parseExpected(57 /* QuestionToken */);
31312                 var trueType = parseTypeWorker();
31313                 parseExpected(58 /* ColonToken */);
31314                 var falseType = parseTypeWorker();
31315                 return finishNode(factory.createConditionalTypeNode(type, extendsType, trueType, falseType), pos);
31316             }
31317             return type;
31318         }
31319         function parseTypeAnnotation() {
31320             return parseOptional(58 /* ColonToken */) ? parseType() : undefined;
31321         }
31322         // EXPRESSIONS
31323         function isStartOfLeftHandSideExpression() {
31324             switch (token()) {
31325                 case 107 /* ThisKeyword */:
31326                 case 105 /* SuperKeyword */:
31327                 case 103 /* NullKeyword */:
31328                 case 109 /* TrueKeyword */:
31329                 case 94 /* FalseKeyword */:
31330                 case 8 /* NumericLiteral */:
31331                 case 9 /* BigIntLiteral */:
31332                 case 10 /* StringLiteral */:
31333                 case 14 /* NoSubstitutionTemplateLiteral */:
31334                 case 15 /* TemplateHead */:
31335                 case 20 /* OpenParenToken */:
31336                 case 22 /* OpenBracketToken */:
31337                 case 18 /* OpenBraceToken */:
31338                 case 97 /* FunctionKeyword */:
31339                 case 83 /* ClassKeyword */:
31340                 case 102 /* NewKeyword */:
31341                 case 43 /* SlashToken */:
31342                 case 67 /* SlashEqualsToken */:
31343                 case 78 /* Identifier */:
31344                     return true;
31345                 case 99 /* ImportKeyword */:
31346                     return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
31347                 default:
31348                     return isIdentifier();
31349             }
31350         }
31351         function isStartOfExpression() {
31352             if (isStartOfLeftHandSideExpression()) {
31353                 return true;
31354             }
31355             switch (token()) {
31356                 case 39 /* PlusToken */:
31357                 case 40 /* MinusToken */:
31358                 case 54 /* TildeToken */:
31359                 case 53 /* ExclamationToken */:
31360                 case 88 /* DeleteKeyword */:
31361                 case 111 /* TypeOfKeyword */:
31362                 case 113 /* VoidKeyword */:
31363                 case 45 /* PlusPlusToken */:
31364                 case 46 /* MinusMinusToken */:
31365                 case 29 /* LessThanToken */:
31366                 case 130 /* AwaitKeyword */:
31367                 case 124 /* YieldKeyword */:
31368                 case 79 /* PrivateIdentifier */:
31369                     // Yield/await always starts an expression.  Either it is an identifier (in which case
31370                     // it is definitely an expression).  Or it's a keyword (either because we're in
31371                     // a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
31372                     return true;
31373                 default:
31374                     // Error tolerance.  If we see the start of some binary operator, we consider
31375                     // that the start of an expression.  That way we'll parse out a missing identifier,
31376                     // give a good message about an identifier being missing, and then consume the
31377                     // rest of the binary expression.
31378                     if (isBinaryOperator()) {
31379                         return true;
31380                     }
31381                     return isIdentifier();
31382             }
31383         }
31384         function isStartOfExpressionStatement() {
31385             // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
31386             return token() !== 18 /* OpenBraceToken */ &&
31387                 token() !== 97 /* FunctionKeyword */ &&
31388                 token() !== 83 /* ClassKeyword */ &&
31389                 token() !== 59 /* AtToken */ &&
31390                 isStartOfExpression();
31391         }
31392         function parseExpression() {
31393             // Expression[in]:
31394             //      AssignmentExpression[in]
31395             //      Expression[in] , AssignmentExpression[in]
31396             // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
31397             var saveDecoratorContext = inDecoratorContext();
31398             if (saveDecoratorContext) {
31399                 setDecoratorContext(/*val*/ false);
31400             }
31401             var pos = getNodePos();
31402             var expr = parseAssignmentExpressionOrHigher();
31403             var operatorToken;
31404             while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) {
31405                 expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(), pos);
31406             }
31407             if (saveDecoratorContext) {
31408                 setDecoratorContext(/*val*/ true);
31409             }
31410             return expr;
31411         }
31412         function parseInitializer() {
31413             return parseOptional(62 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined;
31414         }
31415         function parseAssignmentExpressionOrHigher() {
31416             //  AssignmentExpression[in,yield]:
31417             //      1) ConditionalExpression[?in,?yield]
31418             //      2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
31419             //      3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
31420             //      4) ArrowFunctionExpression[?in,?yield]
31421             //      5) AsyncArrowFunctionExpression[in,yield,await]
31422             //      6) [+Yield] YieldExpression[?In]
31423             //
31424             // Note: for ease of implementation we treat productions '2' and '3' as the same thing.
31425             // (i.e. they're both BinaryExpressions with an assignment operator in it).
31426             // First, do the simple check if we have a YieldExpression (production '6').
31427             if (isYieldExpression()) {
31428                 return parseYieldExpression();
31429             }
31430             // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
31431             // parameter list or is an async arrow function.
31432             // AsyncArrowFunctionExpression:
31433             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
31434             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
31435             // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
31436             // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
31437             //
31438             // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
31439             // not a LeftHandSideExpression, nor does it start a ConditionalExpression.  So we are done
31440             // with AssignmentExpression if we see one.
31441             var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
31442             if (arrowExpression) {
31443                 return arrowExpression;
31444             }
31445             // Now try to see if we're in production '1', '2' or '3'.  A conditional expression can
31446             // start with a LogicalOrExpression, while the assignment productions can only start with
31447             // LeftHandSideExpressions.
31448             //
31449             // So, first, we try to just parse out a BinaryExpression.  If we get something that is a
31450             // LeftHandSide or higher, then we can try to parse out the assignment expression part.
31451             // Otherwise, we try to parse out the conditional expression bit.  We want to allow any
31452             // binary expression here, so we pass in the 'lowest' precedence here so that it matches
31453             // and consumes anything.
31454             var pos = getNodePos();
31455             var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
31456             // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
31457             // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
31458             // identifier and the current token is an arrow.
31459             if (expr.kind === 78 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
31460                 return parseSimpleArrowFunctionExpression(pos, expr, /*asyncModifier*/ undefined);
31461             }
31462             // Now see if we might be in cases '2' or '3'.
31463             // If the expression was a LHS expression, and we have an assignment operator, then
31464             // we're in '2' or '3'. Consume the assignment and return.
31465             //
31466             // Note: we call reScanGreaterToken so that we get an appropriately merged token
31467             // for cases like `> > =` becoming `>>=`
31468             if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) {
31469                 return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(), pos);
31470             }
31471             // It wasn't an assignment or a lambda.  This is a conditional expression:
31472             return parseConditionalExpressionRest(expr, pos);
31473         }
31474         function isYieldExpression() {
31475             if (token() === 124 /* YieldKeyword */) {
31476                 // If we have a 'yield' keyword, and this is a context where yield expressions are
31477                 // allowed, then definitely parse out a yield expression.
31478                 if (inYieldContext()) {
31479                     return true;
31480                 }
31481                 // We're in a context where 'yield expr' is not allowed.  However, if we can
31482                 // definitely tell that the user was trying to parse a 'yield expr' and not
31483                 // just a normal expr that start with a 'yield' identifier, then parse out
31484                 // a 'yield expr'.  We can then report an error later that they are only
31485                 // allowed in generator expressions.
31486                 //
31487                 // for example, if we see 'yield(foo)', then we'll have to treat that as an
31488                 // invocation expression of something called 'yield'.  However, if we have
31489                 // 'yield foo' then that is not legal as a normal expression, so we can
31490                 // definitely recognize this as a yield expression.
31491                 //
31492                 // for now we just check if the next token is an identifier.  More heuristics
31493                 // can be added here later as necessary.  We just need to make sure that we
31494                 // don't accidentally consume something legal.
31495                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
31496             }
31497             return false;
31498         }
31499         function nextTokenIsIdentifierOnSameLine() {
31500             nextToken();
31501             return !scanner.hasPrecedingLineBreak() && isIdentifier();
31502         }
31503         function parseYieldExpression() {
31504             var pos = getNodePos();
31505             // YieldExpression[In] :
31506             //      yield
31507             //      yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
31508             //      yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
31509             nextToken();
31510             if (!scanner.hasPrecedingLineBreak() &&
31511                 (token() === 41 /* AsteriskToken */ || isStartOfExpression())) {
31512                 return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* AsteriskToken */), parseAssignmentExpressionOrHigher()), pos);
31513             }
31514             else {
31515                 // if the next token is not on the same line as yield.  or we don't have an '*' or
31516                 // the start of an expression, then this is just a simple "yield" expression.
31517                 return finishNode(factory.createYieldExpression(/*asteriskToken*/ undefined, /*expression*/ undefined), pos);
31518             }
31519         }
31520         function parseSimpleArrowFunctionExpression(pos, identifier, asyncModifier) {
31521             ts.Debug.assert(token() === 38 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
31522             var parameter = factory.createParameterDeclaration(
31523             /*decorators*/ undefined, 
31524             /*modifiers*/ undefined, 
31525             /*dotDotDotToken*/ undefined, identifier, 
31526             /*questionToken*/ undefined, 
31527             /*type*/ undefined, 
31528             /*initializer*/ undefined);
31529             finishNode(parameter, identifier.pos);
31530             var parameters = createNodeArray([parameter], parameter.pos, parameter.end);
31531             var equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
31532             var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
31533             var node = factory.createArrowFunction(asyncModifier, /*typeParameters*/ undefined, parameters, /*type*/ undefined, equalsGreaterThanToken, body);
31534             return addJSDocComment(finishNode(node, pos));
31535         }
31536         function tryParseParenthesizedArrowFunctionExpression() {
31537             var triState = isParenthesizedArrowFunctionExpression();
31538             if (triState === 0 /* False */) {
31539                 // It's definitely not a parenthesized arrow function expression.
31540                 return undefined;
31541             }
31542             // If we definitely have an arrow function, then we can just parse one, not requiring a
31543             // following => or { token. Otherwise, we *might* have an arrow function.  Try to parse
31544             // it out, but don't allow any ambiguity, and return 'undefined' if this could be an
31545             // expression instead.
31546             return triState === 1 /* True */ ?
31547                 parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true) :
31548                 tryParse(parsePossibleParenthesizedArrowFunctionExpression);
31549         }
31550         //  True        -> We definitely expect a parenthesized arrow function here.
31551         //  False       -> There *cannot* be a parenthesized arrow function here.
31552         //  Unknown     -> There *might* be a parenthesized arrow function here.
31553         //                 Speculatively look ahead to be sure, and rollback if not.
31554         function isParenthesizedArrowFunctionExpression() {
31555             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 129 /* AsyncKeyword */) {
31556                 return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
31557             }
31558             if (token() === 38 /* EqualsGreaterThanToken */) {
31559                 // ERROR RECOVERY TWEAK:
31560                 // If we see a standalone => try to parse it as an arrow function expression as that's
31561                 // likely what the user intended to write.
31562                 return 1 /* True */;
31563             }
31564             // Definitely not a parenthesized arrow function.
31565             return 0 /* False */;
31566         }
31567         function isParenthesizedArrowFunctionExpressionWorker() {
31568             if (token() === 129 /* AsyncKeyword */) {
31569                 nextToken();
31570                 if (scanner.hasPrecedingLineBreak()) {
31571                     return 0 /* False */;
31572                 }
31573                 if (token() !== 20 /* OpenParenToken */ && token() !== 29 /* LessThanToken */) {
31574                     return 0 /* False */;
31575                 }
31576             }
31577             var first = token();
31578             var second = nextToken();
31579             if (first === 20 /* OpenParenToken */) {
31580                 if (second === 21 /* CloseParenToken */) {
31581                     // Simple cases: "() =>", "(): ", and "() {".
31582                     // This is an arrow function with no parameters.
31583                     // The last one is not actually an arrow function,
31584                     // but this is probably what the user intended.
31585                     var third = nextToken();
31586                     switch (third) {
31587                         case 38 /* EqualsGreaterThanToken */:
31588                         case 58 /* ColonToken */:
31589                         case 18 /* OpenBraceToken */:
31590                             return 1 /* True */;
31591                         default:
31592                             return 0 /* False */;
31593                     }
31594                 }
31595                 // If encounter "([" or "({", this could be the start of a binding pattern.
31596                 // Examples:
31597                 //      ([ x ]) => { }
31598                 //      ({ x }) => { }
31599                 //      ([ x ])
31600                 //      ({ x })
31601                 if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) {
31602                     return 2 /* Unknown */;
31603                 }
31604                 // Simple case: "(..."
31605                 // This is an arrow function with a rest parameter.
31606                 if (second === 25 /* DotDotDotToken */) {
31607                     return 1 /* True */;
31608                 }
31609                 // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This
31610                 // isn't actually allowed, but we want to treat it as a lambda so we can provide
31611                 // a good error message.
31612                 if (ts.isModifierKind(second) && second !== 129 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
31613                     return 1 /* True */;
31614                 }
31615                 // If we had "(" followed by something that's not an identifier,
31616                 // then this definitely doesn't look like a lambda.  "this" is not
31617                 // valid, but we want to parse it and then give a semantic error.
31618                 if (!isIdentifier() && second !== 107 /* ThisKeyword */) {
31619                     return 0 /* False */;
31620                 }
31621                 switch (nextToken()) {
31622                     case 58 /* ColonToken */:
31623                         // If we have something like "(a:", then we must have a
31624                         // type-annotated parameter in an arrow function expression.
31625                         return 1 /* True */;
31626                     case 57 /* QuestionToken */:
31627                         nextToken();
31628                         // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
31629                         if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 62 /* EqualsToken */ || token() === 21 /* CloseParenToken */) {
31630                             return 1 /* True */;
31631                         }
31632                         // Otherwise it is definitely not a lambda.
31633                         return 0 /* False */;
31634                     case 27 /* CommaToken */:
31635                     case 62 /* EqualsToken */:
31636                     case 21 /* CloseParenToken */:
31637                         // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
31638                         return 2 /* Unknown */;
31639                 }
31640                 // It is definitely not an arrow function
31641                 return 0 /* False */;
31642             }
31643             else {
31644                 ts.Debug.assert(first === 29 /* LessThanToken */);
31645                 // If we have "<" not followed by an identifier,
31646                 // then this definitely is not an arrow function.
31647                 if (!isIdentifier()) {
31648                     return 0 /* False */;
31649                 }
31650                 // JSX overrides
31651                 if (languageVariant === 1 /* JSX */) {
31652                     var isArrowFunctionInJsx = lookAhead(function () {
31653                         var third = nextToken();
31654                         if (third === 93 /* ExtendsKeyword */) {
31655                             var fourth = nextToken();
31656                             switch (fourth) {
31657                                 case 62 /* EqualsToken */:
31658                                 case 31 /* GreaterThanToken */:
31659                                     return false;
31660                                 default:
31661                                     return true;
31662                             }
31663                         }
31664                         else if (third === 27 /* CommaToken */) {
31665                             return true;
31666                         }
31667                         return false;
31668                     });
31669                     if (isArrowFunctionInJsx) {
31670                         return 1 /* True */;
31671                     }
31672                     return 0 /* False */;
31673                 }
31674                 // This *could* be a parenthesized arrow function.
31675                 return 2 /* Unknown */;
31676             }
31677         }
31678         function parsePossibleParenthesizedArrowFunctionExpression() {
31679             var tokenPos = scanner.getTokenPos();
31680             if (notParenthesizedArrow === null || notParenthesizedArrow === void 0 ? void 0 : notParenthesizedArrow.has(tokenPos)) {
31681                 return undefined;
31682             }
31683             var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false);
31684             if (!result) {
31685                 (notParenthesizedArrow || (notParenthesizedArrow = new ts.Set())).add(tokenPos);
31686             }
31687             return result;
31688         }
31689         function tryParseAsyncSimpleArrowFunctionExpression() {
31690             // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
31691             if (token() === 129 /* AsyncKeyword */) {
31692                 if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
31693                     var pos = getNodePos();
31694                     var asyncModifier = parseModifiersForArrowFunction();
31695                     var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
31696                     return parseSimpleArrowFunctionExpression(pos, expr, asyncModifier);
31697                 }
31698             }
31699             return undefined;
31700         }
31701         function isUnParenthesizedAsyncArrowFunctionWorker() {
31702             // AsyncArrowFunctionExpression:
31703             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
31704             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
31705             if (token() === 129 /* AsyncKeyword */) {
31706                 nextToken();
31707                 // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
31708                 // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
31709                 if (scanner.hasPrecedingLineBreak() || token() === 38 /* EqualsGreaterThanToken */) {
31710                     return 0 /* False */;
31711                 }
31712                 // Check for un-parenthesized AsyncArrowFunction
31713                 var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
31714                 if (!scanner.hasPrecedingLineBreak() && expr.kind === 78 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
31715                     return 1 /* True */;
31716                 }
31717             }
31718             return 0 /* False */;
31719         }
31720         function parseParenthesizedArrowFunctionExpression(allowAmbiguity) {
31721             var pos = getNodePos();
31722             var hasJSDoc = hasPrecedingJSDocComment();
31723             var modifiers = parseModifiersForArrowFunction();
31724             var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
31725             // Arrow functions are never generators.
31726             //
31727             // If we're speculatively parsing a signature for a parenthesized arrow function, then
31728             // we have to have a complete parameter list.  Otherwise we might see something like
31729             // a => (b => c)
31730             // And think that "(b =>" was actually a parenthesized arrow function with a missing
31731             // close paren.
31732             var typeParameters = parseTypeParameters();
31733             var parameters;
31734             if (!parseExpected(20 /* OpenParenToken */)) {
31735                 if (!allowAmbiguity) {
31736                     return undefined;
31737                 }
31738                 parameters = createMissingList();
31739             }
31740             else {
31741                 parameters = parseParametersWorker(isAsync);
31742                 if (!parseExpected(21 /* CloseParenToken */) && !allowAmbiguity) {
31743                     return undefined;
31744                 }
31745             }
31746             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
31747             if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) {
31748                 return undefined;
31749             }
31750             // Parsing a signature isn't enough.
31751             // Parenthesized arrow signatures often look like other valid expressions.
31752             // For instance:
31753             //  - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
31754             //  - "(x,y)" is a comma expression parsed as a signature with two parameters.
31755             //  - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
31756             //  - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type.
31757             //
31758             // So we need just a bit of lookahead to ensure that it can only be a signature.
31759             var hasJSDocFunctionType = type && ts.isJSDocFunctionType(type);
31760             if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) {
31761                 // Returning undefined here will cause our caller to rewind to where we started from.
31762                 return undefined;
31763             }
31764             // If we have an arrow, then try to parse the body. Even if not, try to parse if we
31765             // have an opening brace, just in case we're in an error state.
31766             var lastToken = token();
31767             var equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
31768             var body = (lastToken === 38 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */)
31769                 ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier))
31770                 : parseIdentifier();
31771             var node = factory.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body);
31772             return withJSDoc(finishNode(node, pos), hasJSDoc);
31773         }
31774         function parseArrowFunctionExpressionBody(isAsync) {
31775             if (token() === 18 /* OpenBraceToken */) {
31776                 return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
31777             }
31778             if (token() !== 26 /* SemicolonToken */ &&
31779                 token() !== 97 /* FunctionKeyword */ &&
31780                 token() !== 83 /* ClassKeyword */ &&
31781                 isStartOfStatement() &&
31782                 !isStartOfExpressionStatement()) {
31783                 // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
31784                 //
31785                 // Here we try to recover from a potential error situation in the case where the
31786                 // user meant to supply a block. For example, if the user wrote:
31787                 //
31788                 //  a =>
31789                 //      let v = 0;
31790                 //  }
31791                 //
31792                 // they may be missing an open brace.  Check to see if that's the case so we can
31793                 // try to recover better.  If we don't do this, then the next close curly we see may end
31794                 // up preemptively closing the containing construct.
31795                 //
31796                 // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
31797                 return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
31798             }
31799             var savedTopLevel = topLevel;
31800             topLevel = false;
31801             var node = isAsync
31802                 ? doInAwaitContext(parseAssignmentExpressionOrHigher)
31803                 : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
31804             topLevel = savedTopLevel;
31805             return node;
31806         }
31807         function parseConditionalExpressionRest(leftOperand, pos) {
31808             // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
31809             var questionToken = parseOptionalToken(57 /* QuestionToken */);
31810             if (!questionToken) {
31811                 return leftOperand;
31812             }
31813             // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
31814             // we do not that for the 'whenFalse' part.
31815             var colonToken;
31816             return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher), colonToken = parseExpectedToken(58 /* ColonToken */), ts.nodeIsPresent(colonToken)
31817                 ? parseAssignmentExpressionOrHigher()
31818                 : createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */))), pos);
31819         }
31820         function parseBinaryExpressionOrHigher(precedence) {
31821             var pos = getNodePos();
31822             var leftOperand = parseUnaryExpressionOrHigher();
31823             return parseBinaryExpressionRest(precedence, leftOperand, pos);
31824         }
31825         function isInOrOfKeyword(t) {
31826             return t === 100 /* InKeyword */ || t === 156 /* OfKeyword */;
31827         }
31828         function parseBinaryExpressionRest(precedence, leftOperand, pos) {
31829             while (true) {
31830                 // We either have a binary operator here, or we're finished.  We call
31831                 // reScanGreaterToken so that we merge token sequences like > and = into >=
31832                 reScanGreaterToken();
31833                 var newPrecedence = ts.getBinaryOperatorPrecedence(token());
31834                 // Check the precedence to see if we should "take" this operator
31835                 // - For left associative operator (all operator but **), consume the operator,
31836                 //   recursively call the function below, and parse binaryExpression as a rightOperand
31837                 //   of the caller if the new precedence of the operator is greater then or equal to the current precedence.
31838                 //   For example:
31839                 //      a - b - c;
31840                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
31841                 //      a * b - c
31842                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
31843                 //      a - b * c;
31844                 //            ^token; leftOperand = b. Return b * c to the caller as a rightOperand
31845                 // - For right associative operator (**), consume the operator, recursively call the function
31846                 //   and parse binaryExpression as a rightOperand of the caller if the new precedence of
31847                 //   the operator is strictly grater than the current precedence
31848                 //   For example:
31849                 //      a ** b ** c;
31850                 //             ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
31851                 //      a - b ** c;
31852                 //            ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
31853                 //      a ** b - c
31854                 //             ^token; leftOperand = b. Return b to the caller as a rightOperand
31855                 var consumeCurrentOperator = token() === 42 /* AsteriskAsteriskToken */ ?
31856                     newPrecedence >= precedence :
31857                     newPrecedence > precedence;
31858                 if (!consumeCurrentOperator) {
31859                     break;
31860                 }
31861                 if (token() === 100 /* InKeyword */ && inDisallowInContext()) {
31862                     break;
31863                 }
31864                 if (token() === 126 /* AsKeyword */) {
31865                     // Make sure we *do* perform ASI for constructs like this:
31866                     //    var x = foo
31867                     //    as (Bar)
31868                     // This should be parsed as an initialized variable, followed
31869                     // by a function call to 'as' with the argument 'Bar'
31870                     if (scanner.hasPrecedingLineBreak()) {
31871                         break;
31872                     }
31873                     else {
31874                         nextToken();
31875                         leftOperand = makeAsExpression(leftOperand, parseType());
31876                     }
31877                 }
31878                 else {
31879                     leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence), pos);
31880                 }
31881             }
31882             return leftOperand;
31883         }
31884         function isBinaryOperator() {
31885             if (inDisallowInContext() && token() === 100 /* InKeyword */) {
31886                 return false;
31887             }
31888             return ts.getBinaryOperatorPrecedence(token()) > 0;
31889         }
31890         function makeBinaryExpression(left, operatorToken, right, pos) {
31891             return finishNode(factory.createBinaryExpression(left, operatorToken, right), pos);
31892         }
31893         function makeAsExpression(left, right) {
31894             return finishNode(factory.createAsExpression(left, right), left.pos);
31895         }
31896         function parsePrefixUnaryExpression() {
31897             var pos = getNodePos();
31898             return finishNode(factory.createPrefixUnaryExpression(token(), nextTokenAnd(parseSimpleUnaryExpression)), pos);
31899         }
31900         function parseDeleteExpression() {
31901             var pos = getNodePos();
31902             return finishNode(factory.createDeleteExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
31903         }
31904         function parseTypeOfExpression() {
31905             var pos = getNodePos();
31906             return finishNode(factory.createTypeOfExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
31907         }
31908         function parseVoidExpression() {
31909             var pos = getNodePos();
31910             return finishNode(factory.createVoidExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
31911         }
31912         function isAwaitExpression() {
31913             if (token() === 130 /* AwaitKeyword */) {
31914                 if (inAwaitContext()) {
31915                     return true;
31916                 }
31917                 // here we are using similar heuristics as 'isYieldExpression'
31918                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
31919             }
31920             return false;
31921         }
31922         function parseAwaitExpression() {
31923             var pos = getNodePos();
31924             return finishNode(factory.createAwaitExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
31925         }
31926         /**
31927          * Parse ES7 exponential expression and await expression
31928          *
31929          * ES7 ExponentiationExpression:
31930          *      1) UnaryExpression[?Yield]
31931          *      2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
31932          *
31933          */
31934         function parseUnaryExpressionOrHigher() {
31935             /**
31936              * ES7 UpdateExpression:
31937              *      1) LeftHandSideExpression[?Yield]
31938              *      2) LeftHandSideExpression[?Yield][no LineTerminator here]++
31939              *      3) LeftHandSideExpression[?Yield][no LineTerminator here]--
31940              *      4) ++UnaryExpression[?Yield]
31941              *      5) --UnaryExpression[?Yield]
31942              */
31943             if (isUpdateExpression()) {
31944                 var pos = getNodePos();
31945                 var updateExpression = parseUpdateExpression();
31946                 return token() === 42 /* AsteriskAsteriskToken */ ?
31947                     parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression, pos) :
31948                     updateExpression;
31949             }
31950             /**
31951              * ES7 UnaryExpression:
31952              *      1) UpdateExpression[?yield]
31953              *      2) delete UpdateExpression[?yield]
31954              *      3) void UpdateExpression[?yield]
31955              *      4) typeof UpdateExpression[?yield]
31956              *      5) + UpdateExpression[?yield]
31957              *      6) - UpdateExpression[?yield]
31958              *      7) ~ UpdateExpression[?yield]
31959              *      8) ! UpdateExpression[?yield]
31960              */
31961             var unaryOperator = token();
31962             var simpleUnaryExpression = parseSimpleUnaryExpression();
31963             if (token() === 42 /* AsteriskAsteriskToken */) {
31964                 var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
31965                 var end = simpleUnaryExpression.end;
31966                 if (simpleUnaryExpression.kind === 206 /* TypeAssertionExpression */) {
31967                     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);
31968                 }
31969                 else {
31970                     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));
31971                 }
31972             }
31973             return simpleUnaryExpression;
31974         }
31975         /**
31976          * Parse ES7 simple-unary expression or higher:
31977          *
31978          * ES7 UnaryExpression:
31979          *      1) UpdateExpression[?yield]
31980          *      2) delete UnaryExpression[?yield]
31981          *      3) void UnaryExpression[?yield]
31982          *      4) typeof UnaryExpression[?yield]
31983          *      5) + UnaryExpression[?yield]
31984          *      6) - UnaryExpression[?yield]
31985          *      7) ~ UnaryExpression[?yield]
31986          *      8) ! UnaryExpression[?yield]
31987          *      9) [+Await] await UnaryExpression[?yield]
31988          */
31989         function parseSimpleUnaryExpression() {
31990             switch (token()) {
31991                 case 39 /* PlusToken */:
31992                 case 40 /* MinusToken */:
31993                 case 54 /* TildeToken */:
31994                 case 53 /* ExclamationToken */:
31995                     return parsePrefixUnaryExpression();
31996                 case 88 /* DeleteKeyword */:
31997                     return parseDeleteExpression();
31998                 case 111 /* TypeOfKeyword */:
31999                     return parseTypeOfExpression();
32000                 case 113 /* VoidKeyword */:
32001                     return parseVoidExpression();
32002                 case 29 /* LessThanToken */:
32003                     // This is modified UnaryExpression grammar in TypeScript
32004                     //  UnaryExpression (modified):
32005                     //      < type > UnaryExpression
32006                     return parseTypeAssertion();
32007                 case 130 /* AwaitKeyword */:
32008                     if (isAwaitExpression()) {
32009                         return parseAwaitExpression();
32010                     }
32011                 // falls through
32012                 default:
32013                     return parseUpdateExpression();
32014             }
32015         }
32016         /**
32017          * Check if the current token can possibly be an ES7 increment expression.
32018          *
32019          * ES7 UpdateExpression:
32020          *      LeftHandSideExpression[?Yield]
32021          *      LeftHandSideExpression[?Yield][no LineTerminator here]++
32022          *      LeftHandSideExpression[?Yield][no LineTerminator here]--
32023          *      ++LeftHandSideExpression[?Yield]
32024          *      --LeftHandSideExpression[?Yield]
32025          */
32026         function isUpdateExpression() {
32027             // This function is called inside parseUnaryExpression to decide
32028             // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
32029             switch (token()) {
32030                 case 39 /* PlusToken */:
32031                 case 40 /* MinusToken */:
32032                 case 54 /* TildeToken */:
32033                 case 53 /* ExclamationToken */:
32034                 case 88 /* DeleteKeyword */:
32035                 case 111 /* TypeOfKeyword */:
32036                 case 113 /* VoidKeyword */:
32037                 case 130 /* AwaitKeyword */:
32038                     return false;
32039                 case 29 /* LessThanToken */:
32040                     // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
32041                     if (languageVariant !== 1 /* JSX */) {
32042                         return false;
32043                     }
32044                 // We are in JSX context and the token is part of JSXElement.
32045                 // falls through
32046                 default:
32047                     return true;
32048             }
32049         }
32050         /**
32051          * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
32052          *
32053          * ES7 UpdateExpression[yield]:
32054          *      1) LeftHandSideExpression[?yield]
32055          *      2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
32056          *      3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
32057          *      4) ++LeftHandSideExpression[?yield]
32058          *      5) --LeftHandSideExpression[?yield]
32059          * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
32060          */
32061         function parseUpdateExpression() {
32062             if (token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) {
32063                 var pos = getNodePos();
32064                 return finishNode(factory.createPrefixUnaryExpression(token(), nextTokenAnd(parseLeftHandSideExpressionOrHigher)), pos);
32065             }
32066             else if (languageVariant === 1 /* JSX */ && token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
32067                 // JSXElement is part of primaryExpression
32068                 return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
32069             }
32070             var expression = parseLeftHandSideExpressionOrHigher();
32071             ts.Debug.assert(ts.isLeftHandSideExpression(expression));
32072             if ((token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
32073                 var operator = token();
32074                 nextToken();
32075                 return finishNode(factory.createPostfixUnaryExpression(expression, operator), expression.pos);
32076             }
32077             return expression;
32078         }
32079         function parseLeftHandSideExpressionOrHigher() {
32080             // Original Ecma:
32081             // LeftHandSideExpression: See 11.2
32082             //      NewExpression
32083             //      CallExpression
32084             //
32085             // Our simplification:
32086             //
32087             // LeftHandSideExpression: See 11.2
32088             //      MemberExpression
32089             //      CallExpression
32090             //
32091             // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
32092             // MemberExpression to make our lives easier.
32093             //
32094             // to best understand the below code, it's important to see how CallExpression expands
32095             // out into its own productions:
32096             //
32097             // CallExpression:
32098             //      MemberExpression Arguments
32099             //      CallExpression Arguments
32100             //      CallExpression[Expression]
32101             //      CallExpression.IdentifierName
32102             //      import (AssignmentExpression)
32103             //      super Arguments
32104             //      super.IdentifierName
32105             //
32106             // Because of the recursion in these calls, we need to bottom out first. There are three
32107             // bottom out states we can run into: 1) We see 'super' which must start either of
32108             // the last two CallExpression productions. 2) We see 'import' which must start import call.
32109             // 3)we have a MemberExpression which either completes the LeftHandSideExpression,
32110             // or starts the beginning of the first four CallExpression productions.
32111             var pos = getNodePos();
32112             var expression;
32113             if (token() === 99 /* ImportKeyword */) {
32114                 if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
32115                     // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "("
32116                     // For example:
32117                     //      var foo3 = require("subfolder
32118                     //      import * as foo1 from "module-from-node
32119                     // We want this import to be a statement rather than import call expression
32120                     sourceFlags |= 1048576 /* PossiblyContainsDynamicImport */;
32121                     expression = parseTokenNode();
32122                 }
32123                 else if (lookAhead(nextTokenIsDot)) {
32124                     // This is an 'import.*' metaproperty (i.e. 'import.meta')
32125                     nextToken(); // advance past the 'import'
32126                     nextToken(); // advance past the dot
32127                     expression = finishNode(factory.createMetaProperty(99 /* ImportKeyword */, parseIdentifierName()), pos);
32128                     sourceFlags |= 2097152 /* PossiblyContainsImportMeta */;
32129                 }
32130                 else {
32131                     expression = parseMemberExpressionOrHigher();
32132                 }
32133             }
32134             else {
32135                 expression = token() === 105 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
32136             }
32137             // Now, we *may* be complete.  However, we might have consumed the start of a
32138             // CallExpression or OptionalExpression.  As such, we need to consume the rest
32139             // of it here to be complete.
32140             return parseCallExpressionRest(pos, expression);
32141         }
32142         function parseMemberExpressionOrHigher() {
32143             // Note: to make our lives simpler, we decompose the NewExpression productions and
32144             // place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
32145             // like so:
32146             //
32147             //   PrimaryExpression : See 11.1
32148             //      this
32149             //      Identifier
32150             //      Literal
32151             //      ArrayLiteral
32152             //      ObjectLiteral
32153             //      (Expression)
32154             //      FunctionExpression
32155             //      new MemberExpression Arguments?
32156             //
32157             //   MemberExpression : See 11.2
32158             //      PrimaryExpression
32159             //      MemberExpression[Expression]
32160             //      MemberExpression.IdentifierName
32161             //
32162             //   CallExpression : See 11.2
32163             //      MemberExpression
32164             //      CallExpression Arguments
32165             //      CallExpression[Expression]
32166             //      CallExpression.IdentifierName
32167             //
32168             // Technically this is ambiguous.  i.e. CallExpression defines:
32169             //
32170             //   CallExpression:
32171             //      CallExpression Arguments
32172             //
32173             // If you see: "new Foo()"
32174             //
32175             // Then that could be treated as a single ObjectCreationExpression, or it could be
32176             // treated as the invocation of "new Foo".  We disambiguate that in code (to match
32177             // the original grammar) by making sure that if we see an ObjectCreationExpression
32178             // we always consume arguments if they are there. So we treat "new Foo()" as an
32179             // object creation only, and not at all as an invocation.  Another way to think
32180             // about this is that for every "new" that we see, we will consume an argument list if
32181             // it is there as part of the *associated* object creation node.  Any additional
32182             // argument lists we see, will become invocation expressions.
32183             //
32184             // Because there are no other places in the grammar now that refer to FunctionExpression
32185             // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
32186             // production.
32187             //
32188             // Because CallExpression and MemberExpression are left recursive, we need to bottom out
32189             // of the recursion immediately.  So we parse out a primary expression to start with.
32190             var pos = getNodePos();
32191             var expression = parsePrimaryExpression();
32192             return parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true);
32193         }
32194         function parseSuperExpression() {
32195             var pos = getNodePos();
32196             var expression = parseTokenNode();
32197             if (token() === 29 /* LessThanToken */) {
32198                 var startPos = getNodePos();
32199                 var typeArguments = tryParse(parseTypeArgumentsInExpression);
32200                 if (typeArguments !== undefined) {
32201                     parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments);
32202                 }
32203             }
32204             if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) {
32205                 return expression;
32206             }
32207             // If we have seen "super" it must be followed by '(' or '.'.
32208             // If it wasn't then just try to parse out a '.' and report an error.
32209             parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
32210             // private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic
32211             return finishNode(factory.createPropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true)), pos);
32212         }
32213         function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext, topInvalidNodePosition) {
32214             var pos = getNodePos();
32215             var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
32216             var result;
32217             if (opening.kind === 275 /* JsxOpeningElement */) {
32218                 var children = parseJsxChildren(opening);
32219                 var closingElement = parseJsxClosingElement(inExpressionContext);
32220                 if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) {
32221                     parseErrorAtRange(closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, opening.tagName));
32222                 }
32223                 result = finishNode(factory.createJsxElement(opening, children, closingElement), pos);
32224             }
32225             else if (opening.kind === 278 /* JsxOpeningFragment */) {
32226                 result = finishNode(factory.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos);
32227             }
32228             else {
32229                 ts.Debug.assert(opening.kind === 274 /* JsxSelfClosingElement */);
32230                 // Nothing else to do for self-closing elements
32231                 result = opening;
32232             }
32233             // If the user writes the invalid code '<div></div><div></div>' in an expression context (i.e. not wrapped in
32234             // an enclosing tag), we'll naively try to parse   ^ this as a 'less than' operator and the remainder of the tag
32235             // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX
32236             // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter
32237             // does less damage and we can report a better error.
32238             // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
32239             // of one sort or another.
32240             if (inExpressionContext && token() === 29 /* LessThanToken */) {
32241                 var topBadPos_1 = typeof topInvalidNodePosition === "undefined" ? result.pos : topInvalidNodePosition;
32242                 var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true, topBadPos_1); });
32243                 if (invalidElement) {
32244                     var operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false);
32245                     ts.setTextRangePosWidth(operatorToken, invalidElement.pos, 0);
32246                     parseErrorAt(ts.skipTrivia(sourceText, topBadPos_1), invalidElement.end, ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
32247                     return finishNode(factory.createBinaryExpression(result, operatorToken, invalidElement), pos);
32248                 }
32249             }
32250             return result;
32251         }
32252         function parseJsxText() {
32253             var pos = getNodePos();
32254             var node = factory.createJsxText(scanner.getTokenValue(), currentToken === 12 /* JsxTextAllWhiteSpaces */);
32255             currentToken = scanner.scanJsxToken();
32256             return finishNode(node, pos);
32257         }
32258         function parseJsxChild(openingTag, token) {
32259             switch (token) {
32260                 case 1 /* EndOfFileToken */:
32261                     // If we hit EOF, issue the error at the tag that lacks the closing element
32262                     // rather than at the end of the file (which is useless)
32263                     if (ts.isJsxOpeningFragment(openingTag)) {
32264                         parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
32265                     }
32266                     else {
32267                         // We want the error span to cover only 'Foo.Bar' in < Foo.Bar >
32268                         // or to cover only 'Foo' in < Foo >
32269                         var tag = openingTag.tagName;
32270                         var start = ts.skipTrivia(sourceText, tag.pos);
32271                         parseErrorAt(start, tag.end, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
32272                     }
32273                     return undefined;
32274                 case 30 /* LessThanSlashToken */:
32275                 case 7 /* ConflictMarkerTrivia */:
32276                     return undefined;
32277                 case 11 /* JsxText */:
32278                 case 12 /* JsxTextAllWhiteSpaces */:
32279                     return parseJsxText();
32280                 case 18 /* OpenBraceToken */:
32281                     return parseJsxExpression(/*inExpressionContext*/ false);
32282                 case 29 /* LessThanToken */:
32283                     return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
32284                 default:
32285                     return ts.Debug.assertNever(token);
32286             }
32287         }
32288         function parseJsxChildren(openingTag) {
32289             var list = [];
32290             var listPos = getNodePos();
32291             var saveParsingContext = parsingContext;
32292             parsingContext |= 1 << 14 /* JsxChildren */;
32293             while (true) {
32294                 var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
32295                 if (!child)
32296                     break;
32297                 list.push(child);
32298             }
32299             parsingContext = saveParsingContext;
32300             return createNodeArray(list, listPos);
32301         }
32302         function parseJsxAttributes() {
32303             var pos = getNodePos();
32304             return finishNode(factory.createJsxAttributes(parseList(13 /* JsxAttributes */, parseJsxAttribute)), pos);
32305         }
32306         function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
32307             var pos = getNodePos();
32308             parseExpected(29 /* LessThanToken */);
32309             if (token() === 31 /* GreaterThanToken */) {
32310                 // See below for explanation of scanJsxText
32311                 scanJsxText();
32312                 return finishNode(factory.createJsxOpeningFragment(), pos);
32313             }
32314             var tagName = parseJsxElementName();
32315             var typeArguments = (contextFlags & 131072 /* JavaScriptFile */) === 0 ? tryParseTypeArguments() : undefined;
32316             var attributes = parseJsxAttributes();
32317             var node;
32318             if (token() === 31 /* GreaterThanToken */) {
32319                 // Closing tag, so scan the immediately-following text with the JSX scanning instead
32320                 // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
32321                 // scanning errors
32322                 scanJsxText();
32323                 node = factory.createJsxOpeningElement(tagName, typeArguments, attributes);
32324             }
32325             else {
32326                 parseExpected(43 /* SlashToken */);
32327                 if (inExpressionContext) {
32328                     parseExpected(31 /* GreaterThanToken */);
32329                 }
32330                 else {
32331                     parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
32332                     scanJsxText();
32333                 }
32334                 node = factory.createJsxSelfClosingElement(tagName, typeArguments, attributes);
32335             }
32336             return finishNode(node, pos);
32337         }
32338         function parseJsxElementName() {
32339             var pos = getNodePos();
32340             scanJsxIdentifier();
32341             // JsxElement can have name in the form of
32342             //      propertyAccessExpression
32343             //      primaryExpression in the form of an identifier and "this" keyword
32344             // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
32345             // We only want to consider "this" as a primaryExpression
32346             var expression = token() === 107 /* ThisKeyword */ ?
32347                 parseTokenNode() : parseIdentifierName();
32348             while (parseOptional(24 /* DotToken */)) {
32349                 expression = finishNode(factory.createPropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false)), pos);
32350             }
32351             return expression;
32352         }
32353         function parseJsxExpression(inExpressionContext) {
32354             var pos = getNodePos();
32355             if (!parseExpected(18 /* OpenBraceToken */)) {
32356                 return undefined;
32357             }
32358             var dotDotDotToken;
32359             var expression;
32360             if (token() !== 19 /* CloseBraceToken */) {
32361                 dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
32362                 // Only an AssignmentExpression is valid here per the JSX spec,
32363                 // but we can unambiguously parse a comma sequence and provide
32364                 // a better error message in grammar checking.
32365                 expression = parseExpression();
32366             }
32367             if (inExpressionContext) {
32368                 parseExpected(19 /* CloseBraceToken */);
32369             }
32370             else {
32371                 if (parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false)) {
32372                     scanJsxText();
32373                 }
32374             }
32375             return finishNode(factory.createJsxExpression(dotDotDotToken, expression), pos);
32376         }
32377         function parseJsxAttribute() {
32378             if (token() === 18 /* OpenBraceToken */) {
32379                 return parseJsxSpreadAttribute();
32380             }
32381             scanJsxIdentifier();
32382             var pos = getNodePos();
32383             return finishNode(factory.createJsxAttribute(parseIdentifierName(), token() !== 62 /* EqualsToken */ ? undefined :
32384                 scanJsxAttributeValue() === 10 /* StringLiteral */ ? parseLiteralNode() :
32385                     parseJsxExpression(/*inExpressionContext*/ true)), pos);
32386         }
32387         function parseJsxSpreadAttribute() {
32388             var pos = getNodePos();
32389             parseExpected(18 /* OpenBraceToken */);
32390             parseExpected(25 /* DotDotDotToken */);
32391             var expression = parseExpression();
32392             parseExpected(19 /* CloseBraceToken */);
32393             return finishNode(factory.createJsxSpreadAttribute(expression), pos);
32394         }
32395         function parseJsxClosingElement(inExpressionContext) {
32396             var pos = getNodePos();
32397             parseExpected(30 /* LessThanSlashToken */);
32398             var tagName = parseJsxElementName();
32399             if (inExpressionContext) {
32400                 parseExpected(31 /* GreaterThanToken */);
32401             }
32402             else {
32403                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
32404                 scanJsxText();
32405             }
32406             return finishNode(factory.createJsxClosingElement(tagName), pos);
32407         }
32408         function parseJsxClosingFragment(inExpressionContext) {
32409             var pos = getNodePos();
32410             parseExpected(30 /* LessThanSlashToken */);
32411             if (ts.tokenIsIdentifierOrKeyword(token())) {
32412                 parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
32413             }
32414             if (inExpressionContext) {
32415                 parseExpected(31 /* GreaterThanToken */);
32416             }
32417             else {
32418                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
32419                 scanJsxText();
32420             }
32421             return finishNode(factory.createJsxJsxClosingFragment(), pos);
32422         }
32423         function parseTypeAssertion() {
32424             var pos = getNodePos();
32425             parseExpected(29 /* LessThanToken */);
32426             var type = parseType();
32427             parseExpected(31 /* GreaterThanToken */);
32428             var expression = parseSimpleUnaryExpression();
32429             return finishNode(factory.createTypeAssertion(type, expression), pos);
32430         }
32431         function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
32432             nextToken();
32433             return ts.tokenIsIdentifierOrKeyword(token())
32434                 || token() === 22 /* OpenBracketToken */
32435                 || isTemplateStartOfTaggedTemplate();
32436         }
32437         function isStartOfOptionalPropertyOrElementAccessChain() {
32438             return token() === 28 /* QuestionDotToken */
32439                 && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
32440         }
32441         function tryReparseOptionalChain(node) {
32442             if (node.flags & 32 /* OptionalChain */) {
32443                 return true;
32444             }
32445             // check for an optional chain in a non-null expression
32446             if (ts.isNonNullExpression(node)) {
32447                 var expr = node.expression;
32448                 while (ts.isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */)) {
32449                     expr = expr.expression;
32450                 }
32451                 if (expr.flags & 32 /* OptionalChain */) {
32452                     // this is part of an optional chain. Walk down from `node` to `expression` and set the flag.
32453                     while (ts.isNonNullExpression(node)) {
32454                         node.flags |= 32 /* OptionalChain */;
32455                         node = node.expression;
32456                     }
32457                     return true;
32458                 }
32459             }
32460             return false;
32461         }
32462         function parsePropertyAccessExpressionRest(pos, expression, questionDotToken) {
32463             var name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
32464             var isOptionalChain = questionDotToken || tryReparseOptionalChain(expression);
32465             var propertyAccess = isOptionalChain ?
32466                 factory.createPropertyAccessChain(expression, questionDotToken, name) :
32467                 factory.createPropertyAccessExpression(expression, name);
32468             if (isOptionalChain && ts.isPrivateIdentifier(propertyAccess.name)) {
32469                 parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
32470             }
32471             return finishNode(propertyAccess, pos);
32472         }
32473         function parseElementAccessExpressionRest(pos, expression, questionDotToken) {
32474             var argumentExpression;
32475             if (token() === 23 /* CloseBracketToken */) {
32476                 argumentExpression = createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
32477             }
32478             else {
32479                 var argument = allowInAnd(parseExpression);
32480                 if (ts.isStringOrNumericLiteralLike(argument)) {
32481                     argument.text = internIdentifier(argument.text);
32482                 }
32483                 argumentExpression = argument;
32484             }
32485             parseExpected(23 /* CloseBracketToken */);
32486             var indexedAccess = questionDotToken || tryReparseOptionalChain(expression) ?
32487                 factory.createElementAccessChain(expression, questionDotToken, argumentExpression) :
32488                 factory.createElementAccessExpression(expression, argumentExpression);
32489             return finishNode(indexedAccess, pos);
32490         }
32491         function parseMemberExpressionRest(pos, expression, allowOptionalChain) {
32492             while (true) {
32493                 var questionDotToken = void 0;
32494                 var isPropertyAccess = false;
32495                 if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
32496                     questionDotToken = parseExpectedToken(28 /* QuestionDotToken */);
32497                     isPropertyAccess = ts.tokenIsIdentifierOrKeyword(token());
32498                 }
32499                 else {
32500                     isPropertyAccess = parseOptional(24 /* DotToken */);
32501                 }
32502                 if (isPropertyAccess) {
32503                     expression = parsePropertyAccessExpressionRest(pos, expression, questionDotToken);
32504                     continue;
32505                 }
32506                 if (!questionDotToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
32507                     nextToken();
32508                     expression = finishNode(factory.createNonNullExpression(expression), pos);
32509                     continue;
32510                 }
32511                 // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
32512                 if ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */)) {
32513                     expression = parseElementAccessExpressionRest(pos, expression, questionDotToken);
32514                     continue;
32515                 }
32516                 if (isTemplateStartOfTaggedTemplate()) {
32517                     expression = parseTaggedTemplateRest(pos, expression, questionDotToken, /*typeArguments*/ undefined);
32518                     continue;
32519                 }
32520                 return expression;
32521             }
32522         }
32523         function isTemplateStartOfTaggedTemplate() {
32524             return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
32525         }
32526         function parseTaggedTemplateRest(pos, tag, questionDotToken, typeArguments) {
32527             var tagExpression = factory.createTaggedTemplateExpression(tag, typeArguments, token() === 14 /* NoSubstitutionTemplateLiteral */ ?
32528                 (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode()) :
32529                 parseTemplateExpression(/*isTaggedTemplate*/ true));
32530             if (questionDotToken || tag.flags & 32 /* OptionalChain */) {
32531                 tagExpression.flags |= 32 /* OptionalChain */;
32532             }
32533             tagExpression.questionDotToken = questionDotToken;
32534             return finishNode(tagExpression, pos);
32535         }
32536         function parseCallExpressionRest(pos, expression) {
32537             while (true) {
32538                 expression = parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true);
32539                 var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
32540                 // handle 'foo<<T>()'
32541                 // parse template arguments only in TypeScript files (not in JavaScript files).
32542                 if ((contextFlags & 131072 /* JavaScriptFile */) === 0 && (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */)) {
32543                     // See if this is the start of a generic invocation.  If so, consume it and
32544                     // keep checking for postfix expressions.  Otherwise, it's just a '<' that's
32545                     // part of an arithmetic expression.  Break out so we consume it higher in the
32546                     // stack.
32547                     var typeArguments = tryParse(parseTypeArgumentsInExpression);
32548                     if (typeArguments) {
32549                         if (isTemplateStartOfTaggedTemplate()) {
32550                             expression = parseTaggedTemplateRest(pos, expression, questionDotToken, typeArguments);
32551                             continue;
32552                         }
32553                         var argumentList = parseArgumentList();
32554                         var callExpr = questionDotToken || tryReparseOptionalChain(expression) ?
32555                             factory.createCallChain(expression, questionDotToken, typeArguments, argumentList) :
32556                             factory.createCallExpression(expression, typeArguments, argumentList);
32557                         expression = finishNode(callExpr, pos);
32558                         continue;
32559                     }
32560                 }
32561                 else if (token() === 20 /* OpenParenToken */) {
32562                     var argumentList = parseArgumentList();
32563                     var callExpr = questionDotToken || tryReparseOptionalChain(expression) ?
32564                         factory.createCallChain(expression, questionDotToken, /*typeArguments*/ undefined, argumentList) :
32565                         factory.createCallExpression(expression, /*typeArguments*/ undefined, argumentList);
32566                     expression = finishNode(callExpr, pos);
32567                     continue;
32568                 }
32569                 if (questionDotToken) {
32570                     // We failed to parse anything, so report a missing identifier here.
32571                     var name = createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Identifier_expected);
32572                     expression = finishNode(factory.createPropertyAccessChain(expression, questionDotToken, name), pos);
32573                 }
32574                 break;
32575             }
32576             return expression;
32577         }
32578         function parseArgumentList() {
32579             parseExpected(20 /* OpenParenToken */);
32580             var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
32581             parseExpected(21 /* CloseParenToken */);
32582             return result;
32583         }
32584         function parseTypeArgumentsInExpression() {
32585             if ((contextFlags & 131072 /* JavaScriptFile */) !== 0) {
32586                 // TypeArguments must not be parsed in JavaScript files to avoid ambiguity with binary operators.
32587                 return undefined;
32588             }
32589             if (reScanLessThanToken() !== 29 /* LessThanToken */) {
32590                 return undefined;
32591             }
32592             nextToken();
32593             var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
32594             if (!parseExpected(31 /* GreaterThanToken */)) {
32595                 // If it doesn't have the closing `>` then it's definitely not an type argument list.
32596                 return undefined;
32597             }
32598             // If we have a '<', then only parse this as a argument list if the type arguments
32599             // are complete and we have an open paren.  if we don't, rewind and return nothing.
32600             return typeArguments && canFollowTypeArgumentsInExpression()
32601                 ? typeArguments
32602                 : undefined;
32603         }
32604         function canFollowTypeArgumentsInExpression() {
32605             switch (token()) {
32606                 case 20 /* OpenParenToken */: // foo<x>(
32607                 case 14 /* NoSubstitutionTemplateLiteral */: // foo<T> `...`
32608                 case 15 /* TemplateHead */: // foo<T> `...${100}...`
32609                 // these are the only tokens can legally follow a type argument
32610                 // list. So we definitely want to treat them as type arg lists.
32611                 // falls through
32612                 case 24 /* DotToken */: // foo<x>.
32613                 case 21 /* CloseParenToken */: // foo<x>)
32614                 case 23 /* CloseBracketToken */: // foo<x>]
32615                 case 58 /* ColonToken */: // foo<x>:
32616                 case 26 /* SemicolonToken */: // foo<x>;
32617                 case 57 /* QuestionToken */: // foo<x>?
32618                 case 34 /* EqualsEqualsToken */: // foo<x> ==
32619                 case 36 /* EqualsEqualsEqualsToken */: // foo<x> ===
32620                 case 35 /* ExclamationEqualsToken */: // foo<x> !=
32621                 case 37 /* ExclamationEqualsEqualsToken */: // foo<x> !==
32622                 case 55 /* AmpersandAmpersandToken */: // foo<x> &&
32623                 case 56 /* BarBarToken */: // foo<x> ||
32624                 case 60 /* QuestionQuestionToken */: // foo<x> ??
32625                 case 52 /* CaretToken */: // foo<x> ^
32626                 case 50 /* AmpersandToken */: // foo<x> &
32627                 case 51 /* BarToken */: // foo<x> |
32628                 case 19 /* CloseBraceToken */: // foo<x> }
32629                 case 1 /* EndOfFileToken */: // foo<x>
32630                     // these cases can't legally follow a type arg list.  However, they're not legal
32631                     // expressions either.  The user is probably in the middle of a generic type. So
32632                     // treat it as such.
32633                     return true;
32634                 case 27 /* CommaToken */: // foo<x>,
32635                 case 18 /* OpenBraceToken */: // foo<x> {
32636                 // We don't want to treat these as type arguments.  Otherwise we'll parse this
32637                 // as an invocation expression.  Instead, we want to parse out the expression
32638                 // in isolation from the type arguments.
32639                 // falls through
32640                 default:
32641                     // Anything else treat as an expression.
32642                     return false;
32643             }
32644         }
32645         function parsePrimaryExpression() {
32646             switch (token()) {
32647                 case 8 /* NumericLiteral */:
32648                 case 9 /* BigIntLiteral */:
32649                 case 10 /* StringLiteral */:
32650                 case 14 /* NoSubstitutionTemplateLiteral */:
32651                     return parseLiteralNode();
32652                 case 107 /* ThisKeyword */:
32653                 case 105 /* SuperKeyword */:
32654                 case 103 /* NullKeyword */:
32655                 case 109 /* TrueKeyword */:
32656                 case 94 /* FalseKeyword */:
32657                     return parseTokenNode();
32658                 case 20 /* OpenParenToken */:
32659                     return parseParenthesizedExpression();
32660                 case 22 /* OpenBracketToken */:
32661                     return parseArrayLiteralExpression();
32662                 case 18 /* OpenBraceToken */:
32663                     return parseObjectLiteralExpression();
32664                 case 129 /* AsyncKeyword */:
32665                     // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
32666                     // If we encounter `async [no LineTerminator here] function` then this is an async
32667                     // function; otherwise, its an identifier.
32668                     if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
32669                         break;
32670                     }
32671                     return parseFunctionExpression();
32672                 case 83 /* ClassKeyword */:
32673                     return parseClassExpression();
32674                 case 97 /* FunctionKeyword */:
32675                     return parseFunctionExpression();
32676                 case 102 /* NewKeyword */:
32677                     return parseNewExpressionOrNewDotTarget();
32678                 case 43 /* SlashToken */:
32679                 case 67 /* SlashEqualsToken */:
32680                     if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
32681                         return parseLiteralNode();
32682                     }
32683                     break;
32684                 case 15 /* TemplateHead */:
32685                     return parseTemplateExpression(/* isTaggedTemplate */ false);
32686             }
32687             return parseIdentifier(ts.Diagnostics.Expression_expected);
32688         }
32689         function parseParenthesizedExpression() {
32690             var pos = getNodePos();
32691             var hasJSDoc = hasPrecedingJSDocComment();
32692             parseExpected(20 /* OpenParenToken */);
32693             var expression = allowInAnd(parseExpression);
32694             parseExpected(21 /* CloseParenToken */);
32695             return withJSDoc(finishNode(factory.createParenthesizedExpression(expression), pos), hasJSDoc);
32696         }
32697         function parseSpreadElement() {
32698             var pos = getNodePos();
32699             parseExpected(25 /* DotDotDotToken */);
32700             var expression = parseAssignmentExpressionOrHigher();
32701             return finishNode(factory.createSpreadElement(expression), pos);
32702         }
32703         function parseArgumentOrArrayLiteralElement() {
32704             return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
32705                 token() === 27 /* CommaToken */ ? finishNode(factory.createOmittedExpression(), getNodePos()) :
32706                     parseAssignmentExpressionOrHigher();
32707         }
32708         function parseArgumentExpression() {
32709             return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
32710         }
32711         function parseArrayLiteralExpression() {
32712             var pos = getNodePos();
32713             parseExpected(22 /* OpenBracketToken */);
32714             var multiLine = scanner.hasPrecedingLineBreak();
32715             var elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
32716             parseExpected(23 /* CloseBracketToken */);
32717             return finishNode(factory.createArrayLiteralExpression(elements, multiLine), pos);
32718         }
32719         function parseObjectLiteralElement() {
32720             var pos = getNodePos();
32721             var hasJSDoc = hasPrecedingJSDocComment();
32722             if (parseOptionalToken(25 /* DotDotDotToken */)) {
32723                 var expression = parseAssignmentExpressionOrHigher();
32724                 return withJSDoc(finishNode(factory.createSpreadAssignment(expression), pos), hasJSDoc);
32725             }
32726             var decorators = parseDecorators();
32727             var modifiers = parseModifiers();
32728             if (parseContextualModifier(134 /* GetKeyword */)) {
32729                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */);
32730             }
32731             if (parseContextualModifier(146 /* SetKeyword */)) {
32732                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */);
32733             }
32734             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
32735             var tokenIsIdentifier = isIdentifier();
32736             var name = parsePropertyName();
32737             // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
32738             var questionToken = parseOptionalToken(57 /* QuestionToken */);
32739             var exclamationToken = parseOptionalToken(53 /* ExclamationToken */);
32740             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
32741                 return parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, exclamationToken);
32742             }
32743             // check if it is short-hand property assignment or normal property assignment
32744             // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
32745             // CoverInitializedName[Yield] :
32746             //     IdentifierReference[?Yield] Initializer[In, ?Yield]
32747             // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
32748             var node;
32749             var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* ColonToken */);
32750             if (isShorthandPropertyAssignment) {
32751                 var equalsToken = parseOptionalToken(62 /* EqualsToken */);
32752                 var objectAssignmentInitializer = equalsToken ? allowInAnd(parseAssignmentExpressionOrHigher) : undefined;
32753                 node = factory.createShorthandPropertyAssignment(name, objectAssignmentInitializer);
32754                 // Save equals token for error reporting.
32755                 // TODO(rbuckton): Consider manufacturing this when we need to report an error as it is otherwise not useful.
32756                 node.equalsToken = equalsToken;
32757             }
32758             else {
32759                 parseExpected(58 /* ColonToken */);
32760                 var initializer = allowInAnd(parseAssignmentExpressionOrHigher);
32761                 node = factory.createPropertyAssignment(name, initializer);
32762             }
32763             // Decorators, Modifiers, questionToken, and exclamationToken are not supported by property assignments and are reported in the grammar checker
32764             node.decorators = decorators;
32765             node.modifiers = modifiers;
32766             node.questionToken = questionToken;
32767             node.exclamationToken = exclamationToken;
32768             return withJSDoc(finishNode(node, pos), hasJSDoc);
32769         }
32770         function parseObjectLiteralExpression() {
32771             var pos = getNodePos();
32772             var openBracePosition = scanner.getTokenPos();
32773             parseExpected(18 /* OpenBraceToken */);
32774             var multiLine = scanner.hasPrecedingLineBreak();
32775             var properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
32776             if (!parseExpected(19 /* CloseBraceToken */)) {
32777                 var lastError = ts.lastOrUndefined(parseDiagnostics);
32778                 if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
32779                     ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
32780                 }
32781             }
32782             return finishNode(factory.createObjectLiteralExpression(properties, multiLine), pos);
32783         }
32784         function parseFunctionExpression() {
32785             // GeneratorExpression:
32786             //      function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
32787             //
32788             // FunctionExpression:
32789             //      function BindingIdentifier[opt](FormalParameters){ FunctionBody }
32790             var saveDecoratorContext = inDecoratorContext();
32791             if (saveDecoratorContext) {
32792                 setDecoratorContext(/*val*/ false);
32793             }
32794             var pos = getNodePos();
32795             var hasJSDoc = hasPrecedingJSDocComment();
32796             var modifiers = parseModifiers();
32797             parseExpected(97 /* FunctionKeyword */);
32798             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
32799             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
32800             var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
32801             var name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalBindingIdentifier) :
32802                 isGenerator ? doInYieldContext(parseOptionalBindingIdentifier) :
32803                     isAsync ? doInAwaitContext(parseOptionalBindingIdentifier) :
32804                         parseOptionalBindingIdentifier();
32805             var typeParameters = parseTypeParameters();
32806             var parameters = parseParameters(isGenerator | isAsync);
32807             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
32808             var body = parseFunctionBlock(isGenerator | isAsync);
32809             if (saveDecoratorContext) {
32810                 setDecoratorContext(/*val*/ true);
32811             }
32812             var node = factory.createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body);
32813             return withJSDoc(finishNode(node, pos), hasJSDoc);
32814         }
32815         function parseOptionalBindingIdentifier() {
32816             return isBindingIdentifier() ? parseBindingIdentifier() : undefined;
32817         }
32818         function parseNewExpressionOrNewDotTarget() {
32819             var pos = getNodePos();
32820             parseExpected(102 /* NewKeyword */);
32821             if (parseOptional(24 /* DotToken */)) {
32822                 var name = parseIdentifierName();
32823                 return finishNode(factory.createMetaProperty(102 /* NewKeyword */, name), pos);
32824             }
32825             var expressionPos = getNodePos();
32826             var expression = parsePrimaryExpression();
32827             var typeArguments;
32828             while (true) {
32829                 expression = parseMemberExpressionRest(expressionPos, expression, /*allowOptionalChain*/ false);
32830                 typeArguments = tryParse(parseTypeArgumentsInExpression);
32831                 if (isTemplateStartOfTaggedTemplate()) {
32832                     ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
32833                     expression = parseTaggedTemplateRest(expressionPos, expression, /*optionalChain*/ undefined, typeArguments);
32834                     typeArguments = undefined;
32835                 }
32836                 break;
32837             }
32838             var argumentsArray;
32839             if (token() === 20 /* OpenParenToken */) {
32840                 argumentsArray = parseArgumentList();
32841             }
32842             else if (typeArguments) {
32843                 parseErrorAt(pos, scanner.getStartPos(), ts.Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list);
32844             }
32845             return finishNode(factory.createNewExpression(expression, typeArguments, argumentsArray), pos);
32846         }
32847         // STATEMENTS
32848         function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
32849             var pos = getNodePos();
32850             var openBracePosition = scanner.getTokenPos();
32851             if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
32852                 var multiLine = scanner.hasPrecedingLineBreak();
32853                 var statements = parseList(1 /* BlockStatements */, parseStatement);
32854                 if (!parseExpected(19 /* CloseBraceToken */)) {
32855                     var lastError = ts.lastOrUndefined(parseDiagnostics);
32856                     if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
32857                         ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
32858                     }
32859                 }
32860                 return finishNode(factory.createBlock(statements, multiLine), pos);
32861             }
32862             else {
32863                 var statements = createMissingList();
32864                 return finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos);
32865             }
32866         }
32867         function parseFunctionBlock(flags, diagnosticMessage) {
32868             var savedYieldContext = inYieldContext();
32869             setYieldContext(!!(flags & 1 /* Yield */));
32870             var savedAwaitContext = inAwaitContext();
32871             setAwaitContext(!!(flags & 2 /* Await */));
32872             var savedTopLevel = topLevel;
32873             topLevel = false;
32874             // We may be in a [Decorator] context when parsing a function expression or
32875             // arrow function. The body of the function is not in [Decorator] context.
32876             var saveDecoratorContext = inDecoratorContext();
32877             if (saveDecoratorContext) {
32878                 setDecoratorContext(/*val*/ false);
32879             }
32880             var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
32881             if (saveDecoratorContext) {
32882                 setDecoratorContext(/*val*/ true);
32883             }
32884             topLevel = savedTopLevel;
32885             setYieldContext(savedYieldContext);
32886             setAwaitContext(savedAwaitContext);
32887             return block;
32888         }
32889         function parseEmptyStatement() {
32890             var pos = getNodePos();
32891             parseExpected(26 /* SemicolonToken */);
32892             return finishNode(factory.createEmptyStatement(), pos);
32893         }
32894         function parseIfStatement() {
32895             var pos = getNodePos();
32896             parseExpected(98 /* IfKeyword */);
32897             parseExpected(20 /* OpenParenToken */);
32898             var expression = allowInAnd(parseExpression);
32899             parseExpected(21 /* CloseParenToken */);
32900             var thenStatement = parseStatement();
32901             var elseStatement = parseOptional(90 /* ElseKeyword */) ? parseStatement() : undefined;
32902             return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos);
32903         }
32904         function parseDoStatement() {
32905             var pos = getNodePos();
32906             parseExpected(89 /* DoKeyword */);
32907             var statement = parseStatement();
32908             parseExpected(114 /* WhileKeyword */);
32909             parseExpected(20 /* OpenParenToken */);
32910             var expression = allowInAnd(parseExpression);
32911             parseExpected(21 /* CloseParenToken */);
32912             // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
32913             // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
32914             // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
32915             //  do;while(0)x will have a semicolon inserted before x.
32916             parseOptional(26 /* SemicolonToken */);
32917             return finishNode(factory.createDoStatement(statement, expression), pos);
32918         }
32919         function parseWhileStatement() {
32920             var pos = getNodePos();
32921             parseExpected(114 /* WhileKeyword */);
32922             parseExpected(20 /* OpenParenToken */);
32923             var expression = allowInAnd(parseExpression);
32924             parseExpected(21 /* CloseParenToken */);
32925             var statement = parseStatement();
32926             return finishNode(factory.createWhileStatement(expression, statement), pos);
32927         }
32928         function parseForOrForInOrForOfStatement() {
32929             var pos = getNodePos();
32930             parseExpected(96 /* ForKeyword */);
32931             var awaitToken = parseOptionalToken(130 /* AwaitKeyword */);
32932             parseExpected(20 /* OpenParenToken */);
32933             var initializer;
32934             if (token() !== 26 /* SemicolonToken */) {
32935                 if (token() === 112 /* VarKeyword */ || token() === 118 /* LetKeyword */ || token() === 84 /* ConstKeyword */) {
32936                     initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
32937                 }
32938                 else {
32939                     initializer = disallowInAnd(parseExpression);
32940                 }
32941             }
32942             var node;
32943             if (awaitToken ? parseExpected(156 /* OfKeyword */) : parseOptional(156 /* OfKeyword */)) {
32944                 var expression = allowInAnd(parseAssignmentExpressionOrHigher);
32945                 parseExpected(21 /* CloseParenToken */);
32946                 node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement());
32947             }
32948             else if (parseOptional(100 /* InKeyword */)) {
32949                 var expression = allowInAnd(parseExpression);
32950                 parseExpected(21 /* CloseParenToken */);
32951                 node = factory.createForInStatement(initializer, expression, parseStatement());
32952             }
32953             else {
32954                 parseExpected(26 /* SemicolonToken */);
32955                 var condition = token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */
32956                     ? allowInAnd(parseExpression)
32957                     : undefined;
32958                 parseExpected(26 /* SemicolonToken */);
32959                 var incrementor = token() !== 21 /* CloseParenToken */
32960                     ? allowInAnd(parseExpression)
32961                     : undefined;
32962                 parseExpected(21 /* CloseParenToken */);
32963                 node = factory.createForStatement(initializer, condition, incrementor, parseStatement());
32964             }
32965             return finishNode(node, pos);
32966         }
32967         function parseBreakOrContinueStatement(kind) {
32968             var pos = getNodePos();
32969             parseExpected(kind === 241 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */);
32970             var label = canParseSemicolon() ? undefined : parseIdentifier();
32971             parseSemicolon();
32972             var node = kind === 241 /* BreakStatement */
32973                 ? factory.createBreakStatement(label)
32974                 : factory.createContinueStatement(label);
32975             return finishNode(node, pos);
32976         }
32977         function parseReturnStatement() {
32978             var pos = getNodePos();
32979             parseExpected(104 /* ReturnKeyword */);
32980             var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression);
32981             parseSemicolon();
32982             return finishNode(factory.createReturnStatement(expression), pos);
32983         }
32984         function parseWithStatement() {
32985             var pos = getNodePos();
32986             parseExpected(115 /* WithKeyword */);
32987             parseExpected(20 /* OpenParenToken */);
32988             var expression = allowInAnd(parseExpression);
32989             parseExpected(21 /* CloseParenToken */);
32990             var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement);
32991             return finishNode(factory.createWithStatement(expression, statement), pos);
32992         }
32993         function parseCaseClause() {
32994             var pos = getNodePos();
32995             parseExpected(81 /* CaseKeyword */);
32996             var expression = allowInAnd(parseExpression);
32997             parseExpected(58 /* ColonToken */);
32998             var statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
32999             return finishNode(factory.createCaseClause(expression, statements), pos);
33000         }
33001         function parseDefaultClause() {
33002             var pos = getNodePos();
33003             parseExpected(87 /* DefaultKeyword */);
33004             parseExpected(58 /* ColonToken */);
33005             var statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
33006             return finishNode(factory.createDefaultClause(statements), pos);
33007         }
33008         function parseCaseOrDefaultClause() {
33009             return token() === 81 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
33010         }
33011         function parseCaseBlock() {
33012             var pos = getNodePos();
33013             parseExpected(18 /* OpenBraceToken */);
33014             var clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
33015             parseExpected(19 /* CloseBraceToken */);
33016             return finishNode(factory.createCaseBlock(clauses), pos);
33017         }
33018         function parseSwitchStatement() {
33019             var pos = getNodePos();
33020             parseExpected(106 /* SwitchKeyword */);
33021             parseExpected(20 /* OpenParenToken */);
33022             var expression = allowInAnd(parseExpression);
33023             parseExpected(21 /* CloseParenToken */);
33024             var caseBlock = parseCaseBlock();
33025             return finishNode(factory.createSwitchStatement(expression, caseBlock), pos);
33026         }
33027         function parseThrowStatement() {
33028             // ThrowStatement[Yield] :
33029             //      throw [no LineTerminator here]Expression[In, ?Yield];
33030             var pos = getNodePos();
33031             parseExpected(108 /* ThrowKeyword */);
33032             // Because of automatic semicolon insertion, we need to report error if this
33033             // throw could be terminated with a semicolon.  Note: we can't call 'parseExpression'
33034             // directly as that might consume an expression on the following line.
33035             // Instead, we create a "missing" identifier, but don't report an error. The actual error
33036             // will be reported in the grammar walker.
33037             var expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
33038             if (expression === undefined) {
33039                 identifierCount++;
33040                 expression = finishNode(factory.createIdentifier(""), getNodePos());
33041             }
33042             parseSemicolon();
33043             return finishNode(factory.createThrowStatement(expression), pos);
33044         }
33045         // TODO: Review for error recovery
33046         function parseTryStatement() {
33047             var pos = getNodePos();
33048             parseExpected(110 /* TryKeyword */);
33049             var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
33050             var catchClause = token() === 82 /* CatchKeyword */ ? parseCatchClause() : undefined;
33051             // If we don't have a catch clause, then we must have a finally clause.  Try to parse
33052             // one out no matter what.
33053             var finallyBlock;
33054             if (!catchClause || token() === 95 /* FinallyKeyword */) {
33055                 parseExpected(95 /* FinallyKeyword */);
33056                 finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
33057             }
33058             return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos);
33059         }
33060         function parseCatchClause() {
33061             var pos = getNodePos();
33062             parseExpected(82 /* CatchKeyword */);
33063             var variableDeclaration;
33064             if (parseOptional(20 /* OpenParenToken */)) {
33065                 variableDeclaration = parseVariableDeclaration();
33066                 parseExpected(21 /* CloseParenToken */);
33067             }
33068             else {
33069                 // Keep shape of node to avoid degrading performance.
33070                 variableDeclaration = undefined;
33071             }
33072             var block = parseBlock(/*ignoreMissingOpenBrace*/ false);
33073             return finishNode(factory.createCatchClause(variableDeclaration, block), pos);
33074         }
33075         function parseDebuggerStatement() {
33076             var pos = getNodePos();
33077             parseExpected(86 /* DebuggerKeyword */);
33078             parseSemicolon();
33079             return finishNode(factory.createDebuggerStatement(), pos);
33080         }
33081         function parseExpressionOrLabeledStatement() {
33082             // Avoiding having to do the lookahead for a labeled statement by just trying to parse
33083             // out an expression, seeing if it is identifier and then seeing if it is followed by
33084             // a colon.
33085             var pos = getNodePos();
33086             var hasJSDoc = hasPrecedingJSDocComment();
33087             var node;
33088             var hasParen = token() === 20 /* OpenParenToken */;
33089             var expression = allowInAnd(parseExpression);
33090             if (ts.isIdentifier(expression) && parseOptional(58 /* ColonToken */)) {
33091                 node = factory.createLabeledStatement(expression, parseStatement());
33092             }
33093             else {
33094                 parseSemicolon();
33095                 node = factory.createExpressionStatement(expression);
33096                 if (hasParen) {
33097                     // do not parse the same jsdoc twice
33098                     hasJSDoc = false;
33099                 }
33100             }
33101             return withJSDoc(finishNode(node, pos), hasJSDoc);
33102         }
33103         function nextTokenIsIdentifierOrKeywordOnSameLine() {
33104             nextToken();
33105             return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
33106         }
33107         function nextTokenIsClassKeywordOnSameLine() {
33108             nextToken();
33109             return token() === 83 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
33110         }
33111         function nextTokenIsFunctionKeywordOnSameLine() {
33112             nextToken();
33113             return token() === 97 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
33114         }
33115         function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
33116             nextToken();
33117             return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
33118         }
33119         function isDeclaration() {
33120             while (true) {
33121                 switch (token()) {
33122                     case 112 /* VarKeyword */:
33123                     case 118 /* LetKeyword */:
33124                     case 84 /* ConstKeyword */:
33125                     case 97 /* FunctionKeyword */:
33126                     case 83 /* ClassKeyword */:
33127                     case 91 /* EnumKeyword */:
33128                         return true;
33129                     // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
33130                     // however, an identifier cannot be followed by another identifier on the same line. This is what we
33131                     // count on to parse out the respective declarations. For instance, we exploit this to say that
33132                     //
33133                     //    namespace n
33134                     //
33135                     // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
33136                     //
33137                     //    namespace
33138                     //    n
33139                     //
33140                     // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
33141                     // We need to look one token ahead to see if it permissible to try parsing a declaration.
33142                     //
33143                     // *Note*: 'interface' is actually a strict mode reserved word. So while
33144                     //
33145                     //   "use strict"
33146                     //   interface
33147                     //   I {}
33148                     //
33149                     // could be legal, it would add complexity for very little gain.
33150                     case 117 /* InterfaceKeyword */:
33151                     case 149 /* TypeKeyword */:
33152                         return nextTokenIsIdentifierOnSameLine();
33153                     case 139 /* ModuleKeyword */:
33154                     case 140 /* NamespaceKeyword */:
33155                         return nextTokenIsIdentifierOrStringLiteralOnSameLine();
33156                     case 125 /* AbstractKeyword */:
33157                     case 129 /* AsyncKeyword */:
33158                     case 133 /* DeclareKeyword */:
33159                     case 120 /* PrivateKeyword */:
33160                     case 121 /* ProtectedKeyword */:
33161                     case 122 /* PublicKeyword */:
33162                     case 142 /* ReadonlyKeyword */:
33163                         nextToken();
33164                         // ASI takes effect for this modifier.
33165                         if (scanner.hasPrecedingLineBreak()) {
33166                             return false;
33167                         }
33168                         continue;
33169                     case 154 /* GlobalKeyword */:
33170                         nextToken();
33171                         return token() === 18 /* OpenBraceToken */ || token() === 78 /* Identifier */ || token() === 92 /* ExportKeyword */;
33172                     case 99 /* ImportKeyword */:
33173                         nextToken();
33174                         return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ ||
33175                             token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
33176                     case 92 /* ExportKeyword */:
33177                         var currentToken_1 = nextToken();
33178                         if (currentToken_1 === 149 /* TypeKeyword */) {
33179                             currentToken_1 = lookAhead(nextToken);
33180                         }
33181                         if (currentToken_1 === 62 /* EqualsToken */ || currentToken_1 === 41 /* AsteriskToken */ ||
33182                             currentToken_1 === 18 /* OpenBraceToken */ || currentToken_1 === 87 /* DefaultKeyword */ ||
33183                             currentToken_1 === 126 /* AsKeyword */) {
33184                             return true;
33185                         }
33186                         continue;
33187                     case 123 /* StaticKeyword */:
33188                         nextToken();
33189                         continue;
33190                     default:
33191                         return false;
33192                 }
33193             }
33194         }
33195         function isStartOfDeclaration() {
33196             return lookAhead(isDeclaration);
33197         }
33198         function isStartOfStatement() {
33199             switch (token()) {
33200                 case 59 /* AtToken */:
33201                 case 26 /* SemicolonToken */:
33202                 case 18 /* OpenBraceToken */:
33203                 case 112 /* VarKeyword */:
33204                 case 118 /* LetKeyword */:
33205                 case 97 /* FunctionKeyword */:
33206                 case 83 /* ClassKeyword */:
33207                 case 91 /* EnumKeyword */:
33208                 case 98 /* IfKeyword */:
33209                 case 89 /* DoKeyword */:
33210                 case 114 /* WhileKeyword */:
33211                 case 96 /* ForKeyword */:
33212                 case 85 /* ContinueKeyword */:
33213                 case 80 /* BreakKeyword */:
33214                 case 104 /* ReturnKeyword */:
33215                 case 115 /* WithKeyword */:
33216                 case 106 /* SwitchKeyword */:
33217                 case 108 /* ThrowKeyword */:
33218                 case 110 /* TryKeyword */:
33219                 case 86 /* DebuggerKeyword */:
33220                 // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
33221                 // however, we say they are here so that we may gracefully parse them and error later.
33222                 // falls through
33223                 case 82 /* CatchKeyword */:
33224                 case 95 /* FinallyKeyword */:
33225                     return true;
33226                 case 99 /* ImportKeyword */:
33227                     return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
33228                 case 84 /* ConstKeyword */:
33229                 case 92 /* ExportKeyword */:
33230                     return isStartOfDeclaration();
33231                 case 129 /* AsyncKeyword */:
33232                 case 133 /* DeclareKeyword */:
33233                 case 117 /* InterfaceKeyword */:
33234                 case 139 /* ModuleKeyword */:
33235                 case 140 /* NamespaceKeyword */:
33236                 case 149 /* TypeKeyword */:
33237                 case 154 /* GlobalKeyword */:
33238                     // When these don't start a declaration, they're an identifier in an expression statement
33239                     return true;
33240                 case 122 /* PublicKeyword */:
33241                 case 120 /* PrivateKeyword */:
33242                 case 121 /* ProtectedKeyword */:
33243                 case 123 /* StaticKeyword */:
33244                 case 142 /* ReadonlyKeyword */:
33245                     // When these don't start a declaration, they may be the start of a class member if an identifier
33246                     // immediately follows. Otherwise they're an identifier in an expression statement.
33247                     return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
33248                 default:
33249                     return isStartOfExpression();
33250             }
33251         }
33252         function nextTokenIsIdentifierOrStartOfDestructuring() {
33253             nextToken();
33254             return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */;
33255         }
33256         function isLetDeclaration() {
33257             // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
33258             // or [.
33259             return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
33260         }
33261         function parseStatement() {
33262             switch (token()) {
33263                 case 26 /* SemicolonToken */:
33264                     return parseEmptyStatement();
33265                 case 18 /* OpenBraceToken */:
33266                     return parseBlock(/*ignoreMissingOpenBrace*/ false);
33267                 case 112 /* VarKeyword */:
33268                     return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
33269                 case 118 /* LetKeyword */:
33270                     if (isLetDeclaration()) {
33271                         return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
33272                     }
33273                     break;
33274                 case 97 /* FunctionKeyword */:
33275                     return parseFunctionDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
33276                 case 83 /* ClassKeyword */:
33277                     return parseClassDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
33278                 case 98 /* IfKeyword */:
33279                     return parseIfStatement();
33280                 case 89 /* DoKeyword */:
33281                     return parseDoStatement();
33282                 case 114 /* WhileKeyword */:
33283                     return parseWhileStatement();
33284                 case 96 /* ForKeyword */:
33285                     return parseForOrForInOrForOfStatement();
33286                 case 85 /* ContinueKeyword */:
33287                     return parseBreakOrContinueStatement(240 /* ContinueStatement */);
33288                 case 80 /* BreakKeyword */:
33289                     return parseBreakOrContinueStatement(241 /* BreakStatement */);
33290                 case 104 /* ReturnKeyword */:
33291                     return parseReturnStatement();
33292                 case 115 /* WithKeyword */:
33293                     return parseWithStatement();
33294                 case 106 /* SwitchKeyword */:
33295                     return parseSwitchStatement();
33296                 case 108 /* ThrowKeyword */:
33297                     return parseThrowStatement();
33298                 case 110 /* TryKeyword */:
33299                 // Include 'catch' and 'finally' for error recovery.
33300                 // falls through
33301                 case 82 /* CatchKeyword */:
33302                 case 95 /* FinallyKeyword */:
33303                     return parseTryStatement();
33304                 case 86 /* DebuggerKeyword */:
33305                     return parseDebuggerStatement();
33306                 case 59 /* AtToken */:
33307                     return parseDeclaration();
33308                 case 129 /* AsyncKeyword */:
33309                 case 117 /* InterfaceKeyword */:
33310                 case 149 /* TypeKeyword */:
33311                 case 139 /* ModuleKeyword */:
33312                 case 140 /* NamespaceKeyword */:
33313                 case 133 /* DeclareKeyword */:
33314                 case 84 /* ConstKeyword */:
33315                 case 91 /* EnumKeyword */:
33316                 case 92 /* ExportKeyword */:
33317                 case 99 /* ImportKeyword */:
33318                 case 120 /* PrivateKeyword */:
33319                 case 121 /* ProtectedKeyword */:
33320                 case 122 /* PublicKeyword */:
33321                 case 125 /* AbstractKeyword */:
33322                 case 123 /* StaticKeyword */:
33323                 case 142 /* ReadonlyKeyword */:
33324                 case 154 /* GlobalKeyword */:
33325                     if (isStartOfDeclaration()) {
33326                         return parseDeclaration();
33327                     }
33328                     break;
33329             }
33330             return parseExpressionOrLabeledStatement();
33331         }
33332         function isDeclareModifier(modifier) {
33333             return modifier.kind === 133 /* DeclareKeyword */;
33334         }
33335         function parseDeclaration() {
33336             // TODO: Can we hold onto the parsed decorators/modifiers and advance the scanner
33337             //       if we can't reuse the declaration, so that we don't do this work twice?
33338             //
33339             // `parseListElement` attempted to get the reused node at this position,
33340             // but the ambient context flag was not yet set, so the node appeared
33341             // not reusable in that context.
33342             var isAmbient = ts.some(lookAhead(function () { return (parseDecorators(), parseModifiers()); }), isDeclareModifier);
33343             if (isAmbient) {
33344                 var node = tryReuseAmbientDeclaration();
33345                 if (node) {
33346                     return node;
33347                 }
33348             }
33349             var pos = getNodePos();
33350             var hasJSDoc = hasPrecedingJSDocComment();
33351             var decorators = parseDecorators();
33352             var modifiers = parseModifiers();
33353             if (isAmbient) {
33354                 for (var _i = 0, _a = modifiers; _i < _a.length; _i++) {
33355                     var m = _a[_i];
33356                     m.flags |= 8388608 /* Ambient */;
33357                 }
33358                 return doInsideOfContext(8388608 /* Ambient */, function () { return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); });
33359             }
33360             else {
33361                 return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers);
33362             }
33363         }
33364         function tryReuseAmbientDeclaration() {
33365             return doInsideOfContext(8388608 /* Ambient */, function () {
33366                 var node = currentNode(parsingContext);
33367                 if (node) {
33368                     return consumeNode(node);
33369                 }
33370             });
33371         }
33372         function parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers) {
33373             switch (token()) {
33374                 case 112 /* VarKeyword */:
33375                 case 118 /* LetKeyword */:
33376                 case 84 /* ConstKeyword */:
33377                     return parseVariableStatement(pos, hasJSDoc, decorators, modifiers);
33378                 case 97 /* FunctionKeyword */:
33379                     return parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers);
33380                 case 83 /* ClassKeyword */:
33381                     return parseClassDeclaration(pos, hasJSDoc, decorators, modifiers);
33382                 case 117 /* InterfaceKeyword */:
33383                     return parseInterfaceDeclaration(pos, hasJSDoc, decorators, modifiers);
33384                 case 149 /* TypeKeyword */:
33385                     return parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers);
33386                 case 91 /* EnumKeyword */:
33387                     return parseEnumDeclaration(pos, hasJSDoc, decorators, modifiers);
33388                 case 154 /* GlobalKeyword */:
33389                 case 139 /* ModuleKeyword */:
33390                 case 140 /* NamespaceKeyword */:
33391                     return parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
33392                 case 99 /* ImportKeyword */:
33393                     return parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers);
33394                 case 92 /* ExportKeyword */:
33395                     nextToken();
33396                     switch (token()) {
33397                         case 87 /* DefaultKeyword */:
33398                         case 62 /* EqualsToken */:
33399                             return parseExportAssignment(pos, hasJSDoc, decorators, modifiers);
33400                         case 126 /* AsKeyword */:
33401                             return parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers);
33402                         default:
33403                             return parseExportDeclaration(pos, hasJSDoc, decorators, modifiers);
33404                     }
33405                 default:
33406                     if (decorators || modifiers) {
33407                         // We reached this point because we encountered decorators and/or modifiers and assumed a declaration
33408                         // would follow. For recovery and error reporting purposes, return an incomplete declaration.
33409                         var missing = createMissingNode(271 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
33410                         ts.setTextRangePos(missing, pos);
33411                         missing.decorators = decorators;
33412                         missing.modifiers = modifiers;
33413                         return missing;
33414                     }
33415                     return undefined; // TODO: GH#18217
33416             }
33417         }
33418         function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
33419             nextToken();
33420             return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
33421         }
33422         function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
33423             if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
33424                 parseSemicolon();
33425                 return;
33426             }
33427             return parseFunctionBlock(flags, diagnosticMessage);
33428         }
33429         // DECLARATIONS
33430         function parseArrayBindingElement() {
33431             var pos = getNodePos();
33432             if (token() === 27 /* CommaToken */) {
33433                 return finishNode(factory.createOmittedExpression(), pos);
33434             }
33435             var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
33436             var name = parseIdentifierOrPattern();
33437             var initializer = parseInitializer();
33438             return finishNode(factory.createBindingElement(dotDotDotToken, /*propertyName*/ undefined, name, initializer), pos);
33439         }
33440         function parseObjectBindingElement() {
33441             var pos = getNodePos();
33442             var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
33443             var tokenIsIdentifier = isBindingIdentifier();
33444             var propertyName = parsePropertyName();
33445             var name;
33446             if (tokenIsIdentifier && token() !== 58 /* ColonToken */) {
33447                 name = propertyName;
33448                 propertyName = undefined;
33449             }
33450             else {
33451                 parseExpected(58 /* ColonToken */);
33452                 name = parseIdentifierOrPattern();
33453             }
33454             var initializer = parseInitializer();
33455             return finishNode(factory.createBindingElement(dotDotDotToken, propertyName, name, initializer), pos);
33456         }
33457         function parseObjectBindingPattern() {
33458             var pos = getNodePos();
33459             parseExpected(18 /* OpenBraceToken */);
33460             var elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
33461             parseExpected(19 /* CloseBraceToken */);
33462             return finishNode(factory.createObjectBindingPattern(elements), pos);
33463         }
33464         function parseArrayBindingPattern() {
33465             var pos = getNodePos();
33466             parseExpected(22 /* OpenBracketToken */);
33467             var elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
33468             parseExpected(23 /* CloseBracketToken */);
33469             return finishNode(factory.createArrayBindingPattern(elements), pos);
33470         }
33471         function isBindingIdentifierOrPrivateIdentifierOrPattern() {
33472             return token() === 18 /* OpenBraceToken */
33473                 || token() === 22 /* OpenBracketToken */
33474                 || token() === 79 /* PrivateIdentifier */
33475                 || isBindingIdentifier();
33476         }
33477         function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
33478             if (token() === 22 /* OpenBracketToken */) {
33479                 return parseArrayBindingPattern();
33480             }
33481             if (token() === 18 /* OpenBraceToken */) {
33482                 return parseObjectBindingPattern();
33483             }
33484             return parseBindingIdentifier(privateIdentifierDiagnosticMessage);
33485         }
33486         function parseVariableDeclarationAllowExclamation() {
33487             return parseVariableDeclaration(/*allowExclamation*/ true);
33488         }
33489         function parseVariableDeclaration(allowExclamation) {
33490             var pos = getNodePos();
33491             var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
33492             var exclamationToken;
33493             if (allowExclamation && name.kind === 78 /* Identifier */ &&
33494                 token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
33495                 exclamationToken = parseTokenNode();
33496             }
33497             var type = parseTypeAnnotation();
33498             var initializer = isInOrOfKeyword(token()) ? undefined : parseInitializer();
33499             var node = factory.createVariableDeclaration(name, exclamationToken, type, initializer);
33500             return finishNode(node, pos);
33501         }
33502         function parseVariableDeclarationList(inForStatementInitializer) {
33503             var pos = getNodePos();
33504             var flags = 0;
33505             switch (token()) {
33506                 case 112 /* VarKeyword */:
33507                     break;
33508                 case 118 /* LetKeyword */:
33509                     flags |= 1 /* Let */;
33510                     break;
33511                 case 84 /* ConstKeyword */:
33512                     flags |= 2 /* Const */;
33513                     break;
33514                 default:
33515                     ts.Debug.fail();
33516             }
33517             nextToken();
33518             // The user may have written the following:
33519             //
33520             //    for (let of X) { }
33521             //
33522             // In this case, we want to parse an empty declaration list, and then parse 'of'
33523             // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
33524             // So we need to look ahead to determine if 'of' should be treated as a keyword in
33525             // this context.
33526             // The checker will then give an error that there is an empty declaration list.
33527             var declarations;
33528             if (token() === 156 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
33529                 declarations = createMissingList();
33530             }
33531             else {
33532                 var savedDisallowIn = inDisallowInContext();
33533                 setDisallowInContext(inForStatementInitializer);
33534                 declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
33535                 setDisallowInContext(savedDisallowIn);
33536             }
33537             return finishNode(factory.createVariableDeclarationList(declarations, flags), pos);
33538         }
33539         function canFollowContextualOfKeyword() {
33540             return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
33541         }
33542         function parseVariableStatement(pos, hasJSDoc, decorators, modifiers) {
33543             var declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
33544             parseSemicolon();
33545             var node = factory.createVariableStatement(modifiers, declarationList);
33546             // Decorators are not allowed on a variable statement, so we keep track of them to report them in the grammar checker.
33547             node.decorators = decorators;
33548             return withJSDoc(finishNode(node, pos), hasJSDoc);
33549         }
33550         function parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers) {
33551             var savedAwaitContext = inAwaitContext();
33552             var modifierFlags = ts.modifiersToFlags(modifiers);
33553             parseExpected(97 /* FunctionKeyword */);
33554             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
33555             // We don't parse the name here in await context, instead we will report a grammar error in the checker.
33556             var name = modifierFlags & 512 /* Default */ ? parseOptionalBindingIdentifier() : parseBindingIdentifier();
33557             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
33558             var isAsync = modifierFlags & 256 /* Async */ ? 2 /* Await */ : 0 /* None */;
33559             var typeParameters = parseTypeParameters();
33560             if (modifierFlags & 1 /* Export */)
33561                 setAwaitContext(/*value*/ true);
33562             var parameters = parseParameters(isGenerator | isAsync);
33563             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
33564             var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
33565             setAwaitContext(savedAwaitContext);
33566             var node = factory.createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body);
33567             return withJSDoc(finishNode(node, pos), hasJSDoc);
33568         }
33569         function parseConstructorName() {
33570             if (token() === 132 /* ConstructorKeyword */) {
33571                 return parseExpected(132 /* ConstructorKeyword */);
33572             }
33573             if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */) {
33574                 return tryParse(function () {
33575                     var literalNode = parseLiteralNode();
33576                     return literalNode.text === "constructor" ? literalNode : undefined;
33577                 });
33578             }
33579         }
33580         function tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers) {
33581             return tryParse(function () {
33582                 if (parseConstructorName()) {
33583                     var typeParameters = parseTypeParameters();
33584                     var parameters = parseParameters(0 /* None */);
33585                     var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
33586                     var body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
33587                     var node = factory.createConstructorDeclaration(decorators, modifiers, parameters, body);
33588                     // Attach `typeParameters` and `type` if they exist so that we can report them in the grammar checker.
33589                     node.typeParameters = typeParameters;
33590                     node.type = type;
33591                     return withJSDoc(finishNode(node, pos), hasJSDoc);
33592                 }
33593             });
33594         }
33595         function parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, exclamationToken, diagnosticMessage) {
33596             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
33597             var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
33598             var typeParameters = parseTypeParameters();
33599             var parameters = parseParameters(isGenerator | isAsync);
33600             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
33601             var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
33602             var node = factory.createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body);
33603             // An exclamation token on a method is invalid syntax and will be handled by the grammar checker
33604             node.exclamationToken = exclamationToken;
33605             return withJSDoc(finishNode(node, pos), hasJSDoc);
33606         }
33607         function parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken) {
33608             var exclamationToken = !questionToken && !scanner.hasPrecedingLineBreak() ? parseOptionalToken(53 /* ExclamationToken */) : undefined;
33609             var type = parseTypeAnnotation();
33610             var initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer);
33611             parseSemicolon();
33612             var node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken || exclamationToken, type, initializer);
33613             return withJSDoc(finishNode(node, pos), hasJSDoc);
33614         }
33615         function parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers) {
33616             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
33617             var name = parsePropertyName();
33618             // Note: this is not legal as per the grammar.  But we allow it in the parser and
33619             // report an error in the grammar checker.
33620             var questionToken = parseOptionalToken(57 /* QuestionToken */);
33621             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
33622                 return parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, /*exclamationToken*/ undefined, ts.Diagnostics.or_expected);
33623             }
33624             return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken);
33625         }
33626         function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind) {
33627             var name = parsePropertyName();
33628             var typeParameters = parseTypeParameters();
33629             var parameters = parseParameters(0 /* None */);
33630             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
33631             var body = parseFunctionBlockOrSemicolon(0 /* None */);
33632             var node = kind === 167 /* GetAccessor */
33633                 ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body)
33634                 : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body);
33635             // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors
33636             node.typeParameters = typeParameters;
33637             if (type && node.kind === 168 /* SetAccessor */)
33638                 node.type = type;
33639             return withJSDoc(finishNode(node, pos), hasJSDoc);
33640         }
33641         function isClassMemberStart() {
33642             var idToken;
33643             if (token() === 59 /* AtToken */) {
33644                 return true;
33645             }
33646             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
33647             while (ts.isModifierKind(token())) {
33648                 idToken = token();
33649                 // If the idToken is a class modifier (protected, private, public, and static), it is
33650                 // certain that we are starting to parse class member. This allows better error recovery
33651                 // Example:
33652                 //      public foo() ...     // true
33653                 //      public @dec blah ... // true; we will then report an error later
33654                 //      export public ...    // true; we will then report an error later
33655                 if (ts.isClassMemberModifier(idToken)) {
33656                     return true;
33657                 }
33658                 nextToken();
33659             }
33660             if (token() === 41 /* AsteriskToken */) {
33661                 return true;
33662             }
33663             // Try to get the first property-like token following all modifiers.
33664             // This can either be an identifier or the 'get' or 'set' keywords.
33665             if (isLiteralPropertyName()) {
33666                 idToken = token();
33667                 nextToken();
33668             }
33669             // Index signatures and computed properties are class members; we can parse.
33670             if (token() === 22 /* OpenBracketToken */) {
33671                 return true;
33672             }
33673             // If we were able to get any potential identifier...
33674             if (idToken !== undefined) {
33675                 // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
33676                 if (!ts.isKeyword(idToken) || idToken === 146 /* SetKeyword */ || idToken === 134 /* GetKeyword */) {
33677                     return true;
33678                 }
33679                 // If it *is* a keyword, but not an accessor, check a little farther along
33680                 // to see if it should actually be parsed as a class member.
33681                 switch (token()) {
33682                     case 20 /* OpenParenToken */: // Method declaration
33683                     case 29 /* LessThanToken */: // Generic Method declaration
33684                     case 53 /* ExclamationToken */: // Non-null assertion on property name
33685                     case 58 /* ColonToken */: // Type Annotation for declaration
33686                     case 62 /* EqualsToken */: // Initializer for declaration
33687                     case 57 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
33688                         return true;
33689                     default:
33690                         // Covers
33691                         //  - Semicolons     (declaration termination)
33692                         //  - Closing braces (end-of-class, must be declaration)
33693                         //  - End-of-files   (not valid, but permitted so that it gets caught later on)
33694                         //  - Line-breaks    (enabling *automatic semicolon insertion*)
33695                         return canParseSemicolon();
33696                 }
33697             }
33698             return false;
33699         }
33700         function parseDecoratorExpression() {
33701             if (inAwaitContext() && token() === 130 /* AwaitKeyword */) {
33702                 // `@await` is is disallowed in an [Await] context, but can cause parsing to go off the rails
33703                 // This simply parses the missing identifier and moves on.
33704                 var pos = getNodePos();
33705                 var awaitExpression = parseIdentifier(ts.Diagnostics.Expression_expected);
33706                 nextToken();
33707                 var memberExpression = parseMemberExpressionRest(pos, awaitExpression, /*allowOptionalChain*/ true);
33708                 return parseCallExpressionRest(pos, memberExpression);
33709             }
33710             return parseLeftHandSideExpressionOrHigher();
33711         }
33712         function tryParseDecorator() {
33713             var pos = getNodePos();
33714             if (!parseOptional(59 /* AtToken */)) {
33715                 return undefined;
33716             }
33717             var expression = doInDecoratorContext(parseDecoratorExpression);
33718             return finishNode(factory.createDecorator(expression), pos);
33719         }
33720         function parseDecorators() {
33721             var pos = getNodePos();
33722             var list, decorator;
33723             while (decorator = tryParseDecorator()) {
33724                 list = ts.append(list, decorator);
33725             }
33726             return list && createNodeArray(list, pos);
33727         }
33728         function tryParseModifier(permitInvalidConstAsModifier) {
33729             var pos = getNodePos();
33730             var kind = token();
33731             if (token() === 84 /* ConstKeyword */ && permitInvalidConstAsModifier) {
33732                 // We need to ensure that any subsequent modifiers appear on the same line
33733                 // so that when 'const' is a standalone declaration, we don't issue an error.
33734                 if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
33735                     return undefined;
33736                 }
33737             }
33738             else {
33739                 if (!parseAnyContextualModifier()) {
33740                     return undefined;
33741                 }
33742             }
33743             return finishNode(factory.createToken(kind), pos);
33744         }
33745         /*
33746          * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
33747          * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
33748          * and turns it into a standalone declaration), then it is better to parse it and report an error later.
33749          *
33750          * In such situations, 'permitInvalidConstAsModifier' should be set to true.
33751          */
33752         function parseModifiers(permitInvalidConstAsModifier) {
33753             var pos = getNodePos();
33754             var list, modifier;
33755             while (modifier = tryParseModifier(permitInvalidConstAsModifier)) {
33756                 list = ts.append(list, modifier);
33757             }
33758             return list && createNodeArray(list, pos);
33759         }
33760         function parseModifiersForArrowFunction() {
33761             var modifiers;
33762             if (token() === 129 /* AsyncKeyword */) {
33763                 var pos = getNodePos();
33764                 nextToken();
33765                 var modifier = finishNode(factory.createToken(129 /* AsyncKeyword */), pos);
33766                 modifiers = createNodeArray([modifier], pos);
33767             }
33768             return modifiers;
33769         }
33770         function parseClassElement() {
33771             var pos = getNodePos();
33772             if (token() === 26 /* SemicolonToken */) {
33773                 nextToken();
33774                 return finishNode(factory.createSemicolonClassElement(), pos);
33775             }
33776             var hasJSDoc = hasPrecedingJSDocComment();
33777             var decorators = parseDecorators();
33778             var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
33779             if (parseContextualModifier(134 /* GetKeyword */)) {
33780                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */);
33781             }
33782             if (parseContextualModifier(146 /* SetKeyword */)) {
33783                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */);
33784             }
33785             if (token() === 132 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) {
33786                 var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers);
33787                 if (constructorDeclaration) {
33788                     return constructorDeclaration;
33789                 }
33790             }
33791             if (isIndexSignature()) {
33792                 return parseIndexSignatureDeclaration(pos, hasJSDoc, decorators, modifiers);
33793             }
33794             // It is very important that we check this *after* checking indexers because
33795             // the [ token can start an index signature or a computed property name
33796             if (ts.tokenIsIdentifierOrKeyword(token()) ||
33797                 token() === 10 /* StringLiteral */ ||
33798                 token() === 8 /* NumericLiteral */ ||
33799                 token() === 41 /* AsteriskToken */ ||
33800                 token() === 22 /* OpenBracketToken */) {
33801                 var isAmbient = ts.some(modifiers, isDeclareModifier);
33802                 if (isAmbient) {
33803                     for (var _i = 0, _a = modifiers; _i < _a.length; _i++) {
33804                         var m = _a[_i];
33805                         m.flags |= 8388608 /* Ambient */;
33806                     }
33807                     return doInsideOfContext(8388608 /* Ambient */, function () { return parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers); });
33808                 }
33809                 else {
33810                     return parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers);
33811                 }
33812             }
33813             if (decorators || modifiers) {
33814                 // treat this as a property declaration with a missing name.
33815                 var name = createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
33816                 return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, /*questionToken*/ undefined);
33817             }
33818             // 'isClassMemberStart' should have hinted not to attempt parsing.
33819             return ts.Debug.fail("Should not have attempted to parse class member declaration.");
33820         }
33821         function parseClassExpression() {
33822             return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 221 /* ClassExpression */);
33823         }
33824         function parseClassDeclaration(pos, hasJSDoc, decorators, modifiers) {
33825             return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 252 /* ClassDeclaration */);
33826         }
33827         function parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, kind) {
33828             var savedAwaitContext = inAwaitContext();
33829             parseExpected(83 /* ClassKeyword */);
33830             // We don't parse the name here in await context, instead we will report a grammar error in the checker.
33831             var name = parseNameOfClassDeclarationOrExpression();
33832             var typeParameters = parseTypeParameters();
33833             if (ts.some(modifiers, ts.isExportModifier))
33834                 setAwaitContext(/*value*/ true);
33835             var heritageClauses = parseHeritageClauses();
33836             var members;
33837             if (parseExpected(18 /* OpenBraceToken */)) {
33838                 // ClassTail[Yield,Await] : (Modified) See 14.5
33839                 //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
33840                 members = parseClassMembers();
33841                 parseExpected(19 /* CloseBraceToken */);
33842             }
33843             else {
33844                 members = createMissingList();
33845             }
33846             setAwaitContext(savedAwaitContext);
33847             var node = kind === 252 /* ClassDeclaration */
33848                 ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members)
33849                 : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members);
33850             return withJSDoc(finishNode(node, pos), hasJSDoc);
33851         }
33852         function parseNameOfClassDeclarationOrExpression() {
33853             // implements is a future reserved word so
33854             // 'class implements' might mean either
33855             // - class expression with omitted name, 'implements' starts heritage clause
33856             // - class with name 'implements'
33857             // 'isImplementsClause' helps to disambiguate between these two cases
33858             return isBindingIdentifier() && !isImplementsClause()
33859                 ? createIdentifier(isBindingIdentifier())
33860                 : undefined;
33861         }
33862         function isImplementsClause() {
33863             return token() === 116 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
33864         }
33865         function parseHeritageClauses() {
33866             // ClassTail[Yield,Await] : (Modified) See 14.5
33867             //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
33868             if (isHeritageClause()) {
33869                 return parseList(22 /* HeritageClauses */, parseHeritageClause);
33870             }
33871             return undefined;
33872         }
33873         function parseHeritageClause() {
33874             var pos = getNodePos();
33875             var tok = token();
33876             ts.Debug.assert(tok === 93 /* ExtendsKeyword */ || tok === 116 /* ImplementsKeyword */); // isListElement() should ensure this.
33877             nextToken();
33878             var types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
33879             return finishNode(factory.createHeritageClause(tok, types), pos);
33880         }
33881         function parseExpressionWithTypeArguments() {
33882             var pos = getNodePos();
33883             var expression = parseLeftHandSideExpressionOrHigher();
33884             var typeArguments = tryParseTypeArguments();
33885             return finishNode(factory.createExpressionWithTypeArguments(expression, typeArguments), pos);
33886         }
33887         function tryParseTypeArguments() {
33888             return token() === 29 /* LessThanToken */ ?
33889                 parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */) : undefined;
33890         }
33891         function isHeritageClause() {
33892             return token() === 93 /* ExtendsKeyword */ || token() === 116 /* ImplementsKeyword */;
33893         }
33894         function parseClassMembers() {
33895             return parseList(5 /* ClassMembers */, parseClassElement);
33896         }
33897         function parseInterfaceDeclaration(pos, hasJSDoc, decorators, modifiers) {
33898             parseExpected(117 /* InterfaceKeyword */);
33899             var name = parseIdentifier();
33900             var typeParameters = parseTypeParameters();
33901             var heritageClauses = parseHeritageClauses();
33902             var members = parseObjectTypeMembers();
33903             var node = factory.createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members);
33904             return withJSDoc(finishNode(node, pos), hasJSDoc);
33905         }
33906         function parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers) {
33907             parseExpected(149 /* TypeKeyword */);
33908             var name = parseIdentifier();
33909             var typeParameters = parseTypeParameters();
33910             parseExpected(62 /* EqualsToken */);
33911             var type = token() === 136 /* IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType();
33912             parseSemicolon();
33913             var node = factory.createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type);
33914             return withJSDoc(finishNode(node, pos), hasJSDoc);
33915         }
33916         // In an ambient declaration, the grammar only allows integer literals as initializers.
33917         // In a non-ambient declaration, the grammar allows uninitialized members only in a
33918         // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
33919         // or any time an integer literal initializer is encountered.
33920         function parseEnumMember() {
33921             var pos = getNodePos();
33922             var hasJSDoc = hasPrecedingJSDocComment();
33923             var name = parsePropertyName();
33924             var initializer = allowInAnd(parseInitializer);
33925             return withJSDoc(finishNode(factory.createEnumMember(name, initializer), pos), hasJSDoc);
33926         }
33927         function parseEnumDeclaration(pos, hasJSDoc, decorators, modifiers) {
33928             parseExpected(91 /* EnumKeyword */);
33929             var name = parseIdentifier();
33930             var members;
33931             if (parseExpected(18 /* OpenBraceToken */)) {
33932                 members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); });
33933                 parseExpected(19 /* CloseBraceToken */);
33934             }
33935             else {
33936                 members = createMissingList();
33937             }
33938             var node = factory.createEnumDeclaration(decorators, modifiers, name, members);
33939             return withJSDoc(finishNode(node, pos), hasJSDoc);
33940         }
33941         function parseModuleBlock() {
33942             var pos = getNodePos();
33943             var statements;
33944             if (parseExpected(18 /* OpenBraceToken */)) {
33945                 statements = parseList(1 /* BlockStatements */, parseStatement);
33946                 parseExpected(19 /* CloseBraceToken */);
33947             }
33948             else {
33949                 statements = createMissingList();
33950             }
33951             return finishNode(factory.createModuleBlock(statements), pos);
33952         }
33953         function parseModuleOrNamespaceDeclaration(pos, hasJSDoc, decorators, modifiers, flags) {
33954             // If we are parsing a dotted namespace name, we want to
33955             // propagate the 'Namespace' flag across the names if set.
33956             var namespaceFlag = flags & 16 /* Namespace */;
33957             var name = parseIdentifier();
33958             var body = parseOptional(24 /* DotToken */)
33959                 ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag)
33960                 : parseModuleBlock();
33961             var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags);
33962             return withJSDoc(finishNode(node, pos), hasJSDoc);
33963         }
33964         function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers) {
33965             var flags = 0;
33966             var name;
33967             if (token() === 154 /* GlobalKeyword */) {
33968                 // parse 'global' as name of global scope augmentation
33969                 name = parseIdentifier();
33970                 flags |= 1024 /* GlobalAugmentation */;
33971             }
33972             else {
33973                 name = parseLiteralNode();
33974                 name.text = internIdentifier(name.text);
33975             }
33976             var body;
33977             if (token() === 18 /* OpenBraceToken */) {
33978                 body = parseModuleBlock();
33979             }
33980             else {
33981                 parseSemicolon();
33982             }
33983             var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags);
33984             return withJSDoc(finishNode(node, pos), hasJSDoc);
33985         }
33986         function parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers) {
33987             var flags = 0;
33988             if (token() === 154 /* GlobalKeyword */) {
33989                 // global augmentation
33990                 return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
33991             }
33992             else if (parseOptional(140 /* NamespaceKeyword */)) {
33993                 flags |= 16 /* Namespace */;
33994             }
33995             else {
33996                 parseExpected(139 /* ModuleKeyword */);
33997                 if (token() === 10 /* StringLiteral */) {
33998                     return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
33999                 }
34000             }
34001             return parseModuleOrNamespaceDeclaration(pos, hasJSDoc, decorators, modifiers, flags);
34002         }
34003         function isExternalModuleReference() {
34004             return token() === 143 /* RequireKeyword */ &&
34005                 lookAhead(nextTokenIsOpenParen);
34006         }
34007         function nextTokenIsOpenParen() {
34008             return nextToken() === 20 /* OpenParenToken */;
34009         }
34010         function nextTokenIsSlash() {
34011             return nextToken() === 43 /* SlashToken */;
34012         }
34013         function parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers) {
34014             parseExpected(126 /* AsKeyword */);
34015             parseExpected(140 /* NamespaceKeyword */);
34016             var name = parseIdentifier();
34017             parseSemicolon();
34018             var node = factory.createNamespaceExportDeclaration(name);
34019             // NamespaceExportDeclaration nodes cannot have decorators or modifiers, so we attach them here so we can report them in the grammar checker
34020             node.decorators = decorators;
34021             node.modifiers = modifiers;
34022             return withJSDoc(finishNode(node, pos), hasJSDoc);
34023         }
34024         function parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers) {
34025             parseExpected(99 /* ImportKeyword */);
34026             var afterImportPos = scanner.getStartPos();
34027             // We don't parse the identifier here in await context, instead we will report a grammar error in the checker.
34028             var identifier;
34029             if (isIdentifier()) {
34030                 identifier = parseIdentifier();
34031             }
34032             var isTypeOnly = false;
34033             if (token() !== 153 /* FromKeyword */ &&
34034                 (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" &&
34035                 (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
34036                 isTypeOnly = true;
34037                 identifier = isIdentifier() ? parseIdentifier() : undefined;
34038             }
34039             if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
34040                 return parseImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers, identifier, isTypeOnly);
34041             }
34042             // ImportDeclaration:
34043             //  import ImportClause from ModuleSpecifier ;
34044             //  import ModuleSpecifier;
34045             var importClause;
34046             if (identifier || // import id
34047                 token() === 41 /* AsteriskToken */ || // import *
34048                 token() === 18 /* OpenBraceToken */ // import {
34049             ) {
34050                 importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
34051                 parseExpected(153 /* FromKeyword */);
34052             }
34053             var moduleSpecifier = parseModuleSpecifier();
34054             parseSemicolon();
34055             var node = factory.createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier);
34056             return withJSDoc(finishNode(node, pos), hasJSDoc);
34057         }
34058         function tokenAfterImportDefinitelyProducesImportDeclaration() {
34059             return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */;
34060         }
34061         function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
34062             // In `import id ___`, the current token decides whether to produce
34063             // an ImportDeclaration or ImportEqualsDeclaration.
34064             return token() === 27 /* CommaToken */ || token() === 153 /* FromKeyword */;
34065         }
34066         function parseImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers, identifier, isTypeOnly) {
34067             parseExpected(62 /* EqualsToken */);
34068             var moduleReference = parseModuleReference();
34069             parseSemicolon();
34070             var node = factory.createImportEqualsDeclaration(decorators, modifiers, isTypeOnly, identifier, moduleReference);
34071             var finished = withJSDoc(finishNode(node, pos), hasJSDoc);
34072             return finished;
34073         }
34074         function parseImportClause(identifier, pos, isTypeOnly) {
34075             // ImportClause:
34076             //  ImportedDefaultBinding
34077             //  NameSpaceImport
34078             //  NamedImports
34079             //  ImportedDefaultBinding, NameSpaceImport
34080             //  ImportedDefaultBinding, NamedImports
34081             // If there was no default import or if there is comma token after default import
34082             // parse namespace or named imports
34083             var namedBindings;
34084             if (!identifier ||
34085                 parseOptional(27 /* CommaToken */)) {
34086                 namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(264 /* NamedImports */);
34087             }
34088             return finishNode(factory.createImportClause(isTypeOnly, identifier, namedBindings), pos);
34089         }
34090         function parseModuleReference() {
34091             return isExternalModuleReference()
34092                 ? parseExternalModuleReference()
34093                 : parseEntityName(/*allowReservedWords*/ false);
34094         }
34095         function parseExternalModuleReference() {
34096             var pos = getNodePos();
34097             parseExpected(143 /* RequireKeyword */);
34098             parseExpected(20 /* OpenParenToken */);
34099             var expression = parseModuleSpecifier();
34100             parseExpected(21 /* CloseParenToken */);
34101             return finishNode(factory.createExternalModuleReference(expression), pos);
34102         }
34103         function parseModuleSpecifier() {
34104             if (token() === 10 /* StringLiteral */) {
34105                 var result = parseLiteralNode();
34106                 result.text = internIdentifier(result.text);
34107                 return result;
34108             }
34109             else {
34110                 // We allow arbitrary expressions here, even though the grammar only allows string
34111                 // literals.  We check to ensure that it is only a string literal later in the grammar
34112                 // check pass.
34113                 return parseExpression();
34114             }
34115         }
34116         function parseNamespaceImport() {
34117             // NameSpaceImport:
34118             //  * as ImportedBinding
34119             var pos = getNodePos();
34120             parseExpected(41 /* AsteriskToken */);
34121             parseExpected(126 /* AsKeyword */);
34122             var name = parseIdentifier();
34123             return finishNode(factory.createNamespaceImport(name), pos);
34124         }
34125         function parseNamedImportsOrExports(kind) {
34126             var pos = getNodePos();
34127             // NamedImports:
34128             //  { }
34129             //  { ImportsList }
34130             //  { ImportsList, }
34131             // ImportsList:
34132             //  ImportSpecifier
34133             //  ImportsList, ImportSpecifier
34134             var node = kind === 264 /* NamedImports */
34135                 ? factory.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseImportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */))
34136                 : factory.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */));
34137             return finishNode(node, pos);
34138         }
34139         function parseExportSpecifier() {
34140             return parseImportOrExportSpecifier(270 /* ExportSpecifier */);
34141         }
34142         function parseImportSpecifier() {
34143             return parseImportOrExportSpecifier(265 /* ImportSpecifier */);
34144         }
34145         function parseImportOrExportSpecifier(kind) {
34146             var pos = getNodePos();
34147             // ImportSpecifier:
34148             //   BindingIdentifier
34149             //   IdentifierName as BindingIdentifier
34150             // ExportSpecifier:
34151             //   IdentifierName
34152             //   IdentifierName as IdentifierName
34153             var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
34154             var checkIdentifierStart = scanner.getTokenPos();
34155             var checkIdentifierEnd = scanner.getTextPos();
34156             var identifierName = parseIdentifierName();
34157             var propertyName;
34158             var name;
34159             if (token() === 126 /* AsKeyword */) {
34160                 propertyName = identifierName;
34161                 parseExpected(126 /* AsKeyword */);
34162                 checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
34163                 checkIdentifierStart = scanner.getTokenPos();
34164                 checkIdentifierEnd = scanner.getTextPos();
34165                 name = parseIdentifierName();
34166             }
34167             else {
34168                 name = identifierName;
34169             }
34170             if (kind === 265 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
34171                 parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
34172             }
34173             var node = kind === 265 /* ImportSpecifier */
34174                 ? factory.createImportSpecifier(propertyName, name)
34175                 : factory.createExportSpecifier(propertyName, name);
34176             return finishNode(node, pos);
34177         }
34178         function parseNamespaceExport(pos) {
34179             return finishNode(factory.createNamespaceExport(parseIdentifierName()), pos);
34180         }
34181         function parseExportDeclaration(pos, hasJSDoc, decorators, modifiers) {
34182             var savedAwaitContext = inAwaitContext();
34183             setAwaitContext(/*value*/ true);
34184             var exportClause;
34185             var moduleSpecifier;
34186             var isTypeOnly = parseOptional(149 /* TypeKeyword */);
34187             var namespaceExportPos = getNodePos();
34188             if (parseOptional(41 /* AsteriskToken */)) {
34189                 if (parseOptional(126 /* AsKeyword */)) {
34190                     exportClause = parseNamespaceExport(namespaceExportPos);
34191                 }
34192                 parseExpected(153 /* FromKeyword */);
34193                 moduleSpecifier = parseModuleSpecifier();
34194             }
34195             else {
34196                 exportClause = parseNamedImportsOrExports(268 /* NamedExports */);
34197                 // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
34198                 // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
34199                 // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
34200                 if (token() === 153 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
34201                     parseExpected(153 /* FromKeyword */);
34202                     moduleSpecifier = parseModuleSpecifier();
34203                 }
34204             }
34205             parseSemicolon();
34206             setAwaitContext(savedAwaitContext);
34207             var node = factory.createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier);
34208             return withJSDoc(finishNode(node, pos), hasJSDoc);
34209         }
34210         function parseExportAssignment(pos, hasJSDoc, decorators, modifiers) {
34211             var savedAwaitContext = inAwaitContext();
34212             setAwaitContext(/*value*/ true);
34213             var isExportEquals;
34214             if (parseOptional(62 /* EqualsToken */)) {
34215                 isExportEquals = true;
34216             }
34217             else {
34218                 parseExpected(87 /* DefaultKeyword */);
34219             }
34220             var expression = parseAssignmentExpressionOrHigher();
34221             parseSemicolon();
34222             setAwaitContext(savedAwaitContext);
34223             var node = factory.createExportAssignment(decorators, modifiers, isExportEquals, expression);
34224             return withJSDoc(finishNode(node, pos), hasJSDoc);
34225         }
34226         function setExternalModuleIndicator(sourceFile) {
34227             // Try to use the first top-level import/export when available, then
34228             // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
34229             sourceFile.externalModuleIndicator =
34230                 ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
34231                     getImportMetaIfNecessary(sourceFile);
34232         }
34233         function isAnExternalModuleIndicatorNode(node) {
34234             return hasModifierOfKind(node, 92 /* ExportKeyword */)
34235                 || ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)
34236                 || ts.isImportDeclaration(node)
34237                 || ts.isExportAssignment(node)
34238                 || ts.isExportDeclaration(node) ? node : undefined;
34239         }
34240         function getImportMetaIfNecessary(sourceFile) {
34241             return sourceFile.flags & 2097152 /* PossiblyContainsImportMeta */ ?
34242                 walkTreeForExternalModuleIndicators(sourceFile) :
34243                 undefined;
34244         }
34245         function walkTreeForExternalModuleIndicators(node) {
34246             return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
34247         }
34248         /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
34249         function hasModifierOfKind(node, kind) {
34250             return ts.some(node.modifiers, function (m) { return m.kind === kind; });
34251         }
34252         function isImportMeta(node) {
34253             return ts.isMetaProperty(node) && node.keywordToken === 99 /* ImportKeyword */ && node.name.escapedText === "meta";
34254         }
34255         var ParsingContext;
34256         (function (ParsingContext) {
34257             ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
34258             ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
34259             ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
34260             ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
34261             ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
34262             ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
34263             ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
34264             ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
34265             ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
34266             ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
34267             ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
34268             ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
34269             ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
34270             ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
34271             ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
34272             ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
34273             ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
34274             ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
34275             ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
34276             ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
34277             ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
34278             ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
34279             ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
34280             ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
34281             ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts
34282         })(ParsingContext || (ParsingContext = {}));
34283         var Tristate;
34284         (function (Tristate) {
34285             Tristate[Tristate["False"] = 0] = "False";
34286             Tristate[Tristate["True"] = 1] = "True";
34287             Tristate[Tristate["Unknown"] = 2] = "Unknown";
34288         })(Tristate || (Tristate = {}));
34289         var JSDocParser;
34290         (function (JSDocParser) {
34291             function parseJSDocTypeExpressionForTests(content, start, length) {
34292                 initializeState("file.js", content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
34293                 scanner.setText(content, start, length);
34294                 currentToken = scanner.scan();
34295                 var jsDocTypeExpression = parseJSDocTypeExpression();
34296                 var sourceFile = createSourceFile("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false, [], factory.createToken(1 /* EndOfFileToken */), 0 /* None */);
34297                 var diagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
34298                 if (jsDocDiagnostics) {
34299                     sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
34300                 }
34301                 clearState();
34302                 return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
34303             }
34304             JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
34305             // Parses out a JSDoc type expression.
34306             function parseJSDocTypeExpression(mayOmitBraces) {
34307                 var pos = getNodePos();
34308                 var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
34309                 var type = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
34310                 if (!mayOmitBraces || hasBrace) {
34311                     parseExpectedJSDoc(19 /* CloseBraceToken */);
34312                 }
34313                 var result = factory.createJSDocTypeExpression(type);
34314                 fixupParentReferences(result);
34315                 return finishNode(result, pos);
34316             }
34317             JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
34318             function parseJSDocNameReference() {
34319                 var pos = getNodePos();
34320                 var hasBrace = parseOptional(18 /* OpenBraceToken */);
34321                 var entityName = parseEntityName(/* allowReservedWords*/ false);
34322                 if (hasBrace) {
34323                     parseExpectedJSDoc(19 /* CloseBraceToken */);
34324                 }
34325                 var result = factory.createJSDocNameReference(entityName);
34326                 fixupParentReferences(result);
34327                 return finishNode(result, pos);
34328             }
34329             JSDocParser.parseJSDocNameReference = parseJSDocNameReference;
34330             function parseIsolatedJSDocComment(content, start, length) {
34331                 initializeState("", content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
34332                 var jsDoc = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
34333                 var sourceFile = { languageVariant: 0 /* Standard */, text: content };
34334                 var diagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
34335                 clearState();
34336                 return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
34337             }
34338             JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
34339             function parseJSDocComment(parent, start, length) {
34340                 var saveToken = currentToken;
34341                 var saveParseDiagnosticsLength = parseDiagnostics.length;
34342                 var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
34343                 var comment = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
34344                 ts.setParent(comment, parent);
34345                 if (contextFlags & 131072 /* JavaScriptFile */) {
34346                     if (!jsDocDiagnostics) {
34347                         jsDocDiagnostics = [];
34348                     }
34349                     jsDocDiagnostics.push.apply(jsDocDiagnostics, parseDiagnostics);
34350                 }
34351                 currentToken = saveToken;
34352                 parseDiagnostics.length = saveParseDiagnosticsLength;
34353                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
34354                 return comment;
34355             }
34356             JSDocParser.parseJSDocComment = parseJSDocComment;
34357             var JSDocState;
34358             (function (JSDocState) {
34359                 JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
34360                 JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
34361                 JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
34362                 JSDocState[JSDocState["SavingBackticks"] = 3] = "SavingBackticks";
34363             })(JSDocState || (JSDocState = {}));
34364             var PropertyLikeParse;
34365             (function (PropertyLikeParse) {
34366                 PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
34367                 PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
34368                 PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
34369             })(PropertyLikeParse || (PropertyLikeParse = {}));
34370             function parseJSDocCommentWorker(start, length) {
34371                 if (start === void 0) { start = 0; }
34372                 var content = sourceText;
34373                 var end = length === undefined ? content.length : start + length;
34374                 length = end - start;
34375                 ts.Debug.assert(start >= 0);
34376                 ts.Debug.assert(start <= end);
34377                 ts.Debug.assert(end <= content.length);
34378                 // Check for /** (JSDoc opening part)
34379                 if (!isJSDocLikeText(content, start)) {
34380                     return undefined;
34381                 }
34382                 var tags;
34383                 var tagsPos;
34384                 var tagsEnd;
34385                 var comments = [];
34386                 // + 3 for leading /**, - 5 in total for /** */
34387                 return scanner.scanRange(start + 3, length - 5, function () {
34388                     // Initially we can parse out a tag.  We also have seen a starting asterisk.
34389                     // This is so that /** * @type */ doesn't parse.
34390                     var state = 1 /* SawAsterisk */;
34391                     var margin;
34392                     // + 4 for leading '/** '
34393                     // + 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
34394                     var indent = start - (content.lastIndexOf("\n", start) + 1) + 4;
34395                     function pushComment(text) {
34396                         if (!margin) {
34397                             margin = indent;
34398                         }
34399                         comments.push(text);
34400                         indent += text.length;
34401                     }
34402                     nextTokenJSDoc();
34403                     while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
34404                         ;
34405                     if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
34406                         state = 0 /* BeginningOfLine */;
34407                         indent = 0;
34408                     }
34409                     loop: while (true) {
34410                         switch (token()) {
34411                             case 59 /* AtToken */:
34412                                 if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
34413                                     removeTrailingWhitespace(comments);
34414                                     addTag(parseTag(indent));
34415                                     // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
34416                                     // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
34417                                     // for malformed examples like `/** @param {string} x @returns {number} the length */`
34418                                     state = 0 /* BeginningOfLine */;
34419                                     margin = undefined;
34420                                 }
34421                                 else {
34422                                     pushComment(scanner.getTokenText());
34423                                 }
34424                                 break;
34425                             case 4 /* NewLineTrivia */:
34426                                 comments.push(scanner.getTokenText());
34427                                 state = 0 /* BeginningOfLine */;
34428                                 indent = 0;
34429                                 break;
34430                             case 41 /* AsteriskToken */:
34431                                 var asterisk = scanner.getTokenText();
34432                                 if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
34433                                     // If we've already seen an asterisk, then we can no longer parse a tag on this line
34434                                     state = 2 /* SavingComments */;
34435                                     pushComment(asterisk);
34436                                 }
34437                                 else {
34438                                     // Ignore the first asterisk on a line
34439                                     state = 1 /* SawAsterisk */;
34440                                     indent += asterisk.length;
34441                                 }
34442                                 break;
34443                             case 5 /* WhitespaceTrivia */:
34444                                 // only collect whitespace if we're already saving comments or have just crossed the comment indent margin
34445                                 var whitespace = scanner.getTokenText();
34446                                 if (state === 2 /* SavingComments */) {
34447                                     comments.push(whitespace);
34448                                 }
34449                                 else if (margin !== undefined && indent + whitespace.length > margin) {
34450                                     comments.push(whitespace.slice(margin - indent));
34451                                 }
34452                                 indent += whitespace.length;
34453                                 break;
34454                             case 1 /* EndOfFileToken */:
34455                                 break loop;
34456                             default:
34457                                 // Anything else is doc comment text. We just save it. Because it
34458                                 // wasn't a tag, we can no longer parse a tag on this line until we hit the next
34459                                 // line break.
34460                                 state = 2 /* SavingComments */;
34461                                 pushComment(scanner.getTokenText());
34462                                 break;
34463                         }
34464                         nextTokenJSDoc();
34465                     }
34466                     removeLeadingNewlines(comments);
34467                     removeTrailingWhitespace(comments);
34468                     return createJSDocComment();
34469                 });
34470                 function removeLeadingNewlines(comments) {
34471                     while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
34472                         comments.shift();
34473                     }
34474                 }
34475                 function removeTrailingWhitespace(comments) {
34476                     while (comments.length && comments[comments.length - 1].trim() === "") {
34477                         comments.pop();
34478                     }
34479                 }
34480                 function createJSDocComment() {
34481                     var comment = comments.length ? comments.join("") : undefined;
34482                     var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd);
34483                     return finishNode(factory.createJSDocComment(comment, tagsArray), start, end);
34484                 }
34485                 function isNextNonwhitespaceTokenEndOfFile() {
34486                     // We must use infinite lookahead, as there could be any number of newlines :(
34487                     while (true) {
34488                         nextTokenJSDoc();
34489                         if (token() === 1 /* EndOfFileToken */) {
34490                             return true;
34491                         }
34492                         if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
34493                             return false;
34494                         }
34495                     }
34496                 }
34497                 function skipWhitespace() {
34498                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
34499                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
34500                             return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
34501                         }
34502                     }
34503                     while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
34504                         nextTokenJSDoc();
34505                     }
34506                 }
34507                 function skipWhitespaceOrAsterisk() {
34508                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
34509                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
34510                             return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
34511                         }
34512                     }
34513                     var precedingLineBreak = scanner.hasPrecedingLineBreak();
34514                     var seenLineBreak = false;
34515                     var indentText = "";
34516                     while ((precedingLineBreak && token() === 41 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
34517                         indentText += scanner.getTokenText();
34518                         if (token() === 4 /* NewLineTrivia */) {
34519                             precedingLineBreak = true;
34520                             seenLineBreak = true;
34521                             indentText = "";
34522                         }
34523                         else if (token() === 41 /* AsteriskToken */) {
34524                             precedingLineBreak = false;
34525                         }
34526                         nextTokenJSDoc();
34527                     }
34528                     return seenLineBreak ? indentText : "";
34529                 }
34530                 function parseTag(margin) {
34531                     ts.Debug.assert(token() === 59 /* AtToken */);
34532                     var start = scanner.getTokenPos();
34533                     nextTokenJSDoc();
34534                     var tagName = parseJSDocIdentifierName(/*message*/ undefined);
34535                     var indentText = skipWhitespaceOrAsterisk();
34536                     var tag;
34537                     switch (tagName.escapedText) {
34538                         case "author":
34539                             tag = parseAuthorTag(start, tagName, margin, indentText);
34540                             break;
34541                         case "implements":
34542                             tag = parseImplementsTag(start, tagName, margin, indentText);
34543                             break;
34544                         case "augments":
34545                         case "extends":
34546                             tag = parseAugmentsTag(start, tagName, margin, indentText);
34547                             break;
34548                         case "class":
34549                         case "constructor":
34550                             tag = parseSimpleTag(start, factory.createJSDocClassTag, tagName, margin, indentText);
34551                             break;
34552                         case "public":
34553                             tag = parseSimpleTag(start, factory.createJSDocPublicTag, tagName, margin, indentText);
34554                             break;
34555                         case "private":
34556                             tag = parseSimpleTag(start, factory.createJSDocPrivateTag, tagName, margin, indentText);
34557                             break;
34558                         case "protected":
34559                             tag = parseSimpleTag(start, factory.createJSDocProtectedTag, tagName, margin, indentText);
34560                             break;
34561                         case "readonly":
34562                             tag = parseSimpleTag(start, factory.createJSDocReadonlyTag, tagName, margin, indentText);
34563                             break;
34564                         case "deprecated":
34565                             hasDeprecatedTag = true;
34566                             tag = parseSimpleTag(start, factory.createJSDocDeprecatedTag, tagName, margin, indentText);
34567                             break;
34568                         case "this":
34569                             tag = parseThisTag(start, tagName, margin, indentText);
34570                             break;
34571                         case "enum":
34572                             tag = parseEnumTag(start, tagName, margin, indentText);
34573                             break;
34574                         case "arg":
34575                         case "argument":
34576                         case "param":
34577                             return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, margin);
34578                         case "return":
34579                         case "returns":
34580                             tag = parseReturnTag(start, tagName, margin, indentText);
34581                             break;
34582                         case "template":
34583                             tag = parseTemplateTag(start, tagName, margin, indentText);
34584                             break;
34585                         case "type":
34586                             tag = parseTypeTag(start, tagName, margin, indentText);
34587                             break;
34588                         case "typedef":
34589                             tag = parseTypedefTag(start, tagName, margin, indentText);
34590                             break;
34591                         case "callback":
34592                             tag = parseCallbackTag(start, tagName, margin, indentText);
34593                             break;
34594                         case "see":
34595                             tag = parseSeeTag(start, tagName, margin, indentText);
34596                             break;
34597                         default:
34598                             tag = parseUnknownTag(start, tagName, margin, indentText);
34599                             break;
34600                     }
34601                     return tag;
34602                 }
34603                 function parseTrailingTagComments(pos, end, margin, indentText) {
34604                     // some tags, like typedef and callback, have already parsed their comments earlier
34605                     if (!indentText) {
34606                         margin += end - pos;
34607                     }
34608                     return parseTagComments(margin, indentText.slice(margin));
34609                 }
34610                 function parseTagComments(indent, initialMargin) {
34611                     var comments = [];
34612                     var state = 0 /* BeginningOfLine */;
34613                     var previousWhitespace = true;
34614                     var margin;
34615                     function pushComment(text) {
34616                         if (!margin) {
34617                             margin = indent;
34618                         }
34619                         comments.push(text);
34620                         indent += text.length;
34621                     }
34622                     if (initialMargin !== undefined) {
34623                         // jump straight to saving comments if there is some initial indentation
34624                         if (initialMargin !== "") {
34625                             pushComment(initialMargin);
34626                         }
34627                         state = 1 /* SawAsterisk */;
34628                     }
34629                     var tok = token();
34630                     loop: while (true) {
34631                         switch (tok) {
34632                             case 4 /* NewLineTrivia */:
34633                                 state = 0 /* BeginningOfLine */;
34634                                 // don't use pushComment here because we want to keep the margin unchanged
34635                                 comments.push(scanner.getTokenText());
34636                                 indent = 0;
34637                                 break;
34638                             case 59 /* AtToken */:
34639                                 if (state === 3 /* SavingBackticks */ || !previousWhitespace && state === 2 /* SavingComments */) {
34640                                     // @ doesn't start a new tag inside ``, and inside a comment, only after whitespace
34641                                     comments.push(scanner.getTokenText());
34642                                     break;
34643                                 }
34644                                 scanner.setTextPos(scanner.getTextPos() - 1);
34645                             // falls through
34646                             case 1 /* EndOfFileToken */:
34647                                 // Done
34648                                 break loop;
34649                             case 5 /* WhitespaceTrivia */:
34650                                 if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
34651                                     pushComment(scanner.getTokenText());
34652                                 }
34653                                 else {
34654                                     var whitespace = scanner.getTokenText();
34655                                     // if the whitespace crosses the margin, take only the whitespace that passes the margin
34656                                     if (margin !== undefined && indent + whitespace.length > margin) {
34657                                         comments.push(whitespace.slice(margin - indent));
34658                                     }
34659                                     indent += whitespace.length;
34660                                 }
34661                                 break;
34662                             case 18 /* OpenBraceToken */:
34663                                 state = 2 /* SavingComments */;
34664                                 if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) {
34665                                     pushComment(scanner.getTokenText());
34666                                     nextTokenJSDoc();
34667                                     pushComment(scanner.getTokenText());
34668                                     nextTokenJSDoc();
34669                                 }
34670                                 pushComment(scanner.getTokenText());
34671                                 break;
34672                             case 61 /* BacktickToken */:
34673                                 if (state === 3 /* SavingBackticks */) {
34674                                     state = 2 /* SavingComments */;
34675                                 }
34676                                 else {
34677                                     state = 3 /* SavingBackticks */;
34678                                 }
34679                                 pushComment(scanner.getTokenText());
34680                                 break;
34681                             case 41 /* AsteriskToken */:
34682                                 if (state === 0 /* BeginningOfLine */) {
34683                                     // leading asterisks start recording on the *next* (non-whitespace) token
34684                                     state = 1 /* SawAsterisk */;
34685                                     indent += 1;
34686                                     break;
34687                                 }
34688                             // record the * as a comment
34689                             // falls through
34690                             default:
34691                                 if (state !== 3 /* SavingBackticks */) {
34692                                     state = 2 /* SavingComments */; // leading identifiers start recording as well
34693                                 }
34694                                 pushComment(scanner.getTokenText());
34695                                 break;
34696                         }
34697                         previousWhitespace = token() === 5 /* WhitespaceTrivia */;
34698                         tok = nextTokenJSDoc();
34699                     }
34700                     removeLeadingNewlines(comments);
34701                     removeTrailingWhitespace(comments);
34702                     return comments.length === 0 ? undefined : comments.join("");
34703                 }
34704                 function parseUnknownTag(start, tagName, indent, indentText) {
34705                     var end = getNodePos();
34706                     return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, end, indent, indentText)), start, end);
34707                 }
34708                 function addTag(tag) {
34709                     if (!tag) {
34710                         return;
34711                     }
34712                     if (!tags) {
34713                         tags = [tag];
34714                         tagsPos = tag.pos;
34715                     }
34716                     else {
34717                         tags.push(tag);
34718                     }
34719                     tagsEnd = tag.end;
34720                 }
34721                 function tryParseTypeExpression() {
34722                     skipWhitespaceOrAsterisk();
34723                     return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
34724                 }
34725                 function parseBracketNameInPropertyAndParamTag() {
34726                     // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
34727                     var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
34728                     if (isBracketed) {
34729                         skipWhitespace();
34730                     }
34731                     // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
34732                     var isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */);
34733                     var name = parseJSDocEntityName();
34734                     if (isBackquoted) {
34735                         parseExpectedTokenJSDoc(61 /* BacktickToken */);
34736                     }
34737                     if (isBracketed) {
34738                         skipWhitespace();
34739                         // May have an optional default, e.g. '[foo = 42]'
34740                         if (parseOptionalToken(62 /* EqualsToken */)) {
34741                             parseExpression();
34742                         }
34743                         parseExpected(23 /* CloseBracketToken */);
34744                     }
34745                     return { name: name, isBracketed: isBracketed };
34746                 }
34747                 function isObjectOrObjectArrayTypeReference(node) {
34748                     switch (node.kind) {
34749                         case 145 /* ObjectKeyword */:
34750                             return true;
34751                         case 178 /* ArrayType */:
34752                             return isObjectOrObjectArrayTypeReference(node.elementType);
34753                         default:
34754                             return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
34755                     }
34756                 }
34757                 function parseParameterOrPropertyTag(start, tagName, target, indent) {
34758                     var typeExpression = tryParseTypeExpression();
34759                     var isNameFirst = !typeExpression;
34760                     skipWhitespaceOrAsterisk();
34761                     var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
34762                     var indentText = skipWhitespaceOrAsterisk();
34763                     if (isNameFirst) {
34764                         typeExpression = tryParseTypeExpression();
34765                     }
34766                     var comment = parseTrailingTagComments(start, getNodePos(), indent, indentText);
34767                     var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
34768                     if (nestedTypeLiteral) {
34769                         typeExpression = nestedTypeLiteral;
34770                         isNameFirst = true;
34771                     }
34772                     var result = target === 1 /* Property */
34773                         ? factory.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment)
34774                         : factory.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment);
34775                     return finishNode(result, start);
34776                 }
34777                 function parseNestedTypeLiteral(typeExpression, name, target, indent) {
34778                     if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
34779                         var pos = getNodePos();
34780                         var child = void 0;
34781                         var children = void 0;
34782                         while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
34783                             if (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) {
34784                                 children = ts.append(children, child);
34785                             }
34786                         }
34787                         if (children) {
34788                             var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 178 /* ArrayType */), pos);
34789                             return finishNode(factory.createJSDocTypeExpression(literal), pos);
34790                         }
34791                     }
34792                 }
34793                 function parseReturnTag(start, tagName, indent, indentText) {
34794                     if (ts.some(tags, ts.isJSDocReturnTag)) {
34795                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
34796                     }
34797                     var typeExpression = tryParseTypeExpression();
34798                     var end = getNodePos();
34799                     return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, end, indent, indentText)), start, end);
34800                 }
34801                 function parseTypeTag(start, tagName, indent, indentText) {
34802                     if (ts.some(tags, ts.isJSDocTypeTag)) {
34803                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
34804                     }
34805                     var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
34806                     var end = getNodePos();
34807                     var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined;
34808                     return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start, end);
34809                 }
34810                 function parseSeeTag(start, tagName, indent, indentText) {
34811                     var nameExpression = parseJSDocNameReference();
34812                     var end = getNodePos();
34813                     var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined;
34814                     return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start, end);
34815                 }
34816                 function parseAuthorTag(start, tagName, indent, indentText) {
34817                     var comments = parseAuthorNameAndEmail() + (parseTrailingTagComments(start, end, indent, indentText) || "");
34818                     return finishNode(factory.createJSDocAuthorTag(tagName, comments || undefined), start);
34819                 }
34820                 function parseAuthorNameAndEmail() {
34821                     var comments = [];
34822                     var inEmail = false;
34823                     var token = scanner.getToken();
34824                     while (token !== 1 /* EndOfFileToken */ && token !== 4 /* NewLineTrivia */) {
34825                         if (token === 29 /* LessThanToken */) {
34826                             inEmail = true;
34827                         }
34828                         else if (token === 59 /* AtToken */ && !inEmail) {
34829                             break;
34830                         }
34831                         else if (token === 31 /* GreaterThanToken */ && inEmail) {
34832                             comments.push(scanner.getTokenText());
34833                             scanner.setTextPos(scanner.getTokenPos() + 1);
34834                             break;
34835                         }
34836                         comments.push(scanner.getTokenText());
34837                         token = nextTokenJSDoc();
34838                     }
34839                     return comments.join("");
34840                 }
34841                 function parseImplementsTag(start, tagName, margin, indentText) {
34842                     var className = parseExpressionWithTypeArgumentsForAugments();
34843                     var end = getNodePos();
34844                     return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end);
34845                 }
34846                 function parseAugmentsTag(start, tagName, margin, indentText) {
34847                     var className = parseExpressionWithTypeArgumentsForAugments();
34848                     var end = getNodePos();
34849                     return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end);
34850                 }
34851                 function parseExpressionWithTypeArgumentsForAugments() {
34852                     var usedBrace = parseOptional(18 /* OpenBraceToken */);
34853                     var pos = getNodePos();
34854                     var expression = parsePropertyAccessEntityNameExpression();
34855                     var typeArguments = tryParseTypeArguments();
34856                     var node = factory.createExpressionWithTypeArguments(expression, typeArguments);
34857                     var res = finishNode(node, pos);
34858                     if (usedBrace) {
34859                         parseExpected(19 /* CloseBraceToken */);
34860                     }
34861                     return res;
34862                 }
34863                 function parsePropertyAccessEntityNameExpression() {
34864                     var pos = getNodePos();
34865                     var node = parseJSDocIdentifierName();
34866                     while (parseOptional(24 /* DotToken */)) {
34867                         var name = parseJSDocIdentifierName();
34868                         node = finishNode(factory.createPropertyAccessExpression(node, name), pos);
34869                     }
34870                     return node;
34871                 }
34872                 function parseSimpleTag(start, createTag, tagName, margin, indentText) {
34873                     var end = getNodePos();
34874                     return finishNode(createTag(tagName, parseTrailingTagComments(start, end, margin, indentText)), start, end);
34875                 }
34876                 function parseThisTag(start, tagName, margin, indentText) {
34877                     var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
34878                     skipWhitespace();
34879                     var end = getNodePos();
34880                     return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end);
34881                 }
34882                 function parseEnumTag(start, tagName, margin, indentText) {
34883                     var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
34884                     skipWhitespace();
34885                     var end = getNodePos();
34886                     return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end);
34887                 }
34888                 function parseTypedefTag(start, tagName, indent, indentText) {
34889                     var _a;
34890                     var typeExpression = tryParseTypeExpression();
34891                     skipWhitespaceOrAsterisk();
34892                     var fullName = parseJSDocTypeNameWithNamespace();
34893                     skipWhitespace();
34894                     var comment = parseTagComments(indent);
34895                     var end;
34896                     if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
34897                         var child = void 0;
34898                         var childTypeTag = void 0;
34899                         var jsDocPropertyTags = void 0;
34900                         var hasChildren = false;
34901                         while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
34902                             hasChildren = true;
34903                             if (child.kind === 329 /* JSDocTypeTag */) {
34904                                 if (childTypeTag) {
34905                                     parseErrorAtCurrentToken(ts.Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags);
34906                                     var lastError = ts.lastOrUndefined(parseDiagnostics);
34907                                     if (lastError) {
34908                                         ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, 0, 0, ts.Diagnostics.The_tag_was_first_specified_here));
34909                                     }
34910                                     break;
34911                                 }
34912                                 else {
34913                                     childTypeTag = child;
34914                                 }
34915                             }
34916                             else {
34917                                 jsDocPropertyTags = ts.append(jsDocPropertyTags, child);
34918                             }
34919                         }
34920                         if (hasChildren) {
34921                             var isArrayType = typeExpression && typeExpression.type.kind === 178 /* ArrayType */;
34922                             var jsdocTypeLiteral = factory.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType);
34923                             typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
34924                                 childTypeTag.typeExpression :
34925                                 finishNode(jsdocTypeLiteral, start);
34926                             end = typeExpression.end;
34927                         }
34928                     }
34929                     // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
34930                     end = end || comment !== undefined ?
34931                         getNodePos() :
34932                         ((_a = fullName !== null && fullName !== void 0 ? fullName : typeExpression) !== null && _a !== void 0 ? _a : tagName).end;
34933                     if (!comment) {
34934                         comment = parseTrailingTagComments(start, end, indent, indentText);
34935                     }
34936                     var typedefTag = factory.createJSDocTypedefTag(tagName, typeExpression, fullName, comment);
34937                     return finishNode(typedefTag, start, end);
34938                 }
34939                 function parseJSDocTypeNameWithNamespace(nested) {
34940                     var pos = scanner.getTokenPos();
34941                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
34942                         return undefined;
34943                     }
34944                     var typeNameOrNamespaceName = parseJSDocIdentifierName();
34945                     if (parseOptional(24 /* DotToken */)) {
34946                         var body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
34947                         var jsDocNamespaceNode = factory.createModuleDeclaration(
34948                         /*decorators*/ undefined, 
34949                         /*modifiers*/ undefined, typeNameOrNamespaceName, body, nested ? 4 /* NestedNamespace */ : undefined);
34950                         return finishNode(jsDocNamespaceNode, pos);
34951                     }
34952                     if (nested) {
34953                         typeNameOrNamespaceName.isInJSDocNamespace = true;
34954                     }
34955                     return typeNameOrNamespaceName;
34956                 }
34957                 function parseCallbackTagParameters(indent) {
34958                     var pos = getNodePos();
34959                     var child;
34960                     var parameters;
34961                     while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
34962                         parameters = ts.append(parameters, child);
34963                     }
34964                     return createNodeArray(parameters || [], pos);
34965                 }
34966                 function parseCallbackTag(start, tagName, indent, indentText) {
34967                     var fullName = parseJSDocTypeNameWithNamespace();
34968                     skipWhitespace();
34969                     var comment = parseTagComments(indent);
34970                     var parameters = parseCallbackTagParameters(indent);
34971                     var returnTag = tryParse(function () {
34972                         if (parseOptionalJsdoc(59 /* AtToken */)) {
34973                             var tag = parseTag(indent);
34974                             if (tag && tag.kind === 327 /* JSDocReturnTag */) {
34975                                 return tag;
34976                             }
34977                         }
34978                     });
34979                     var typeExpression = finishNode(factory.createJSDocSignature(/*typeParameters*/ undefined, parameters, returnTag), start);
34980                     var end = getNodePos();
34981                     if (!comment) {
34982                         comment = parseTrailingTagComments(start, end, indent, indentText);
34983                     }
34984                     return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start, end);
34985                 }
34986                 function escapedTextsEqual(a, b) {
34987                     while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
34988                         if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
34989                             a = a.left;
34990                             b = b.left;
34991                         }
34992                         else {
34993                             return false;
34994                         }
34995                     }
34996                     return a.escapedText === b.escapedText;
34997                 }
34998                 function parseChildPropertyTag(indent) {
34999                     return parseChildParameterOrPropertyTag(1 /* Property */, indent);
35000                 }
35001                 function parseChildParameterOrPropertyTag(target, indent, name) {
35002                     var canParseTag = true;
35003                     var seenAsterisk = false;
35004                     while (true) {
35005                         switch (nextTokenJSDoc()) {
35006                             case 59 /* AtToken */:
35007                                 if (canParseTag) {
35008                                     var child = tryParseChildTag(target, indent);
35009                                     if (child && (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) &&
35010                                         target !== 4 /* CallbackParameter */ &&
35011                                         name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
35012                                         return false;
35013                                     }
35014                                     return child;
35015                                 }
35016                                 seenAsterisk = false;
35017                                 break;
35018                             case 4 /* NewLineTrivia */:
35019                                 canParseTag = true;
35020                                 seenAsterisk = false;
35021                                 break;
35022                             case 41 /* AsteriskToken */:
35023                                 if (seenAsterisk) {
35024                                     canParseTag = false;
35025                                 }
35026                                 seenAsterisk = true;
35027                                 break;
35028                             case 78 /* Identifier */:
35029                                 canParseTag = false;
35030                                 break;
35031                             case 1 /* EndOfFileToken */:
35032                                 return false;
35033                         }
35034                     }
35035                 }
35036                 function tryParseChildTag(target, indent) {
35037                     ts.Debug.assert(token() === 59 /* AtToken */);
35038                     var start = scanner.getStartPos();
35039                     nextTokenJSDoc();
35040                     var tagName = parseJSDocIdentifierName();
35041                     skipWhitespace();
35042                     var t;
35043                     switch (tagName.escapedText) {
35044                         case "type":
35045                             return target === 1 /* Property */ && parseTypeTag(start, tagName);
35046                         case "prop":
35047                         case "property":
35048                             t = 1 /* Property */;
35049                             break;
35050                         case "arg":
35051                         case "argument":
35052                         case "param":
35053                             t = 2 /* Parameter */ | 4 /* CallbackParameter */;
35054                             break;
35055                         default:
35056                             return false;
35057                     }
35058                     if (!(target & t)) {
35059                         return false;
35060                     }
35061                     return parseParameterOrPropertyTag(start, tagName, target, indent);
35062                 }
35063                 function parseTemplateTagTypeParameter() {
35064                     var typeParameterPos = getNodePos();
35065                     var name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
35066                     return finishNode(factory.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined), typeParameterPos);
35067                 }
35068                 function parseTemplateTagTypeParameters() {
35069                     var pos = getNodePos();
35070                     var typeParameters = [];
35071                     do {
35072                         skipWhitespace();
35073                         typeParameters.push(parseTemplateTagTypeParameter());
35074                         skipWhitespaceOrAsterisk();
35075                     } while (parseOptionalJsdoc(27 /* CommaToken */));
35076                     return createNodeArray(typeParameters, pos);
35077                 }
35078                 function parseTemplateTag(start, tagName, indent, indentText) {
35079                     // The template tag looks like one of the following:
35080                     //   @template T,U,V
35081                     //   @template {Constraint} T
35082                     //
35083                     // According to the [closure docs](https://github.com/google/closure-compiler/wiki/Generic-Types#multiple-bounded-template-types):
35084                     //   > Multiple bounded generics cannot be declared on the same line. For the sake of clarity, if multiple templates share the same
35085                     //   > type bound they must be declared on separate lines.
35086                     //
35087                     // TODO: Determine whether we should enforce this in the checker.
35088                     // TODO: Consider moving the `constraint` to the first type parameter as we could then remove `getEffectiveConstraintOfTypeParameter`.
35089                     // TODO: Consider only parsing a single type parameter if there is a constraint.
35090                     var constraint = token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
35091                     var typeParameters = parseTemplateTagTypeParameters();
35092                     var end = getNodePos();
35093                     return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, end, indent, indentText)), start, end);
35094                 }
35095                 function parseOptionalJsdoc(t) {
35096                     if (token() === t) {
35097                         nextTokenJSDoc();
35098                         return true;
35099                     }
35100                     return false;
35101                 }
35102                 function parseJSDocEntityName() {
35103                     var entity = parseJSDocIdentifierName();
35104                     if (parseOptional(22 /* OpenBracketToken */)) {
35105                         parseExpected(23 /* CloseBracketToken */);
35106                         // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
35107                         // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
35108                         // but it's not worth it to enforce that restriction.
35109                     }
35110                     while (parseOptional(24 /* DotToken */)) {
35111                         var name = parseJSDocIdentifierName();
35112                         if (parseOptional(22 /* OpenBracketToken */)) {
35113                             parseExpected(23 /* CloseBracketToken */);
35114                         }
35115                         entity = createQualifiedName(entity, name);
35116                     }
35117                     return entity;
35118                 }
35119                 function parseJSDocIdentifierName(message) {
35120                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
35121                         return createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
35122                     }
35123                     identifierCount++;
35124                     var pos = scanner.getTokenPos();
35125                     var end = scanner.getTextPos();
35126                     var originalKeywordKind = token();
35127                     var text = internIdentifier(scanner.getTokenValue());
35128                     var result = finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos, end);
35129                     nextTokenJSDoc();
35130                     return result;
35131                 }
35132             }
35133         })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
35134     })(Parser || (Parser = {}));
35135     var IncrementalParser;
35136     (function (IncrementalParser) {
35137         function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
35138             aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
35139             checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
35140             if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
35141                 // if the text didn't change, then we can just return our current source file as-is.
35142                 return sourceFile;
35143             }
35144             if (sourceFile.statements.length === 0) {
35145                 // If we don't have any statements in the current source file, then there's no real
35146                 // way to incrementally parse.  So just do a full parse instead.
35147                 return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
35148             }
35149             // Make sure we're not trying to incrementally update a source file more than once.  Once
35150             // we do an update the original source file is considered unusable from that point onwards.
35151             //
35152             // This is because we do incremental parsing in-place.  i.e. we take nodes from the old
35153             // tree and give them new positions and parents.  From that point on, trusting the old
35154             // tree at all is not possible as far too much of it may violate invariants.
35155             var incrementalSourceFile = sourceFile;
35156             ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
35157             incrementalSourceFile.hasBeenIncrementallyParsed = true;
35158             Parser.fixupParentReferences(incrementalSourceFile);
35159             var oldText = sourceFile.text;
35160             var syntaxCursor = createSyntaxCursor(sourceFile);
35161             // Make the actual change larger so that we know to reparse anything whose lookahead
35162             // might have intersected the change.
35163             var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
35164             checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
35165             // Ensure that extending the affected range only moved the start of the change range
35166             // earlier in the file.
35167             ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
35168             ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
35169             ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
35170             // The is the amount the nodes after the edit range need to be adjusted.  It can be
35171             // positive (if the edit added characters), negative (if the edit deleted characters)
35172             // or zero (if this was a pure overwrite with nothing added/removed).
35173             var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
35174             // If we added or removed characters during the edit, then we need to go and adjust all
35175             // the nodes after the edit.  Those nodes may move forward (if we inserted chars) or they
35176             // may move backward (if we deleted chars).
35177             //
35178             // Doing this helps us out in two ways.  First, it means that any nodes/tokens we want
35179             // to reuse are already at the appropriate position in the new text.  That way when we
35180             // reuse them, we don't have to figure out if they need to be adjusted.  Second, it makes
35181             // it very easy to determine if we can reuse a node.  If the node's position is at where
35182             // we are in the text, then we can reuse it.  Otherwise we can't.  If the node's position
35183             // is ahead of us, then we'll need to rescan tokens.  If the node's position is behind
35184             // us, then we'll need to skip it or crumble it as appropriate
35185             //
35186             // We will also adjust the positions of nodes that intersect the change range as well.
35187             // By doing this, we ensure that all the positions in the old tree are consistent, not
35188             // just the positions of nodes entirely before/after the change range.  By being
35189             // consistent, we can then easily map from positions to nodes in the old tree easily.
35190             //
35191             // Also, mark any syntax elements that intersect the changed span.  We know, up front,
35192             // that we cannot reuse these elements.
35193             updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
35194             // Now that we've set up our internal incremental state just proceed and parse the
35195             // source file in the normal fashion.  When possible the parser will retrieve and
35196             // reuse nodes from the old tree.
35197             //
35198             // Note: passing in 'true' for setNodeParents is very important.  When incrementally
35199             // parsing, we will be reusing nodes from the old tree, and placing it into new
35200             // parents.  If we don't set the parents now, we'll end up with an observably
35201             // inconsistent tree.  Setting the parents on the new tree should be very fast.  We
35202             // will immediately bail out of walking any subtrees when we can see that their parents
35203             // are already correct.
35204             var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
35205             result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks);
35206             return result;
35207         }
35208         IncrementalParser.updateSourceFile = updateSourceFile;
35209         function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) {
35210             if (!oldDirectives)
35211                 return newDirectives;
35212             var commentDirectives;
35213             var addedNewlyScannedDirectives = false;
35214             for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) {
35215                 var directive = oldDirectives_1[_i];
35216                 var range = directive.range, type = directive.type;
35217                 // Range before the change
35218                 if (range.end < changeStart) {
35219                     commentDirectives = ts.append(commentDirectives, directive);
35220                 }
35221                 else if (range.pos > changeRangeOldEnd) {
35222                     addNewlyScannedDirectives();
35223                     // Node is entirely past the change range.  We need to move both its pos and
35224                     // end, forward or backward appropriately.
35225                     var updatedDirective = {
35226                         range: { pos: range.pos + delta, end: range.end + delta },
35227                         type: type
35228                     };
35229                     commentDirectives = ts.append(commentDirectives, updatedDirective);
35230                     if (aggressiveChecks) {
35231                         ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end));
35232                     }
35233                 }
35234                 // Ignore ranges that fall in change range
35235             }
35236             addNewlyScannedDirectives();
35237             return commentDirectives;
35238             function addNewlyScannedDirectives() {
35239                 if (addedNewlyScannedDirectives)
35240                     return;
35241                 addedNewlyScannedDirectives = true;
35242                 if (!commentDirectives) {
35243                     commentDirectives = newDirectives;
35244                 }
35245                 else if (newDirectives) {
35246                     commentDirectives.push.apply(commentDirectives, newDirectives);
35247                 }
35248             }
35249         }
35250         function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
35251             if (isArray) {
35252                 visitArray(element);
35253             }
35254             else {
35255                 visitNode(element);
35256             }
35257             return;
35258             function visitNode(node) {
35259                 var text = "";
35260                 if (aggressiveChecks && shouldCheckNode(node)) {
35261                     text = oldText.substring(node.pos, node.end);
35262                 }
35263                 // Ditch any existing LS children we may have created.  This way we can avoid
35264                 // moving them forward.
35265                 if (node._children) {
35266                     node._children = undefined;
35267                 }
35268                 ts.setTextRangePosEnd(node, node.pos + delta, node.end + delta);
35269                 if (aggressiveChecks && shouldCheckNode(node)) {
35270                     ts.Debug.assert(text === newText.substring(node.pos, node.end));
35271                 }
35272                 forEachChild(node, visitNode, visitArray);
35273                 if (ts.hasJSDocNodes(node)) {
35274                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
35275                         var jsDocComment = _a[_i];
35276                         visitNode(jsDocComment);
35277                     }
35278                 }
35279                 checkNodePositions(node, aggressiveChecks);
35280             }
35281             function visitArray(array) {
35282                 array._children = undefined;
35283                 ts.setTextRangePosEnd(array, array.pos + delta, array.end + delta);
35284                 for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
35285                     var node = array_8[_i];
35286                     visitNode(node);
35287                 }
35288             }
35289         }
35290         function shouldCheckNode(node) {
35291             switch (node.kind) {
35292                 case 10 /* StringLiteral */:
35293                 case 8 /* NumericLiteral */:
35294                 case 78 /* Identifier */:
35295                     return true;
35296             }
35297             return false;
35298         }
35299         function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
35300             ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
35301             ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
35302             ts.Debug.assert(element.pos <= element.end);
35303             // We have an element that intersects the change range in some way.  It may have its
35304             // start, or its end (or both) in the changed range.  We want to adjust any part
35305             // that intersects such that the final tree is in a consistent state.  i.e. all
35306             // children have spans within the span of their parent, and all siblings are ordered
35307             // properly.
35308             // We may need to update both the 'pos' and the 'end' of the element.
35309             // If the 'pos' is before the start of the change, then we don't need to touch it.
35310             // If it isn't, then the 'pos' must be inside the change.  How we update it will
35311             // depend if delta is positive or negative. If delta is positive then we have
35312             // something like:
35313             //
35314             //  -------------------AAA-----------------
35315             //  -------------------BBBCCCCCCC-----------------
35316             //
35317             // In this case, we consider any node that started in the change range to still be
35318             // starting at the same position.
35319             //
35320             // however, if the delta is negative, then we instead have something like this:
35321             //
35322             //  -------------------XXXYYYYYYY-----------------
35323             //  -------------------ZZZ-----------------
35324             //
35325             // In this case, any element that started in the 'X' range will keep its position.
35326             // However any element that started after that will have their pos adjusted to be
35327             // at the end of the new range.  i.e. any node that started in the 'Y' range will
35328             // be adjusted to have their start at the end of the 'Z' range.
35329             //
35330             // The element will keep its position if possible.  Or Move backward to the new-end
35331             // if it's in the 'Y' range.
35332             var pos = Math.min(element.pos, changeRangeNewEnd);
35333             // If the 'end' is after the change range, then we always adjust it by the delta
35334             // amount.  However, if the end is in the change range, then how we adjust it
35335             // will depend on if delta is positive or negative.  If delta is positive then we
35336             // have something like:
35337             //
35338             //  -------------------AAA-----------------
35339             //  -------------------BBBCCCCCCC-----------------
35340             //
35341             // In this case, we consider any node that ended inside the change range to keep its
35342             // end position.
35343             //
35344             // however, if the delta is negative, then we instead have something like this:
35345             //
35346             //  -------------------XXXYYYYYYY-----------------
35347             //  -------------------ZZZ-----------------
35348             //
35349             // In this case, any element that ended in the 'X' range will keep its position.
35350             // However any element that ended after that will have their pos adjusted to be
35351             // at the end of the new range.  i.e. any node that ended in the 'Y' range will
35352             // be adjusted to have their end at the end of the 'Z' range.
35353             var end = element.end >= changeRangeOldEnd ?
35354                 // Element ends after the change range.  Always adjust the end pos.
35355                 element.end + delta :
35356                 // Element ends in the change range.  The element will keep its position if
35357                 // possible. Or Move backward to the new-end if it's in the 'Y' range.
35358                 Math.min(element.end, changeRangeNewEnd);
35359             ts.Debug.assert(pos <= end);
35360             if (element.parent) {
35361                 ts.Debug.assertGreaterThanOrEqual(pos, element.parent.pos);
35362                 ts.Debug.assertLessThanOrEqual(end, element.parent.end);
35363             }
35364             ts.setTextRangePosEnd(element, pos, end);
35365         }
35366         function checkNodePositions(node, aggressiveChecks) {
35367             if (aggressiveChecks) {
35368                 var pos_2 = node.pos;
35369                 var visitNode_1 = function (child) {
35370                     ts.Debug.assert(child.pos >= pos_2);
35371                     pos_2 = child.end;
35372                 };
35373                 if (ts.hasJSDocNodes(node)) {
35374                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
35375                         var jsDocComment = _a[_i];
35376                         visitNode_1(jsDocComment);
35377                     }
35378                 }
35379                 forEachChild(node, visitNode_1);
35380                 ts.Debug.assert(pos_2 <= node.end);
35381             }
35382         }
35383         function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
35384             visitNode(sourceFile);
35385             return;
35386             function visitNode(child) {
35387                 ts.Debug.assert(child.pos <= child.end);
35388                 if (child.pos > changeRangeOldEnd) {
35389                     // Node is entirely past the change range.  We need to move both its pos and
35390                     // end, forward or backward appropriately.
35391                     moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
35392                     return;
35393                 }
35394                 // Check if the element intersects the change range.  If it does, then it is not
35395                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
35396                 // be able to use.
35397                 var fullEnd = child.end;
35398                 if (fullEnd >= changeStart) {
35399                     child.intersectsChange = true;
35400                     child._children = undefined;
35401                     // Adjust the pos or end (or both) of the intersecting element accordingly.
35402                     adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
35403                     forEachChild(child, visitNode, visitArray);
35404                     if (ts.hasJSDocNodes(child)) {
35405                         for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
35406                             var jsDocComment = _a[_i];
35407                             visitNode(jsDocComment);
35408                         }
35409                     }
35410                     checkNodePositions(child, aggressiveChecks);
35411                     return;
35412                 }
35413                 // Otherwise, the node is entirely before the change range.  No need to do anything with it.
35414                 ts.Debug.assert(fullEnd < changeStart);
35415             }
35416             function visitArray(array) {
35417                 ts.Debug.assert(array.pos <= array.end);
35418                 if (array.pos > changeRangeOldEnd) {
35419                     // Array is entirely after the change range.  We need to move it, and move any of
35420                     // its children.
35421                     moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
35422                     return;
35423                 }
35424                 // Check if the element intersects the change range.  If it does, then it is not
35425                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
35426                 // be able to use.
35427                 var fullEnd = array.end;
35428                 if (fullEnd >= changeStart) {
35429                     array.intersectsChange = true;
35430                     array._children = undefined;
35431                     // Adjust the pos or end (or both) of the intersecting array accordingly.
35432                     adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
35433                     for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
35434                         var node = array_9[_i];
35435                         visitNode(node);
35436                     }
35437                     return;
35438                 }
35439                 // Otherwise, the array is entirely before the change range.  No need to do anything with it.
35440                 ts.Debug.assert(fullEnd < changeStart);
35441             }
35442         }
35443         function extendToAffectedRange(sourceFile, changeRange) {
35444             // Consider the following code:
35445             //      void foo() { /; }
35446             //
35447             // If the text changes with an insertion of / just before the semicolon then we end up with:
35448             //      void foo() { //; }
35449             //
35450             // If we were to just use the changeRange a is, then we would not rescan the { token
35451             // (as it does not intersect the actual original change range).  Because an edit may
35452             // change the token touching it, we actually need to look back *at least* one token so
35453             // that the prior token sees that change.
35454             var maxLookahead = 1;
35455             var start = changeRange.span.start;
35456             // the first iteration aligns us with the change start. subsequent iteration move us to
35457             // the left by maxLookahead tokens.  We only need to do this as long as we're not at the
35458             // start of the tree.
35459             for (var i = 0; start > 0 && i <= maxLookahead; i++) {
35460                 var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
35461                 ts.Debug.assert(nearestNode.pos <= start);
35462                 var position = nearestNode.pos;
35463                 start = Math.max(0, position - 1);
35464             }
35465             var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
35466             var finalLength = changeRange.newLength + (changeRange.span.start - start);
35467             return ts.createTextChangeRange(finalSpan, finalLength);
35468         }
35469         function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
35470             var bestResult = sourceFile;
35471             var lastNodeEntirelyBeforePosition;
35472             forEachChild(sourceFile, visit);
35473             if (lastNodeEntirelyBeforePosition) {
35474                 var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
35475                 if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
35476                     bestResult = lastChildOfLastEntireNodeBeforePosition;
35477                 }
35478             }
35479             return bestResult;
35480             function getLastDescendant(node) {
35481                 while (true) {
35482                     var lastChild = ts.getLastChild(node);
35483                     if (lastChild) {
35484                         node = lastChild;
35485                     }
35486                     else {
35487                         return node;
35488                     }
35489                 }
35490             }
35491             function visit(child) {
35492                 if (ts.nodeIsMissing(child)) {
35493                     // Missing nodes are effectively invisible to us.  We never even consider them
35494                     // When trying to find the nearest node before us.
35495                     return;
35496                 }
35497                 // If the child intersects this position, then this node is currently the nearest
35498                 // node that starts before the position.
35499                 if (child.pos <= position) {
35500                     if (child.pos >= bestResult.pos) {
35501                         // This node starts before the position, and is closer to the position than
35502                         // the previous best node we found.  It is now the new best node.
35503                         bestResult = child;
35504                     }
35505                     // Now, the node may overlap the position, or it may end entirely before the
35506                     // position.  If it overlaps with the position, then either it, or one of its
35507                     // children must be the nearest node before the position.  So we can just
35508                     // recurse into this child to see if we can find something better.
35509                     if (position < child.end) {
35510                         // The nearest node is either this child, or one of the children inside
35511                         // of it.  We've already marked this child as the best so far.  Recurse
35512                         // in case one of the children is better.
35513                         forEachChild(child, visit);
35514                         // Once we look at the children of this node, then there's no need to
35515                         // continue any further.
35516                         return true;
35517                     }
35518                     else {
35519                         ts.Debug.assert(child.end <= position);
35520                         // The child ends entirely before this position.  Say you have the following
35521                         // (where $ is the position)
35522                         //
35523                         //      <complex expr 1> ? <complex expr 2> $ : <...> <...>
35524                         //
35525                         // We would want to find the nearest preceding node in "complex expr 2".
35526                         // To support that, we keep track of this node, and once we're done searching
35527                         // for a best node, we recurse down this node to see if we can find a good
35528                         // result in it.
35529                         //
35530                         // This approach allows us to quickly skip over nodes that are entirely
35531                         // before the position, while still allowing us to find any nodes in the
35532                         // last one that might be what we want.
35533                         lastNodeEntirelyBeforePosition = child;
35534                     }
35535                 }
35536                 else {
35537                     ts.Debug.assert(child.pos > position);
35538                     // We're now at a node that is entirely past the position we're searching for.
35539                     // This node (and all following nodes) could never contribute to the result,
35540                     // so just skip them by returning 'true' here.
35541                     return true;
35542                 }
35543             }
35544         }
35545         function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
35546             var oldText = sourceFile.text;
35547             if (textChangeRange) {
35548                 ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
35549                 if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
35550                     var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
35551                     var newTextPrefix = newText.substr(0, textChangeRange.span.start);
35552                     ts.Debug.assert(oldTextPrefix === newTextPrefix);
35553                     var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
35554                     var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
35555                     ts.Debug.assert(oldTextSuffix === newTextSuffix);
35556                 }
35557             }
35558         }
35559         function createSyntaxCursor(sourceFile) {
35560             var currentArray = sourceFile.statements;
35561             var currentArrayIndex = 0;
35562             ts.Debug.assert(currentArrayIndex < currentArray.length);
35563             var current = currentArray[currentArrayIndex];
35564             var lastQueriedPosition = -1 /* Value */;
35565             return {
35566                 currentNode: function (position) {
35567                     // Only compute the current node if the position is different than the last time
35568                     // we were asked.  The parser commonly asks for the node at the same position
35569                     // twice.  Once to know if can read an appropriate list element at a certain point,
35570                     // and then to actually read and consume the node.
35571                     if (position !== lastQueriedPosition) {
35572                         // Much of the time the parser will need the very next node in the array that
35573                         // we just returned a node from.So just simply check for that case and move
35574                         // forward in the array instead of searching for the node again.
35575                         if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
35576                             currentArrayIndex++;
35577                             current = currentArray[currentArrayIndex];
35578                         }
35579                         // If we don't have a node, or the node we have isn't in the right position,
35580                         // then try to find a viable node at the position requested.
35581                         if (!current || current.pos !== position) {
35582                             findHighestListElementThatStartsAtPosition(position);
35583                         }
35584                     }
35585                     // Cache this query so that we don't do any extra work if the parser calls back
35586                     // into us.  Note: this is very common as the parser will make pairs of calls like
35587                     // 'isListElement -> parseListElement'.  If we were unable to find a node when
35588                     // called with 'isListElement', we don't want to redo the work when parseListElement
35589                     // is called immediately after.
35590                     lastQueriedPosition = position;
35591                     // Either we don'd have a node, or we have a node at the position being asked for.
35592                     ts.Debug.assert(!current || current.pos === position);
35593                     return current;
35594                 }
35595             };
35596             // Finds the highest element in the tree we can find that starts at the provided position.
35597             // The element must be a direct child of some node list in the tree.  This way after we
35598             // return it, we can easily return its next sibling in the list.
35599             function findHighestListElementThatStartsAtPosition(position) {
35600                 // Clear out any cached state about the last node we found.
35601                 currentArray = undefined;
35602                 currentArrayIndex = -1 /* Value */;
35603                 current = undefined;
35604                 // Recurse into the source file to find the highest node at this position.
35605                 forEachChild(sourceFile, visitNode, visitArray);
35606                 return;
35607                 function visitNode(node) {
35608                     if (position >= node.pos && position < node.end) {
35609                         // Position was within this node.  Keep searching deeper to find the node.
35610                         forEachChild(node, visitNode, visitArray);
35611                         // don't proceed any further in the search.
35612                         return true;
35613                     }
35614                     // position wasn't in this node, have to keep searching.
35615                     return false;
35616                 }
35617                 function visitArray(array) {
35618                     if (position >= array.pos && position < array.end) {
35619                         // position was in this array.  Search through this array to see if we find a
35620                         // viable element.
35621                         for (var i = 0; i < array.length; i++) {
35622                             var child = array[i];
35623                             if (child) {
35624                                 if (child.pos === position) {
35625                                     // Found the right node.  We're done.
35626                                     currentArray = array;
35627                                     currentArrayIndex = i;
35628                                     current = child;
35629                                     return true;
35630                                 }
35631                                 else {
35632                                     if (child.pos < position && position < child.end) {
35633                                         // Position in somewhere within this child.  Search in it and
35634                                         // stop searching in this array.
35635                                         forEachChild(child, visitNode, visitArray);
35636                                         return true;
35637                                     }
35638                                 }
35639                             }
35640                         }
35641                     }
35642                     // position wasn't in this array, have to keep searching.
35643                     return false;
35644                 }
35645             }
35646         }
35647         IncrementalParser.createSyntaxCursor = createSyntaxCursor;
35648         var InvalidPosition;
35649         (function (InvalidPosition) {
35650             InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
35651         })(InvalidPosition || (InvalidPosition = {}));
35652     })(IncrementalParser || (IncrementalParser = {}));
35653     /** @internal */
35654     function isDeclarationFileName(fileName) {
35655         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
35656     }
35657     ts.isDeclarationFileName = isDeclarationFileName;
35658     /*@internal*/
35659     function processCommentPragmas(context, sourceText) {
35660         var pragmas = [];
35661         for (var _i = 0, _a = ts.getLeadingCommentRanges(sourceText, 0) || ts.emptyArray; _i < _a.length; _i++) {
35662             var range = _a[_i];
35663             var comment = sourceText.substring(range.pos, range.end);
35664             extractPragmas(pragmas, range, comment);
35665         }
35666         context.pragmas = new ts.Map();
35667         for (var _b = 0, pragmas_1 = pragmas; _b < pragmas_1.length; _b++) {
35668             var pragma = pragmas_1[_b];
35669             if (context.pragmas.has(pragma.name)) {
35670                 var currentValue = context.pragmas.get(pragma.name);
35671                 if (currentValue instanceof Array) {
35672                     currentValue.push(pragma.args);
35673                 }
35674                 else {
35675                     context.pragmas.set(pragma.name, [currentValue, pragma.args]);
35676                 }
35677                 continue;
35678             }
35679             context.pragmas.set(pragma.name, pragma.args);
35680         }
35681     }
35682     ts.processCommentPragmas = processCommentPragmas;
35683     /*@internal*/
35684     function processPragmasIntoFields(context, reportDiagnostic) {
35685         context.checkJsDirective = undefined;
35686         context.referencedFiles = [];
35687         context.typeReferenceDirectives = [];
35688         context.libReferenceDirectives = [];
35689         context.amdDependencies = [];
35690         context.hasNoDefaultLib = false;
35691         context.pragmas.forEach(function (entryOrList, key) {
35692             // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
35693             // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
35694             switch (key) {
35695                 case "reference": {
35696                     var referencedFiles_1 = context.referencedFiles;
35697                     var typeReferenceDirectives_1 = context.typeReferenceDirectives;
35698                     var libReferenceDirectives_1 = context.libReferenceDirectives;
35699                     ts.forEach(ts.toArray(entryOrList), function (arg) {
35700                         var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
35701                         if (arg.arguments["no-default-lib"]) {
35702                             context.hasNoDefaultLib = true;
35703                         }
35704                         else if (types) {
35705                             typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
35706                         }
35707                         else if (lib) {
35708                             libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
35709                         }
35710                         else if (path) {
35711                             referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
35712                         }
35713                         else {
35714                             reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
35715                         }
35716                     });
35717                     break;
35718                 }
35719                 case "amd-dependency": {
35720                     context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
35721                     break;
35722                 }
35723                 case "amd-module": {
35724                     if (entryOrList instanceof Array) {
35725                         for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
35726                             var entry = entryOrList_1[_i];
35727                             if (context.moduleName) {
35728                                 // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
35729                                 reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
35730                             }
35731                             context.moduleName = entry.arguments.name;
35732                         }
35733                     }
35734                     else {
35735                         context.moduleName = entryOrList.arguments.name;
35736                     }
35737                     break;
35738                 }
35739                 case "ts-nocheck":
35740                 case "ts-check": {
35741                     // _last_ of either nocheck or check in a file is the "winner"
35742                     ts.forEach(ts.toArray(entryOrList), function (entry) {
35743                         if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
35744                             context.checkJsDirective = {
35745                                 enabled: key === "ts-check",
35746                                 end: entry.range.end,
35747                                 pos: entry.range.pos
35748                             };
35749                         }
35750                     });
35751                     break;
35752                 }
35753                 case "jsx":
35754                 case "jsxfrag":
35755                 case "jsximportsource":
35756                 case "jsxruntime":
35757                     return; // Accessed directly
35758                 default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
35759             }
35760         });
35761     }
35762     ts.processPragmasIntoFields = processPragmasIntoFields;
35763     var namedArgRegExCache = new ts.Map();
35764     function getNamedArgRegEx(name) {
35765         if (namedArgRegExCache.has(name)) {
35766             return namedArgRegExCache.get(name);
35767         }
35768         var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
35769         namedArgRegExCache.set(name, result);
35770         return result;
35771     }
35772     var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
35773     var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
35774     function extractPragmas(pragmas, range, text) {
35775         var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
35776         if (tripleSlash) {
35777             var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
35778             var pragma = ts.commentPragmas[name];
35779             if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
35780                 return;
35781             }
35782             if (pragma.args) {
35783                 var argument = {};
35784                 for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
35785                     var arg = _a[_i];
35786                     var matcher = getNamedArgRegEx(arg.name);
35787                     var matchResult = matcher.exec(text);
35788                     if (!matchResult && !arg.optional) {
35789                         return; // Missing required argument, don't parse
35790                     }
35791                     else if (matchResult) {
35792                         if (arg.captureSpan) {
35793                             var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
35794                             argument[arg.name] = {
35795                                 value: matchResult[3],
35796                                 pos: startPos,
35797                                 end: startPos + matchResult[3].length
35798                             };
35799                         }
35800                         else {
35801                             argument[arg.name] = matchResult[3];
35802                         }
35803                     }
35804                 }
35805                 pragmas.push({ name: name, args: { arguments: argument, range: range } });
35806             }
35807             else {
35808                 pragmas.push({ name: name, args: { arguments: {}, range: range } });
35809             }
35810             return;
35811         }
35812         var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
35813         if (singleLine) {
35814             return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
35815         }
35816         if (range.kind === 3 /* MultiLineCommentTrivia */) {
35817             var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
35818             var multiLineMatch = void 0;
35819             while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
35820                 addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
35821             }
35822         }
35823     }
35824     function addPragmaForMatch(pragmas, range, kind, match) {
35825         if (!match)
35826             return;
35827         var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
35828         var pragma = ts.commentPragmas[name];
35829         if (!pragma || !(pragma.kind & kind)) {
35830             return;
35831         }
35832         var args = match[2]; // Split on spaces and match up positionally with definition
35833         var argument = getNamedPragmaArguments(pragma, args);
35834         if (argument === "fail")
35835             return; // Missing required argument, fail to parse it
35836         pragmas.push({ name: name, args: { arguments: argument, range: range } });
35837         return;
35838     }
35839     function getNamedPragmaArguments(pragma, text) {
35840         if (!text)
35841             return {};
35842         if (!pragma.args)
35843             return {};
35844         var args = text.split(/\s+/);
35845         var argMap = {};
35846         for (var i = 0; i < pragma.args.length; i++) {
35847             var argument = pragma.args[i];
35848             if (!args[i] && !argument.optional) {
35849                 return "fail";
35850             }
35851             if (argument.captureSpan) {
35852                 return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
35853             }
35854             argMap[argument.name] = args[i];
35855         }
35856         return argMap;
35857     }
35858     /** @internal */
35859     function tagNamesAreEquivalent(lhs, rhs) {
35860         if (lhs.kind !== rhs.kind) {
35861             return false;
35862         }
35863         if (lhs.kind === 78 /* Identifier */) {
35864             return lhs.escapedText === rhs.escapedText;
35865         }
35866         if (lhs.kind === 107 /* ThisKeyword */) {
35867             return true;
35868         }
35869         // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
35870         // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
35871         // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
35872         return lhs.name.escapedText === rhs.name.escapedText &&
35873             tagNamesAreEquivalent(lhs.expression, rhs.expression);
35874     }
35875     ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
35876 })(ts || (ts = {}));
35877 var ts;
35878 (function (ts) {
35879     /* @internal */
35880     ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
35881     var jsxOptionMap = new ts.Map(ts.getEntries({
35882         "preserve": 1 /* Preserve */,
35883         "react-native": 3 /* ReactNative */,
35884         "react": 2 /* React */,
35885         "react-jsx": 4 /* ReactJSX */,
35886         "react-jsxdev": 5 /* ReactJSXDev */,
35887     }));
35888     /* @internal */
35889     ts.inverseJsxOptionMap = new ts.Map(ts.arrayFrom(ts.mapIterator(jsxOptionMap.entries(), function (_a) {
35890         var key = _a[0], value = _a[1];
35891         return ["" + value, key];
35892     })));
35893     // NOTE: The order here is important to default lib ordering as entries will have the same
35894     //       order in the generated program (see `getDefaultLibPriority` in program.ts). This
35895     //       order also affects overload resolution when a type declared in one lib is
35896     //       augmented in another lib.
35897     var libEntries = [
35898         // JavaScript only
35899         ["es5", "lib.es5.d.ts"],
35900         ["es6", "lib.es2015.d.ts"],
35901         ["es2015", "lib.es2015.d.ts"],
35902         ["es7", "lib.es2016.d.ts"],
35903         ["es2016", "lib.es2016.d.ts"],
35904         ["es2017", "lib.es2017.d.ts"],
35905         ["es2018", "lib.es2018.d.ts"],
35906         ["es2019", "lib.es2019.d.ts"],
35907         ["es2020", "lib.es2020.d.ts"],
35908         ["esnext", "lib.esnext.d.ts"],
35909         // Host only
35910         ["dom", "lib.dom.d.ts"],
35911         ["dom.iterable", "lib.dom.iterable.d.ts"],
35912         ["webworker", "lib.webworker.d.ts"],
35913         ["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
35914         ["webworker.iterable", "lib.webworker.iterable.d.ts"],
35915         ["scripthost", "lib.scripthost.d.ts"],
35916         // ES2015 Or ESNext By-feature options
35917         ["es2015.core", "lib.es2015.core.d.ts"],
35918         ["es2015.collection", "lib.es2015.collection.d.ts"],
35919         ["es2015.generator", "lib.es2015.generator.d.ts"],
35920         ["es2015.iterable", "lib.es2015.iterable.d.ts"],
35921         ["es2015.promise", "lib.es2015.promise.d.ts"],
35922         ["es2015.proxy", "lib.es2015.proxy.d.ts"],
35923         ["es2015.reflect", "lib.es2015.reflect.d.ts"],
35924         ["es2015.symbol", "lib.es2015.symbol.d.ts"],
35925         ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
35926         ["es2016.array.include", "lib.es2016.array.include.d.ts"],
35927         ["es2017.object", "lib.es2017.object.d.ts"],
35928         ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
35929         ["es2017.string", "lib.es2017.string.d.ts"],
35930         ["es2017.intl", "lib.es2017.intl.d.ts"],
35931         ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
35932         ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
35933         ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
35934         ["es2018.intl", "lib.es2018.intl.d.ts"],
35935         ["es2018.promise", "lib.es2018.promise.d.ts"],
35936         ["es2018.regexp", "lib.es2018.regexp.d.ts"],
35937         ["es2019.array", "lib.es2019.array.d.ts"],
35938         ["es2019.object", "lib.es2019.object.d.ts"],
35939         ["es2019.string", "lib.es2019.string.d.ts"],
35940         ["es2019.symbol", "lib.es2019.symbol.d.ts"],
35941         ["es2020.bigint", "lib.es2020.bigint.d.ts"],
35942         ["es2020.promise", "lib.es2020.promise.d.ts"],
35943         ["es2020.sharedmemory", "lib.es2020.sharedmemory.d.ts"],
35944         ["es2020.string", "lib.es2020.string.d.ts"],
35945         ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
35946         ["es2020.intl", "lib.es2020.intl.d.ts"],
35947         ["esnext.array", "lib.es2019.array.d.ts"],
35948         ["esnext.symbol", "lib.es2019.symbol.d.ts"],
35949         ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
35950         ["esnext.intl", "lib.esnext.intl.d.ts"],
35951         ["esnext.bigint", "lib.es2020.bigint.d.ts"],
35952         ["esnext.string", "lib.esnext.string.d.ts"],
35953         ["esnext.promise", "lib.esnext.promise.d.ts"],
35954         ["esnext.weakref", "lib.esnext.weakref.d.ts"]
35955     ];
35956     /**
35957      * An array of supported "lib" reference file names used to determine the order for inclusion
35958      * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
35959      * overload resolution when a type declared in one lib is extended by another.
35960      */
35961     /* @internal */
35962     ts.libs = libEntries.map(function (entry) { return entry[0]; });
35963     /**
35964      * A map of lib names to lib files. This map is used both for parsing the "lib" command line
35965      * option as well as for resolving lib reference directives.
35966      */
35967     /* @internal */
35968     ts.libMap = new ts.Map(libEntries);
35969     // Watch related options
35970     /* @internal */
35971     ts.optionsForWatch = [
35972         {
35973             name: "watchFile",
35974             type: new ts.Map(ts.getEntries({
35975                 fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval,
35976                 prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval,
35977                 dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling,
35978                 usefsevents: ts.WatchFileKind.UseFsEvents,
35979                 usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory,
35980             })),
35981             category: ts.Diagnostics.Advanced_Options,
35982             description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory,
35983         },
35984         {
35985             name: "watchDirectory",
35986             type: new ts.Map(ts.getEntries({
35987                 usefsevents: ts.WatchDirectoryKind.UseFsEvents,
35988                 fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval,
35989                 dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling,
35990             })),
35991             category: ts.Diagnostics.Advanced_Options,
35992             description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling,
35993         },
35994         {
35995             name: "fallbackPolling",
35996             type: new ts.Map(ts.getEntries({
35997                 fixedinterval: ts.PollingWatchKind.FixedInterval,
35998                 priorityinterval: ts.PollingWatchKind.PriorityInterval,
35999                 dynamicpriority: ts.PollingWatchKind.DynamicPriority,
36000             })),
36001             category: ts.Diagnostics.Advanced_Options,
36002             description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority,
36003         },
36004         {
36005             name: "synchronousWatchDirectory",
36006             type: "boolean",
36007             category: ts.Diagnostics.Advanced_Options,
36008             description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
36009         },
36010         {
36011             name: "excludeDirectories",
36012             type: "list",
36013             element: {
36014                 name: "excludeDirectory",
36015                 type: "string",
36016                 isFilePath: true,
36017                 extraValidation: specToDiagnostic
36018             },
36019             category: ts.Diagnostics.Advanced_Options,
36020             description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
36021         },
36022         {
36023             name: "excludeFiles",
36024             type: "list",
36025             element: {
36026                 name: "excludeFile",
36027                 type: "string",
36028                 isFilePath: true,
36029                 extraValidation: specToDiagnostic
36030             },
36031             category: ts.Diagnostics.Advanced_Options,
36032             description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
36033         },
36034     ];
36035     /* @internal */
36036     ts.commonOptionsWithBuild = [
36037         {
36038             name: "help",
36039             shortName: "h",
36040             type: "boolean",
36041             showInSimplifiedHelpView: true,
36042             category: ts.Diagnostics.Command_line_Options,
36043             description: ts.Diagnostics.Print_this_message,
36044         },
36045         {
36046             name: "help",
36047             shortName: "?",
36048             type: "boolean"
36049         },
36050         {
36051             name: "watch",
36052             shortName: "w",
36053             type: "boolean",
36054             showInSimplifiedHelpView: true,
36055             category: ts.Diagnostics.Command_line_Options,
36056             description: ts.Diagnostics.Watch_input_files,
36057         },
36058         {
36059             name: "preserveWatchOutput",
36060             type: "boolean",
36061             showInSimplifiedHelpView: false,
36062             category: ts.Diagnostics.Command_line_Options,
36063             description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
36064         },
36065         {
36066             name: "listFiles",
36067             type: "boolean",
36068             category: ts.Diagnostics.Advanced_Options,
36069             description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
36070         },
36071         {
36072             name: "explainFiles",
36073             type: "boolean",
36074             category: ts.Diagnostics.Advanced_Options,
36075             description: ts.Diagnostics.Print_names_of_files_and_the_reason_they_are_part_of_the_compilation
36076         }, {
36077             name: "listEmittedFiles",
36078             type: "boolean",
36079             category: ts.Diagnostics.Advanced_Options,
36080             description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
36081         },
36082         {
36083             name: "pretty",
36084             type: "boolean",
36085             showInSimplifiedHelpView: true,
36086             category: ts.Diagnostics.Command_line_Options,
36087             description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
36088         },
36089         {
36090             name: "traceResolution",
36091             type: "boolean",
36092             category: ts.Diagnostics.Advanced_Options,
36093             description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
36094         },
36095         {
36096             name: "diagnostics",
36097             type: "boolean",
36098             category: ts.Diagnostics.Advanced_Options,
36099             description: ts.Diagnostics.Show_diagnostic_information
36100         },
36101         {
36102             name: "extendedDiagnostics",
36103             type: "boolean",
36104             category: ts.Diagnostics.Advanced_Options,
36105             description: ts.Diagnostics.Show_verbose_diagnostic_information
36106         },
36107         {
36108             name: "generateCpuProfile",
36109             type: "string",
36110             isFilePath: true,
36111             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
36112             category: ts.Diagnostics.Advanced_Options,
36113             description: ts.Diagnostics.Generates_a_CPU_profile
36114         },
36115         {
36116             name: "generateTrace",
36117             type: "string",
36118             isFilePath: true,
36119             isCommandLineOnly: true,
36120             paramType: ts.Diagnostics.DIRECTORY,
36121             category: ts.Diagnostics.Advanced_Options,
36122             description: ts.Diagnostics.Generates_an_event_trace_and_a_list_of_types
36123         },
36124         {
36125             name: "incremental",
36126             shortName: "i",
36127             type: "boolean",
36128             category: ts.Diagnostics.Basic_Options,
36129             description: ts.Diagnostics.Enable_incremental_compilation,
36130             transpileOptionValue: undefined
36131         },
36132         {
36133             name: "assumeChangesOnlyAffectDirectDependencies",
36134             type: "boolean",
36135             affectsSemanticDiagnostics: true,
36136             affectsEmit: true,
36137             category: ts.Diagnostics.Advanced_Options,
36138             description: ts.Diagnostics.Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it
36139         },
36140         {
36141             name: "locale",
36142             type: "string",
36143             category: ts.Diagnostics.Advanced_Options,
36144             description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
36145         },
36146     ];
36147     /* @internal */
36148     ts.targetOptionDeclaration = {
36149         name: "target",
36150         shortName: "t",
36151         type: new ts.Map(ts.getEntries({
36152             es3: 0 /* ES3 */,
36153             es5: 1 /* ES5 */,
36154             es6: 2 /* ES2015 */,
36155             es2015: 2 /* ES2015 */,
36156             es2016: 3 /* ES2016 */,
36157             es2017: 4 /* ES2017 */,
36158             es2018: 5 /* ES2018 */,
36159             es2019: 6 /* ES2019 */,
36160             es2020: 7 /* ES2020 */,
36161             esnext: 99 /* ESNext */,
36162         })),
36163         affectsSourceFile: true,
36164         affectsModuleResolution: true,
36165         affectsEmit: true,
36166         paramType: ts.Diagnostics.VERSION,
36167         showInSimplifiedHelpView: true,
36168         category: ts.Diagnostics.Basic_Options,
36169         description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT,
36170     };
36171     /* @internal */
36172     ts.optionDeclarations = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [
36173         {
36174             name: "all",
36175             type: "boolean",
36176             showInSimplifiedHelpView: true,
36177             category: ts.Diagnostics.Command_line_Options,
36178             description: ts.Diagnostics.Show_all_compiler_options,
36179         },
36180         {
36181             name: "version",
36182             shortName: "v",
36183             type: "boolean",
36184             showInSimplifiedHelpView: true,
36185             category: ts.Diagnostics.Command_line_Options,
36186             description: ts.Diagnostics.Print_the_compiler_s_version,
36187         },
36188         {
36189             name: "init",
36190             type: "boolean",
36191             showInSimplifiedHelpView: true,
36192             category: ts.Diagnostics.Command_line_Options,
36193             description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
36194         },
36195         {
36196             name: "project",
36197             shortName: "p",
36198             type: "string",
36199             isFilePath: true,
36200             showInSimplifiedHelpView: true,
36201             category: ts.Diagnostics.Command_line_Options,
36202             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
36203             description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
36204         },
36205         {
36206             name: "build",
36207             type: "boolean",
36208             shortName: "b",
36209             showInSimplifiedHelpView: true,
36210             category: ts.Diagnostics.Command_line_Options,
36211             description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
36212         },
36213         {
36214             name: "showConfig",
36215             type: "boolean",
36216             category: ts.Diagnostics.Command_line_Options,
36217             isCommandLineOnly: true,
36218             description: ts.Diagnostics.Print_the_final_configuration_instead_of_building
36219         },
36220         {
36221             name: "listFilesOnly",
36222             type: "boolean",
36223             category: ts.Diagnostics.Command_line_Options,
36224             affectsSemanticDiagnostics: true,
36225             affectsEmit: true,
36226             isCommandLineOnly: true,
36227             description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
36228         },
36229         // Basic
36230         ts.targetOptionDeclaration,
36231         {
36232             name: "module",
36233             shortName: "m",
36234             type: new ts.Map(ts.getEntries({
36235                 none: ts.ModuleKind.None,
36236                 commonjs: ts.ModuleKind.CommonJS,
36237                 amd: ts.ModuleKind.AMD,
36238                 system: ts.ModuleKind.System,
36239                 umd: ts.ModuleKind.UMD,
36240                 es6: ts.ModuleKind.ES2015,
36241                 es2015: ts.ModuleKind.ES2015,
36242                 es2020: ts.ModuleKind.ES2020,
36243                 esnext: ts.ModuleKind.ESNext
36244             })),
36245             affectsModuleResolution: true,
36246             affectsEmit: true,
36247             paramType: ts.Diagnostics.KIND,
36248             showInSimplifiedHelpView: true,
36249             category: ts.Diagnostics.Basic_Options,
36250             description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext,
36251         },
36252         {
36253             name: "lib",
36254             type: "list",
36255             element: {
36256                 name: "lib",
36257                 type: ts.libMap
36258             },
36259             affectsModuleResolution: true,
36260             showInSimplifiedHelpView: true,
36261             category: ts.Diagnostics.Basic_Options,
36262             description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation,
36263             transpileOptionValue: undefined
36264         },
36265         {
36266             name: "allowJs",
36267             type: "boolean",
36268             affectsModuleResolution: true,
36269             showInSimplifiedHelpView: true,
36270             category: ts.Diagnostics.Basic_Options,
36271             description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
36272         },
36273         {
36274             name: "checkJs",
36275             type: "boolean",
36276             category: ts.Diagnostics.Basic_Options,
36277             description: ts.Diagnostics.Report_errors_in_js_files
36278         },
36279         {
36280             name: "jsx",
36281             type: jsxOptionMap,
36282             affectsSourceFile: true,
36283             affectsEmit: true,
36284             affectsModuleResolution: true,
36285             paramType: ts.Diagnostics.KIND,
36286             showInSimplifiedHelpView: true,
36287             category: ts.Diagnostics.Basic_Options,
36288             description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_react_react_jsx_or_react_jsxdev,
36289         },
36290         {
36291             name: "declaration",
36292             shortName: "d",
36293             type: "boolean",
36294             affectsEmit: true,
36295             showInSimplifiedHelpView: true,
36296             category: ts.Diagnostics.Basic_Options,
36297             description: ts.Diagnostics.Generates_corresponding_d_ts_file,
36298             transpileOptionValue: undefined
36299         },
36300         {
36301             name: "declarationMap",
36302             type: "boolean",
36303             affectsEmit: true,
36304             showInSimplifiedHelpView: true,
36305             category: ts.Diagnostics.Basic_Options,
36306             description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file,
36307             transpileOptionValue: undefined
36308         },
36309         {
36310             name: "emitDeclarationOnly",
36311             type: "boolean",
36312             affectsEmit: true,
36313             category: ts.Diagnostics.Advanced_Options,
36314             description: ts.Diagnostics.Only_emit_d_ts_declaration_files,
36315             transpileOptionValue: undefined
36316         },
36317         {
36318             name: "sourceMap",
36319             type: "boolean",
36320             affectsEmit: true,
36321             showInSimplifiedHelpView: true,
36322             category: ts.Diagnostics.Basic_Options,
36323             description: ts.Diagnostics.Generates_corresponding_map_file,
36324         },
36325         {
36326             name: "outFile",
36327             type: "string",
36328             affectsEmit: true,
36329             isFilePath: true,
36330             paramType: ts.Diagnostics.FILE,
36331             showInSimplifiedHelpView: true,
36332             category: ts.Diagnostics.Basic_Options,
36333             description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
36334             transpileOptionValue: undefined
36335         },
36336         {
36337             name: "outDir",
36338             type: "string",
36339             affectsEmit: true,
36340             isFilePath: true,
36341             paramType: ts.Diagnostics.DIRECTORY,
36342             showInSimplifiedHelpView: true,
36343             category: ts.Diagnostics.Basic_Options,
36344             description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
36345         },
36346         {
36347             name: "rootDir",
36348             type: "string",
36349             affectsEmit: true,
36350             isFilePath: true,
36351             paramType: ts.Diagnostics.LOCATION,
36352             category: ts.Diagnostics.Basic_Options,
36353             description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
36354         },
36355         {
36356             name: "composite",
36357             type: "boolean",
36358             affectsEmit: true,
36359             isTSConfigOnly: true,
36360             category: ts.Diagnostics.Basic_Options,
36361             description: ts.Diagnostics.Enable_project_compilation,
36362             transpileOptionValue: undefined
36363         },
36364         {
36365             name: "tsBuildInfoFile",
36366             type: "string",
36367             affectsEmit: true,
36368             isFilePath: true,
36369             paramType: ts.Diagnostics.FILE,
36370             category: ts.Diagnostics.Basic_Options,
36371             description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
36372             transpileOptionValue: undefined
36373         },
36374         {
36375             name: "removeComments",
36376             type: "boolean",
36377             affectsEmit: true,
36378             showInSimplifiedHelpView: true,
36379             category: ts.Diagnostics.Basic_Options,
36380             description: ts.Diagnostics.Do_not_emit_comments_to_output,
36381         },
36382         {
36383             name: "noEmit",
36384             type: "boolean",
36385             showInSimplifiedHelpView: true,
36386             category: ts.Diagnostics.Basic_Options,
36387             description: ts.Diagnostics.Do_not_emit_outputs,
36388             transpileOptionValue: undefined
36389         },
36390         {
36391             name: "importHelpers",
36392             type: "boolean",
36393             affectsEmit: true,
36394             category: ts.Diagnostics.Basic_Options,
36395             description: ts.Diagnostics.Import_emit_helpers_from_tslib
36396         },
36397         {
36398             name: "importsNotUsedAsValues",
36399             type: new ts.Map(ts.getEntries({
36400                 remove: 0 /* Remove */,
36401                 preserve: 1 /* Preserve */,
36402                 error: 2 /* Error */
36403             })),
36404             affectsEmit: true,
36405             affectsSemanticDiagnostics: true,
36406             category: ts.Diagnostics.Advanced_Options,
36407             description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
36408         },
36409         {
36410             name: "downlevelIteration",
36411             type: "boolean",
36412             affectsEmit: true,
36413             category: ts.Diagnostics.Basic_Options,
36414             description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
36415         },
36416         {
36417             name: "isolatedModules",
36418             type: "boolean",
36419             category: ts.Diagnostics.Basic_Options,
36420             description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule,
36421             transpileOptionValue: true
36422         },
36423         // Strict Type Checks
36424         {
36425             name: "strict",
36426             type: "boolean",
36427             showInSimplifiedHelpView: true,
36428             category: ts.Diagnostics.Strict_Type_Checking_Options,
36429             description: ts.Diagnostics.Enable_all_strict_type_checking_options
36430         },
36431         {
36432             name: "noImplicitAny",
36433             type: "boolean",
36434             affectsSemanticDiagnostics: true,
36435             strictFlag: true,
36436             showInSimplifiedHelpView: true,
36437             category: ts.Diagnostics.Strict_Type_Checking_Options,
36438             description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type
36439         },
36440         {
36441             name: "strictNullChecks",
36442             type: "boolean",
36443             affectsSemanticDiagnostics: true,
36444             strictFlag: true,
36445             showInSimplifiedHelpView: true,
36446             category: ts.Diagnostics.Strict_Type_Checking_Options,
36447             description: ts.Diagnostics.Enable_strict_null_checks
36448         },
36449         {
36450             name: "strictFunctionTypes",
36451             type: "boolean",
36452             affectsSemanticDiagnostics: true,
36453             strictFlag: true,
36454             showInSimplifiedHelpView: true,
36455             category: ts.Diagnostics.Strict_Type_Checking_Options,
36456             description: ts.Diagnostics.Enable_strict_checking_of_function_types
36457         },
36458         {
36459             name: "strictBindCallApply",
36460             type: "boolean",
36461             strictFlag: true,
36462             showInSimplifiedHelpView: true,
36463             category: ts.Diagnostics.Strict_Type_Checking_Options,
36464             description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions
36465         },
36466         {
36467             name: "strictPropertyInitialization",
36468             type: "boolean",
36469             affectsSemanticDiagnostics: true,
36470             strictFlag: true,
36471             showInSimplifiedHelpView: true,
36472             category: ts.Diagnostics.Strict_Type_Checking_Options,
36473             description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
36474         },
36475         {
36476             name: "noImplicitThis",
36477             type: "boolean",
36478             affectsSemanticDiagnostics: true,
36479             strictFlag: true,
36480             showInSimplifiedHelpView: true,
36481             category: ts.Diagnostics.Strict_Type_Checking_Options,
36482             description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
36483         },
36484         {
36485             name: "alwaysStrict",
36486             type: "boolean",
36487             affectsSourceFile: true,
36488             strictFlag: true,
36489             showInSimplifiedHelpView: true,
36490             category: ts.Diagnostics.Strict_Type_Checking_Options,
36491             description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
36492         },
36493         // Additional Checks
36494         {
36495             name: "noUnusedLocals",
36496             type: "boolean",
36497             affectsSemanticDiagnostics: true,
36498             showInSimplifiedHelpView: true,
36499             category: ts.Diagnostics.Additional_Checks,
36500             description: ts.Diagnostics.Report_errors_on_unused_locals,
36501         },
36502         {
36503             name: "noUnusedParameters",
36504             type: "boolean",
36505             affectsSemanticDiagnostics: true,
36506             showInSimplifiedHelpView: true,
36507             category: ts.Diagnostics.Additional_Checks,
36508             description: ts.Diagnostics.Report_errors_on_unused_parameters,
36509         },
36510         {
36511             name: "noImplicitReturns",
36512             type: "boolean",
36513             affectsSemanticDiagnostics: true,
36514             showInSimplifiedHelpView: true,
36515             category: ts.Diagnostics.Additional_Checks,
36516             description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
36517         },
36518         {
36519             name: "noFallthroughCasesInSwitch",
36520             type: "boolean",
36521             affectsBindDiagnostics: true,
36522             affectsSemanticDiagnostics: true,
36523             showInSimplifiedHelpView: true,
36524             category: ts.Diagnostics.Additional_Checks,
36525             description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
36526         },
36527         {
36528             name: "noUncheckedIndexedAccess",
36529             type: "boolean",
36530             affectsSemanticDiagnostics: true,
36531             showInSimplifiedHelpView: false,
36532             category: ts.Diagnostics.Additional_Checks,
36533             description: ts.Diagnostics.Include_undefined_in_index_signature_results
36534         },
36535         {
36536             name: "noPropertyAccessFromIndexSignature",
36537             type: "boolean",
36538             showInSimplifiedHelpView: false,
36539             category: ts.Diagnostics.Additional_Checks,
36540             description: ts.Diagnostics.Require_undeclared_properties_from_index_signatures_to_use_element_accesses
36541         },
36542         // Module Resolution
36543         {
36544             name: "moduleResolution",
36545             type: new ts.Map(ts.getEntries({
36546                 node: ts.ModuleResolutionKind.NodeJs,
36547                 classic: ts.ModuleResolutionKind.Classic,
36548             })),
36549             affectsModuleResolution: true,
36550             paramType: ts.Diagnostics.STRATEGY,
36551             category: ts.Diagnostics.Module_Resolution_Options,
36552             description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
36553         },
36554         {
36555             name: "baseUrl",
36556             type: "string",
36557             affectsModuleResolution: true,
36558             isFilePath: true,
36559             category: ts.Diagnostics.Module_Resolution_Options,
36560             description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
36561         },
36562         {
36563             // this option can only be specified in tsconfig.json
36564             // use type = object to copy the value as-is
36565             name: "paths",
36566             type: "object",
36567             affectsModuleResolution: true,
36568             isTSConfigOnly: true,
36569             category: ts.Diagnostics.Module_Resolution_Options,
36570             description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl,
36571             transpileOptionValue: undefined
36572         },
36573         {
36574             // this option can only be specified in tsconfig.json
36575             // use type = object to copy the value as-is
36576             name: "rootDirs",
36577             type: "list",
36578             isTSConfigOnly: true,
36579             element: {
36580                 name: "rootDirs",
36581                 type: "string",
36582                 isFilePath: true
36583             },
36584             affectsModuleResolution: true,
36585             category: ts.Diagnostics.Module_Resolution_Options,
36586             description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime,
36587             transpileOptionValue: undefined
36588         },
36589         {
36590             name: "typeRoots",
36591             type: "list",
36592             element: {
36593                 name: "typeRoots",
36594                 type: "string",
36595                 isFilePath: true
36596             },
36597             affectsModuleResolution: true,
36598             category: ts.Diagnostics.Module_Resolution_Options,
36599             description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
36600         },
36601         {
36602             name: "types",
36603             type: "list",
36604             element: {
36605                 name: "types",
36606                 type: "string"
36607             },
36608             affectsModuleResolution: true,
36609             showInSimplifiedHelpView: true,
36610             category: ts.Diagnostics.Module_Resolution_Options,
36611             description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation,
36612             transpileOptionValue: undefined
36613         },
36614         {
36615             name: "allowSyntheticDefaultImports",
36616             type: "boolean",
36617             affectsSemanticDiagnostics: true,
36618             category: ts.Diagnostics.Module_Resolution_Options,
36619             description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
36620         },
36621         {
36622             name: "esModuleInterop",
36623             type: "boolean",
36624             affectsSemanticDiagnostics: true,
36625             affectsEmit: true,
36626             showInSimplifiedHelpView: true,
36627             category: ts.Diagnostics.Module_Resolution_Options,
36628             description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports
36629         },
36630         {
36631             name: "preserveSymlinks",
36632             type: "boolean",
36633             category: ts.Diagnostics.Module_Resolution_Options,
36634             description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
36635         },
36636         {
36637             name: "allowUmdGlobalAccess",
36638             type: "boolean",
36639             affectsSemanticDiagnostics: true,
36640             category: ts.Diagnostics.Module_Resolution_Options,
36641             description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules,
36642         },
36643         // Source Maps
36644         {
36645             name: "sourceRoot",
36646             type: "string",
36647             affectsEmit: true,
36648             paramType: ts.Diagnostics.LOCATION,
36649             category: ts.Diagnostics.Source_Map_Options,
36650             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
36651         },
36652         {
36653             name: "mapRoot",
36654             type: "string",
36655             affectsEmit: true,
36656             paramType: ts.Diagnostics.LOCATION,
36657             category: ts.Diagnostics.Source_Map_Options,
36658             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
36659         },
36660         {
36661             name: "inlineSourceMap",
36662             type: "boolean",
36663             affectsEmit: true,
36664             category: ts.Diagnostics.Source_Map_Options,
36665             description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
36666         },
36667         {
36668             name: "inlineSources",
36669             type: "boolean",
36670             affectsEmit: true,
36671             category: ts.Diagnostics.Source_Map_Options,
36672             description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
36673         },
36674         // Experimental
36675         {
36676             name: "experimentalDecorators",
36677             type: "boolean",
36678             affectsSemanticDiagnostics: true,
36679             category: ts.Diagnostics.Experimental_Options,
36680             description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
36681         },
36682         {
36683             name: "emitDecoratorMetadata",
36684             type: "boolean",
36685             affectsSemanticDiagnostics: true,
36686             affectsEmit: true,
36687             category: ts.Diagnostics.Experimental_Options,
36688             description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
36689         },
36690         // Advanced
36691         {
36692             name: "jsxFactory",
36693             type: "string",
36694             category: ts.Diagnostics.Advanced_Options,
36695             description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
36696         },
36697         {
36698             name: "jsxFragmentFactory",
36699             type: "string",
36700             category: ts.Diagnostics.Advanced_Options,
36701             description: ts.Diagnostics.Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compiler_option_is_specified_e_g_Fragment
36702         },
36703         {
36704             name: "jsxImportSource",
36705             type: "string",
36706             affectsSemanticDiagnostics: true,
36707             affectsEmit: true,
36708             affectsModuleResolution: true,
36709             category: ts.Diagnostics.Advanced_Options,
36710             description: ts.Diagnostics.Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react
36711         },
36712         {
36713             name: "resolveJsonModule",
36714             type: "boolean",
36715             affectsModuleResolution: true,
36716             category: ts.Diagnostics.Advanced_Options,
36717             description: ts.Diagnostics.Include_modules_imported_with_json_extension
36718         },
36719         {
36720             name: "out",
36721             type: "string",
36722             affectsEmit: true,
36723             isFilePath: false,
36724             // for correct behaviour, please use outFile
36725             category: ts.Diagnostics.Advanced_Options,
36726             paramType: ts.Diagnostics.FILE,
36727             description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
36728             transpileOptionValue: undefined
36729         },
36730         {
36731             name: "reactNamespace",
36732             type: "string",
36733             affectsEmit: true,
36734             category: ts.Diagnostics.Advanced_Options,
36735             description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
36736         },
36737         {
36738             name: "skipDefaultLibCheck",
36739             type: "boolean",
36740             category: ts.Diagnostics.Advanced_Options,
36741             description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
36742         },
36743         {
36744             name: "charset",
36745             type: "string",
36746             category: ts.Diagnostics.Advanced_Options,
36747             description: ts.Diagnostics.The_character_set_of_the_input_files
36748         },
36749         {
36750             name: "emitBOM",
36751             type: "boolean",
36752             affectsEmit: true,
36753             category: ts.Diagnostics.Advanced_Options,
36754             description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
36755         },
36756         {
36757             name: "newLine",
36758             type: new ts.Map(ts.getEntries({
36759                 crlf: 0 /* CarriageReturnLineFeed */,
36760                 lf: 1 /* LineFeed */
36761             })),
36762             affectsEmit: true,
36763             paramType: ts.Diagnostics.NEWLINE,
36764             category: ts.Diagnostics.Advanced_Options,
36765             description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
36766         },
36767         {
36768             name: "noErrorTruncation",
36769             type: "boolean",
36770             affectsSemanticDiagnostics: true,
36771             category: ts.Diagnostics.Advanced_Options,
36772             description: ts.Diagnostics.Do_not_truncate_error_messages
36773         },
36774         {
36775             name: "noLib",
36776             type: "boolean",
36777             affectsModuleResolution: true,
36778             category: ts.Diagnostics.Advanced_Options,
36779             description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts,
36780             // We are not returning a sourceFile for lib file when asked by the program,
36781             // so pass --noLib to avoid reporting a file not found error.
36782             transpileOptionValue: true
36783         },
36784         {
36785             name: "noResolve",
36786             type: "boolean",
36787             affectsModuleResolution: true,
36788             category: ts.Diagnostics.Advanced_Options,
36789             description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files,
36790             // We are not doing a full typecheck, we are not resolving the whole context,
36791             // so pass --noResolve to avoid reporting missing file errors.
36792             transpileOptionValue: true
36793         },
36794         {
36795             name: "stripInternal",
36796             type: "boolean",
36797             affectsEmit: true,
36798             category: ts.Diagnostics.Advanced_Options,
36799             description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
36800         },
36801         {
36802             name: "disableSizeLimit",
36803             type: "boolean",
36804             affectsSourceFile: true,
36805             category: ts.Diagnostics.Advanced_Options,
36806             description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
36807         },
36808         {
36809             name: "disableSourceOfProjectReferenceRedirect",
36810             type: "boolean",
36811             isTSConfigOnly: true,
36812             category: ts.Diagnostics.Advanced_Options,
36813             description: ts.Diagnostics.Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects
36814         },
36815         {
36816             name: "disableSolutionSearching",
36817             type: "boolean",
36818             isTSConfigOnly: true,
36819             category: ts.Diagnostics.Advanced_Options,
36820             description: ts.Diagnostics.Disable_solution_searching_for_this_project
36821         },
36822         {
36823             name: "disableReferencedProjectLoad",
36824             type: "boolean",
36825             isTSConfigOnly: true,
36826             category: ts.Diagnostics.Advanced_Options,
36827             description: ts.Diagnostics.Disable_loading_referenced_projects
36828         },
36829         {
36830             name: "noImplicitUseStrict",
36831             type: "boolean",
36832             affectsSemanticDiagnostics: true,
36833             category: ts.Diagnostics.Advanced_Options,
36834             description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
36835         },
36836         {
36837             name: "noEmitHelpers",
36838             type: "boolean",
36839             affectsEmit: true,
36840             category: ts.Diagnostics.Advanced_Options,
36841             description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
36842         },
36843         {
36844             name: "noEmitOnError",
36845             type: "boolean",
36846             affectsEmit: true,
36847             category: ts.Diagnostics.Advanced_Options,
36848             description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
36849             transpileOptionValue: undefined
36850         },
36851         {
36852             name: "preserveConstEnums",
36853             type: "boolean",
36854             affectsEmit: true,
36855             category: ts.Diagnostics.Advanced_Options,
36856             description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
36857         },
36858         {
36859             name: "declarationDir",
36860             type: "string",
36861             affectsEmit: true,
36862             isFilePath: true,
36863             paramType: ts.Diagnostics.DIRECTORY,
36864             category: ts.Diagnostics.Advanced_Options,
36865             description: ts.Diagnostics.Output_directory_for_generated_declaration_files,
36866             transpileOptionValue: undefined
36867         },
36868         {
36869             name: "skipLibCheck",
36870             type: "boolean",
36871             category: ts.Diagnostics.Advanced_Options,
36872             description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
36873         },
36874         {
36875             name: "allowUnusedLabels",
36876             type: "boolean",
36877             affectsBindDiagnostics: true,
36878             affectsSemanticDiagnostics: true,
36879             category: ts.Diagnostics.Advanced_Options,
36880             description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
36881         },
36882         {
36883             name: "allowUnreachableCode",
36884             type: "boolean",
36885             affectsBindDiagnostics: true,
36886             affectsSemanticDiagnostics: true,
36887             category: ts.Diagnostics.Advanced_Options,
36888             description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
36889         },
36890         {
36891             name: "suppressExcessPropertyErrors",
36892             type: "boolean",
36893             affectsSemanticDiagnostics: true,
36894             category: ts.Diagnostics.Advanced_Options,
36895             description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
36896         },
36897         {
36898             name: "suppressImplicitAnyIndexErrors",
36899             type: "boolean",
36900             affectsSemanticDiagnostics: true,
36901             category: ts.Diagnostics.Advanced_Options,
36902             description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
36903         },
36904         {
36905             name: "forceConsistentCasingInFileNames",
36906             type: "boolean",
36907             affectsModuleResolution: true,
36908             category: ts.Diagnostics.Advanced_Options,
36909             description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
36910         },
36911         {
36912             name: "maxNodeModuleJsDepth",
36913             type: "number",
36914             affectsModuleResolution: true,
36915             category: ts.Diagnostics.Advanced_Options,
36916             description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
36917         },
36918         {
36919             name: "noStrictGenericChecks",
36920             type: "boolean",
36921             affectsSemanticDiagnostics: true,
36922             category: ts.Diagnostics.Advanced_Options,
36923             description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
36924         },
36925         {
36926             name: "useDefineForClassFields",
36927             type: "boolean",
36928             affectsSemanticDiagnostics: true,
36929             affectsEmit: true,
36930             category: ts.Diagnostics.Advanced_Options,
36931             description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set,
36932         },
36933         {
36934             name: "keyofStringsOnly",
36935             type: "boolean",
36936             category: ts.Diagnostics.Advanced_Options,
36937             description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols,
36938         },
36939         {
36940             // A list of plugins to load in the language service
36941             name: "plugins",
36942             type: "list",
36943             isTSConfigOnly: true,
36944             element: {
36945                 name: "plugin",
36946                 type: "object"
36947             },
36948             description: ts.Diagnostics.List_of_language_service_plugins
36949         },
36950     ]);
36951     /* @internal */
36952     ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
36953     /* @internal */
36954     ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; });
36955     /* @internal */
36956     ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
36957     /* @internal */
36958     ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
36959         return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
36960     });
36961     /* @internal */
36962     ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) {
36963         return ts.hasProperty(option, "transpileOptionValue");
36964     });
36965     /* @internal */
36966     ts.buildOpts = __spreadArray(__spreadArray([], ts.commonOptionsWithBuild), [
36967         {
36968             name: "verbose",
36969             shortName: "v",
36970             category: ts.Diagnostics.Command_line_Options,
36971             description: ts.Diagnostics.Enable_verbose_logging,
36972             type: "boolean"
36973         },
36974         {
36975             name: "dry",
36976             shortName: "d",
36977             category: ts.Diagnostics.Command_line_Options,
36978             description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
36979             type: "boolean"
36980         },
36981         {
36982             name: "force",
36983             shortName: "f",
36984             category: ts.Diagnostics.Command_line_Options,
36985             description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
36986             type: "boolean"
36987         },
36988         {
36989             name: "clean",
36990             category: ts.Diagnostics.Command_line_Options,
36991             description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
36992             type: "boolean"
36993         }
36994     ]);
36995     /* @internal */
36996     ts.typeAcquisitionDeclarations = [
36997         {
36998             /* @deprecated typingOptions.enableAutoDiscovery
36999              * Use typeAcquisition.enable instead.
37000              */
37001             name: "enableAutoDiscovery",
37002             type: "boolean",
37003         },
37004         {
37005             name: "enable",
37006             type: "boolean",
37007         },
37008         {
37009             name: "include",
37010             type: "list",
37011             element: {
37012                 name: "include",
37013                 type: "string"
37014             }
37015         },
37016         {
37017             name: "exclude",
37018             type: "list",
37019             element: {
37020                 name: "exclude",
37021                 type: "string"
37022             }
37023         },
37024         {
37025             name: "disableFilenameBasedTypeAcquisition",
37026             type: "boolean",
37027         },
37028     ];
37029     /*@internal*/
37030     function createOptionNameMap(optionDeclarations) {
37031         var optionsNameMap = new ts.Map();
37032         var shortOptionNames = new ts.Map();
37033         ts.forEach(optionDeclarations, function (option) {
37034             optionsNameMap.set(option.name.toLowerCase(), option);
37035             if (option.shortName) {
37036                 shortOptionNames.set(option.shortName, option.name);
37037             }
37038         });
37039         return { optionsNameMap: optionsNameMap, shortOptionNames: shortOptionNames };
37040     }
37041     ts.createOptionNameMap = createOptionNameMap;
37042     var optionsNameMapCache;
37043     /* @internal */
37044     function getOptionsNameMap() {
37045         return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations));
37046     }
37047     ts.getOptionsNameMap = getOptionsNameMap;
37048     /* @internal */
37049     ts.defaultInitCompilerOptions = {
37050         module: ts.ModuleKind.CommonJS,
37051         target: 1 /* ES5 */,
37052         strict: true,
37053         esModuleInterop: true,
37054         forceConsistentCasingInFileNames: true,
37055         skipLibCheck: true
37056     };
37057     /* @internal */
37058     function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
37059         // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
37060         if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
37061             return {
37062                 enable: typeAcquisition.enableAutoDiscovery,
37063                 include: typeAcquisition.include || [],
37064                 exclude: typeAcquisition.exclude || []
37065             };
37066         }
37067         return typeAcquisition;
37068     }
37069     ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
37070     /* @internal */
37071     function createCompilerDiagnosticForInvalidCustomType(opt) {
37072         return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
37073     }
37074     ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
37075     function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
37076         var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
37077         return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
37078     }
37079     /* @internal */
37080     function parseCustomTypeOption(opt, value, errors) {
37081         return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
37082     }
37083     ts.parseCustomTypeOption = parseCustomTypeOption;
37084     /* @internal */
37085     function parseListTypeOption(opt, value, errors) {
37086         if (value === void 0) { value = ""; }
37087         value = trimString(value);
37088         if (ts.startsWith(value, "-")) {
37089             return undefined;
37090         }
37091         if (value === "") {
37092             return [];
37093         }
37094         var values = value.split(",");
37095         switch (opt.element.type) {
37096             case "number":
37097                 return ts.mapDefined(values, function (v) { return validateJsonOptionValue(opt.element, parseInt(v), errors); });
37098             case "string":
37099                 return ts.mapDefined(values, function (v) { return validateJsonOptionValue(opt.element, v || "", errors); });
37100             default:
37101                 return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
37102         }
37103     }
37104     ts.parseListTypeOption = parseListTypeOption;
37105     function getOptionName(option) {
37106         return option.name;
37107     }
37108     function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) {
37109         var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
37110         return possibleOption ?
37111             createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) :
37112             createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
37113     }
37114     /*@internal*/
37115     function parseCommandLineWorker(diagnostics, commandLine, readFile) {
37116         var options = {};
37117         var watchOptions;
37118         var fileNames = [];
37119         var errors = [];
37120         parseStrings(commandLine);
37121         return {
37122             options: options,
37123             watchOptions: watchOptions,
37124             fileNames: fileNames,
37125             errors: errors
37126         };
37127         function parseStrings(args) {
37128             var i = 0;
37129             while (i < args.length) {
37130                 var s = args[i];
37131                 i++;
37132                 if (s.charCodeAt(0) === 64 /* at */) {
37133                     parseResponseFile(s.slice(1));
37134                 }
37135                 else if (s.charCodeAt(0) === 45 /* minus */) {
37136                     var inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
37137                     var opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
37138                     if (opt) {
37139                         i = parseOptionValue(args, i, diagnostics, opt, options, errors);
37140                     }
37141                     else {
37142                         var watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
37143                         if (watchOpt) {
37144                             i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
37145                         }
37146                         else {
37147                             errors.push(createUnknownOptionError(inputOptionName, diagnostics, ts.createCompilerDiagnostic, s));
37148                         }
37149                     }
37150                 }
37151                 else {
37152                     fileNames.push(s);
37153                 }
37154             }
37155         }
37156         function parseResponseFile(fileName) {
37157             var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); }));
37158             if (!ts.isString(text)) {
37159                 errors.push(text);
37160                 return;
37161             }
37162             var args = [];
37163             var pos = 0;
37164             while (true) {
37165                 while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
37166                     pos++;
37167                 if (pos >= text.length)
37168                     break;
37169                 var start = pos;
37170                 if (text.charCodeAt(start) === 34 /* doubleQuote */) {
37171                     pos++;
37172                     while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
37173                         pos++;
37174                     if (pos < text.length) {
37175                         args.push(text.substring(start + 1, pos));
37176                         pos++;
37177                     }
37178                     else {
37179                         errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
37180                     }
37181                 }
37182                 else {
37183                     while (text.charCodeAt(pos) > 32 /* space */)
37184                         pos++;
37185                     args.push(text.substring(start, pos));
37186                 }
37187             }
37188             parseStrings(args);
37189         }
37190     }
37191     ts.parseCommandLineWorker = parseCommandLineWorker;
37192     function parseOptionValue(args, i, diagnostics, opt, options, errors) {
37193         if (opt.isTSConfigOnly) {
37194             var optValue = args[i];
37195             if (optValue === "null") {
37196                 options[opt.name] = undefined;
37197                 i++;
37198             }
37199             else if (opt.type === "boolean") {
37200                 if (optValue === "false") {
37201                     options[opt.name] = validateJsonOptionValue(opt, /*value*/ false, errors);
37202                     i++;
37203                 }
37204                 else {
37205                     if (optValue === "true")
37206                         i++;
37207                     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));
37208                 }
37209             }
37210             else {
37211                 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));
37212                 if (optValue && !ts.startsWith(optValue, "-"))
37213                     i++;
37214             }
37215         }
37216         else {
37217             // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
37218             if (!args[i] && opt.type !== "boolean") {
37219                 errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
37220             }
37221             if (args[i] !== "null") {
37222                 switch (opt.type) {
37223                     case "number":
37224                         options[opt.name] = validateJsonOptionValue(opt, parseInt(args[i]), errors);
37225                         i++;
37226                         break;
37227                     case "boolean":
37228                         // boolean flag has optional value true, false, others
37229                         var optValue = args[i];
37230                         options[opt.name] = validateJsonOptionValue(opt, optValue !== "false", errors);
37231                         // consume next argument as boolean flag value
37232                         if (optValue === "false" || optValue === "true") {
37233                             i++;
37234                         }
37235                         break;
37236                     case "string":
37237                         options[opt.name] = validateJsonOptionValue(opt, args[i] || "", errors);
37238                         i++;
37239                         break;
37240                     case "list":
37241                         var result = parseListTypeOption(opt, args[i], errors);
37242                         options[opt.name] = result || [];
37243                         if (result) {
37244                             i++;
37245                         }
37246                         break;
37247                     // If not a primitive, the possible types are specified in what is effectively a map of options.
37248                     default:
37249                         options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
37250                         i++;
37251                         break;
37252                 }
37253             }
37254             else {
37255                 options[opt.name] = undefined;
37256                 i++;
37257             }
37258         }
37259         return i;
37260     }
37261     /*@internal*/
37262     ts.compilerOptionsDidYouMeanDiagnostics = {
37263         getOptionsNameMap: getOptionsNameMap,
37264         optionDeclarations: ts.optionDeclarations,
37265         unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0,
37266         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
37267         optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument
37268     };
37269     function parseCommandLine(commandLine, readFile) {
37270         return parseCommandLineWorker(ts.compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
37271     }
37272     ts.parseCommandLine = parseCommandLine;
37273     /** @internal */
37274     function getOptionFromName(optionName, allowShort) {
37275         return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
37276     }
37277     ts.getOptionFromName = getOptionFromName;
37278     function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
37279         if (allowShort === void 0) { allowShort = false; }
37280         optionName = optionName.toLowerCase();
37281         var _a = getOptionNameMap(), optionsNameMap = _a.optionsNameMap, shortOptionNames = _a.shortOptionNames;
37282         // Try to translate short option names to their full equivalents.
37283         if (allowShort) {
37284             var short = shortOptionNames.get(optionName);
37285             if (short !== undefined) {
37286                 optionName = short;
37287             }
37288         }
37289         return optionsNameMap.get(optionName);
37290     }
37291     var buildOptionsNameMapCache;
37292     function getBuildOptionsNameMap() {
37293         return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts));
37294     }
37295     var buildOptionsDidYouMeanDiagnostics = {
37296         getOptionsNameMap: getBuildOptionsNameMap,
37297         optionDeclarations: ts.buildOpts,
37298         unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0,
37299         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1,
37300         optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
37301     };
37302     /*@internal*/
37303     function parseBuildCommand(args) {
37304         var _a = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args), options = _a.options, watchOptions = _a.watchOptions, projects = _a.fileNames, errors = _a.errors;
37305         var buildOptions = options;
37306         if (projects.length === 0) {
37307             // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
37308             projects.push(".");
37309         }
37310         // Nonsensical combinations
37311         if (buildOptions.clean && buildOptions.force) {
37312             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
37313         }
37314         if (buildOptions.clean && buildOptions.verbose) {
37315             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
37316         }
37317         if (buildOptions.clean && buildOptions.watch) {
37318             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
37319         }
37320         if (buildOptions.watch && buildOptions.dry) {
37321             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
37322         }
37323         return { buildOptions: buildOptions, watchOptions: watchOptions, projects: projects, errors: errors };
37324     }
37325     ts.parseBuildCommand = parseBuildCommand;
37326     /* @internal */
37327     function getDiagnosticText(_message) {
37328         var _args = [];
37329         for (var _i = 1; _i < arguments.length; _i++) {
37330             _args[_i - 1] = arguments[_i];
37331         }
37332         var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
37333         return diagnostic.messageText;
37334     }
37335     ts.getDiagnosticText = getDiagnosticText;
37336     /**
37337      * Reads the config file, reports errors if any and exits if the config file cannot be found
37338      */
37339     function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) {
37340         var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); });
37341         if (!ts.isString(configFileText)) {
37342             host.onUnRecoverableConfigFileDiagnostic(configFileText);
37343             return undefined;
37344         }
37345         var result = ts.parseJsonText(configFileName, configFileText);
37346         var cwd = host.getCurrentDirectory();
37347         result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
37348         result.resolvedPath = result.path;
37349         result.originalFileName = result.fileName;
37350         return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), 
37351         /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend);
37352     }
37353     ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
37354     /**
37355      * Read tsconfig.json file
37356      * @param fileName The path to the config file
37357      */
37358     function readConfigFile(fileName, readFile) {
37359         var textOrDiagnostic = tryReadFile(fileName, readFile);
37360         return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
37361     }
37362     ts.readConfigFile = readConfigFile;
37363     /**
37364      * Parse the text of the tsconfig.json file
37365      * @param fileName The path to the config file
37366      * @param jsonText The text of the config file
37367      */
37368     function parseConfigFileTextToJson(fileName, jsonText) {
37369         var jsonSourceFile = ts.parseJsonText(fileName, jsonText);
37370         return {
37371             config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics),
37372             error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
37373         };
37374     }
37375     ts.parseConfigFileTextToJson = parseConfigFileTextToJson;
37376     /**
37377      * Read tsconfig.json file
37378      * @param fileName The path to the config file
37379      */
37380     function readJsonConfigFile(fileName, readFile) {
37381         var textOrDiagnostic = tryReadFile(fileName, readFile);
37382         return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { fileName: fileName, parseDiagnostics: [textOrDiagnostic] };
37383     }
37384     ts.readJsonConfigFile = readJsonConfigFile;
37385     /*@internal*/
37386     function tryReadFile(fileName, readFile) {
37387         var text;
37388         try {
37389             text = readFile(fileName);
37390         }
37391         catch (e) {
37392             return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
37393         }
37394         return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text;
37395     }
37396     ts.tryReadFile = tryReadFile;
37397     function commandLineOptionsToMap(options) {
37398         return ts.arrayToMap(options, getOptionName);
37399     }
37400     var typeAcquisitionDidYouMeanDiagnostics = {
37401         optionDeclarations: ts.typeAcquisitionDeclarations,
37402         unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0,
37403         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1,
37404     };
37405     var watchOptionsNameMapCache;
37406     function getWatchOptionsNameMap() {
37407         return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(ts.optionsForWatch));
37408     }
37409     var watchOptionsDidYouMeanDiagnostics = {
37410         getOptionsNameMap: getWatchOptionsNameMap,
37411         optionDeclarations: ts.optionsForWatch,
37412         unknownOptionDiagnostic: ts.Diagnostics.Unknown_watch_option_0,
37413         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
37414         optionTypeMismatchDiagnostic: ts.Diagnostics.Watch_option_0_requires_a_value_of_type_1
37415     };
37416     var commandLineCompilerOptionsMapCache;
37417     function getCommandLineCompilerOptionsMap() {
37418         return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(ts.optionDeclarations));
37419     }
37420     var commandLineWatchOptionsMapCache;
37421     function getCommandLineWatchOptionsMap() {
37422         return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(ts.optionsForWatch));
37423     }
37424     var commandLineTypeAcquisitionMapCache;
37425     function getCommandLineTypeAcquisitionMap() {
37426         return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(ts.typeAcquisitionDeclarations));
37427     }
37428     var _tsconfigRootOptions;
37429     function getTsconfigRootOptionsMap() {
37430         if (_tsconfigRootOptions === undefined) {
37431             _tsconfigRootOptions = {
37432                 name: undefined,
37433                 type: "object",
37434                 elementOptions: commandLineOptionsToMap([
37435                     {
37436                         name: "compilerOptions",
37437                         type: "object",
37438                         elementOptions: getCommandLineCompilerOptionsMap(),
37439                         extraKeyDiagnostics: ts.compilerOptionsDidYouMeanDiagnostics,
37440                     },
37441                     {
37442                         name: "watchOptions",
37443                         type: "object",
37444                         elementOptions: getCommandLineWatchOptionsMap(),
37445                         extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics,
37446                     },
37447                     {
37448                         name: "typingOptions",
37449                         type: "object",
37450                         elementOptions: getCommandLineTypeAcquisitionMap(),
37451                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics,
37452                     },
37453                     {
37454                         name: "typeAcquisition",
37455                         type: "object",
37456                         elementOptions: getCommandLineTypeAcquisitionMap(),
37457                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
37458                     },
37459                     {
37460                         name: "extends",
37461                         type: "string"
37462                     },
37463                     {
37464                         name: "references",
37465                         type: "list",
37466                         element: {
37467                             name: "references",
37468                             type: "object"
37469                         }
37470                     },
37471                     {
37472                         name: "files",
37473                         type: "list",
37474                         element: {
37475                             name: "files",
37476                             type: "string"
37477                         }
37478                     },
37479                     {
37480                         name: "include",
37481                         type: "list",
37482                         element: {
37483                             name: "include",
37484                             type: "string"
37485                         }
37486                     },
37487                     {
37488                         name: "exclude",
37489                         type: "list",
37490                         element: {
37491                             name: "exclude",
37492                             type: "string"
37493                         }
37494                     },
37495                     ts.compileOnSaveCommandLineOption
37496                 ])
37497             };
37498         }
37499         return _tsconfigRootOptions;
37500     }
37501     /**
37502      * Convert the json syntax tree into the json value
37503      */
37504     function convertToObject(sourceFile, errors) {
37505         return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
37506     }
37507     ts.convertToObject = convertToObject;
37508     /**
37509      * Convert the json syntax tree into the json value and report errors
37510      * This returns the json value (apart from checking errors) only if returnValue provided is true.
37511      * Otherwise it just checks the errors and returns undefined
37512      */
37513     /*@internal*/
37514     function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
37515         if (!sourceFile.statements.length) {
37516             return returnValue ? {} : undefined;
37517         }
37518         return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
37519         function isRootOptionMap(knownOptions) {
37520             return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
37521         }
37522         function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) {
37523             var result = returnValue ? {} : undefined;
37524             var _loop_4 = function (element) {
37525                 if (element.kind !== 288 /* PropertyAssignment */) {
37526                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
37527                     return "continue";
37528                 }
37529                 if (element.questionToken) {
37530                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
37531                 }
37532                 if (!isDoubleQuotedString(element.name)) {
37533                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
37534                 }
37535                 var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name);
37536                 var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
37537                 var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
37538                 if (keyText && extraKeyDiagnostics && !option) {
37539                     if (knownOptions) {
37540                         errors.push(createUnknownOptionError(keyText, extraKeyDiagnostics, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, message, arg0, arg1); }));
37541                     }
37542                     else {
37543                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
37544                     }
37545                 }
37546                 var value = convertPropertyValueToJson(element.initializer, option);
37547                 if (typeof keyText !== "undefined") {
37548                     if (returnValue) {
37549                         result[keyText] = value;
37550                     }
37551                     // Notify key value set, if user asked for it
37552                     if (jsonConversionNotifier &&
37553                         // Current callbacks are only on known parent option or if we are setting values in the root
37554                         (parentOption || isRootOptionMap(knownOptions))) {
37555                         var isValidOptionValue = isCompilerOptionsValue(option, value);
37556                         if (parentOption) {
37557                             if (isValidOptionValue) {
37558                                 // Notify option set in the parent if its a valid option value
37559                                 jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
37560                             }
37561                         }
37562                         else if (isRootOptionMap(knownOptions)) {
37563                             if (isValidOptionValue) {
37564                                 // Notify about the valid root key value being set
37565                                 jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
37566                             }
37567                             else if (!option) {
37568                                 // Notify about the unknown root key value being set
37569                                 jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
37570                             }
37571                         }
37572                     }
37573                 }
37574             };
37575             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
37576                 var element = _a[_i];
37577                 _loop_4(element);
37578             }
37579             return result;
37580         }
37581         function convertArrayLiteralExpressionToJson(elements, elementOption) {
37582             if (!returnValue) {
37583                 elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
37584                 return undefined;
37585             }
37586             // Filter out invalid values
37587             return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
37588         }
37589         function convertPropertyValueToJson(valueExpression, option) {
37590             var invalidReported;
37591             switch (valueExpression.kind) {
37592                 case 109 /* TrueKeyword */:
37593                     reportInvalidOptionValue(option && option.type !== "boolean");
37594                     return validateValue(/*value*/ true);
37595                 case 94 /* FalseKeyword */:
37596                     reportInvalidOptionValue(option && option.type !== "boolean");
37597                     return validateValue(/*value*/ false);
37598                 case 103 /* NullKeyword */:
37599                     reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
37600                     return validateValue(/*value*/ null); // eslint-disable-line no-null/no-null
37601                 case 10 /* StringLiteral */:
37602                     if (!isDoubleQuotedString(valueExpression)) {
37603                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
37604                     }
37605                     reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
37606                     var text = valueExpression.text;
37607                     if (option && !ts.isString(option.type)) {
37608                         var customOption = option;
37609                         // Validate custom option type
37610                         if (!customOption.type.has(text.toLowerCase())) {
37611                             errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
37612                             invalidReported = true;
37613                         }
37614                     }
37615                     return validateValue(text);
37616                 case 8 /* NumericLiteral */:
37617                     reportInvalidOptionValue(option && option.type !== "number");
37618                     return validateValue(Number(valueExpression.text));
37619                 case 214 /* PrefixUnaryExpression */:
37620                     if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
37621                         break; // not valid JSON syntax
37622                     }
37623                     reportInvalidOptionValue(option && option.type !== "number");
37624                     return validateValue(-Number(valueExpression.operand.text));
37625                 case 200 /* ObjectLiteralExpression */:
37626                     reportInvalidOptionValue(option && option.type !== "object");
37627                     var objectLiteralExpression = valueExpression;
37628                     // Currently having element option declaration in the tsconfig with type "object"
37629                     // determines if it needs onSetValidOptionKeyValueInParent callback or not
37630                     // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
37631                     // that satifies it and need it to modify options set in them (for normalizing file paths)
37632                     // vs what we set in the json
37633                     // If need arises, we can modify this interface and callbacks as needed
37634                     if (option) {
37635                         var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name;
37636                         return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName));
37637                     }
37638                     else {
37639                         return validateValue(convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, 
37640                         /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined));
37641                     }
37642                 case 199 /* ArrayLiteralExpression */:
37643                     reportInvalidOptionValue(option && option.type !== "list");
37644                     return validateValue(convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element));
37645             }
37646             // Not in expected format
37647             if (option) {
37648                 reportInvalidOptionValue(/*isError*/ true);
37649             }
37650             else {
37651                 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));
37652             }
37653             return undefined;
37654             function validateValue(value) {
37655                 var _a;
37656                 if (!invalidReported) {
37657                     var diagnostic = (_a = option === null || option === void 0 ? void 0 : option.extraValidation) === null || _a === void 0 ? void 0 : _a.call(option, value);
37658                     if (diagnostic) {
37659                         errors.push(ts.createDiagnosticForNodeInSourceFile.apply(void 0, __spreadArray([sourceFile, valueExpression], diagnostic)));
37660                         return undefined;
37661                     }
37662                 }
37663                 return value;
37664             }
37665             function reportInvalidOptionValue(isError) {
37666                 if (isError) {
37667                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
37668                     invalidReported = true;
37669                 }
37670             }
37671         }
37672         function isDoubleQuotedString(node) {
37673             return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
37674         }
37675     }
37676     ts.convertToObjectWorker = convertToObjectWorker;
37677     function getCompilerOptionValueTypeString(option) {
37678         return option.type === "list" ?
37679             "Array" :
37680             ts.isString(option.type) ? option.type : "string";
37681     }
37682     function isCompilerOptionsValue(option, value) {
37683         if (option) {
37684             if (isNullOrUndefined(value))
37685                 return true; // All options are undefinable/nullable
37686             if (option.type === "list") {
37687                 return ts.isArray(value);
37688             }
37689             var expectedType = ts.isString(option.type) ? option.type : "string";
37690             return typeof value === expectedType;
37691         }
37692         return false;
37693     }
37694     /**
37695      * Generate an uncommented, complete tsconfig for use with "--showConfig"
37696      * @param configParseResult options to be generated into tsconfig.json
37697      * @param configFileName name of the parsed config file - output paths will be generated relative to this
37698      * @param host provides current directory and case sensitivity services
37699      */
37700     /** @internal */
37701     function convertToTSConfig(configParseResult, configFileName, host) {
37702         var _a, _b, _c;
37703         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
37704         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); });
37705         var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
37706         var watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
37707         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) ? {
37708             include: filterSameAsDefaultInclude(configParseResult.options.configFile.configFileSpecs.validatedIncludeSpecs),
37709             exclude: configParseResult.options.configFile.configFileSpecs.validatedExcludeSpecs
37710         } : {})), { compileOnSave: !!configParseResult.compileOnSave ? true : undefined });
37711         return config;
37712     }
37713     ts.convertToTSConfig = convertToTSConfig;
37714     function optionMapToObject(optionMap) {
37715         return __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) {
37716             var _a;
37717             return (__assign(__assign({}, prev), (_a = {}, _a[cur[0]] = cur[1], _a)));
37718         }, {}));
37719     }
37720     function filterSameAsDefaultInclude(specs) {
37721         if (!ts.length(specs))
37722             return undefined;
37723         if (ts.length(specs) !== 1)
37724             return specs;
37725         if (specs[0] === "**/*")
37726             return undefined;
37727         return specs;
37728     }
37729     function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
37730         if (!includeSpecs)
37731             return ts.returnTrue;
37732         var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
37733         var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
37734         var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
37735         if (includeRe) {
37736             if (excludeRe) {
37737                 return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); };
37738             }
37739             return function (path) { return !includeRe.test(path); };
37740         }
37741         if (excludeRe) {
37742             return function (path) { return excludeRe.test(path); };
37743         }
37744         return ts.returnTrue;
37745     }
37746     function getCustomTypeMapOfCommandLineOption(optionDefinition) {
37747         if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
37748             // this is of a type CommandLineOptionOfPrimitiveType
37749             return undefined;
37750         }
37751         else if (optionDefinition.type === "list") {
37752             return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
37753         }
37754         else {
37755             return optionDefinition.type;
37756         }
37757     }
37758     function getNameOfCompilerOptionValue(value, customTypeMap) {
37759         // There is a typeMap associated with this command-line option so use it to map value back to its name
37760         return ts.forEachEntry(customTypeMap, function (mapValue, key) {
37761             if (mapValue === value) {
37762                 return key;
37763             }
37764         });
37765     }
37766     function serializeCompilerOptions(options, pathOptions) {
37767         return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
37768     }
37769     function serializeWatchOptions(options) {
37770         return serializeOptionBaseObject(options, getWatchOptionsNameMap());
37771     }
37772     function serializeOptionBaseObject(options, _a, pathOptions) {
37773         var optionsNameMap = _a.optionsNameMap;
37774         var result = new ts.Map();
37775         var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
37776         var _loop_5 = function (name) {
37777             if (ts.hasProperty(options, name)) {
37778                 // tsconfig only options cannot be specified via command line,
37779                 // so we can assume that only types that can appear here string | number | boolean
37780                 if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) {
37781                     return "continue";
37782                 }
37783                 var value = options[name];
37784                 var optionDefinition = optionsNameMap.get(name.toLowerCase());
37785                 if (optionDefinition) {
37786                     var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition);
37787                     if (!customTypeMap_1) {
37788                         // There is no map associated with this compiler option then use the value as-is
37789                         // This is the case if the value is expect to be string, number, boolean or list of string
37790                         if (pathOptions && optionDefinition.isFilePath) {
37791                             result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
37792                         }
37793                         else {
37794                             result.set(name, value);
37795                         }
37796                     }
37797                     else {
37798                         if (optionDefinition.type === "list") {
37799                             result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217
37800                         }
37801                         else {
37802                             // There is a typeMap associated with this command-line option so use it to map value back to its name
37803                             result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1));
37804                         }
37805                     }
37806                 }
37807             }
37808         };
37809         for (var name in options) {
37810             _loop_5(name);
37811         }
37812         return result;
37813     }
37814     /**
37815      * Generate tsconfig configuration when running command line "--init"
37816      * @param options commandlineOptions to be generated into tsconfig.json
37817      * @param fileNames array of filenames to be generated into tsconfig.json
37818      */
37819     /* @internal */
37820     function generateTSConfig(options, fileNames, newLine) {
37821         var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
37822         var compilerOptionsMap = serializeCompilerOptions(compilerOptions);
37823         return writeConfigurations();
37824         function getDefaultValueForOption(option) {
37825             switch (option.type) {
37826                 case "number":
37827                     return 1;
37828                 case "boolean":
37829                     return true;
37830                 case "string":
37831                     return option.isFilePath ? "./" : "";
37832                 case "list":
37833                     return [];
37834                 case "object":
37835                     return {};
37836                 default:
37837                     var iterResult = option.type.keys().next();
37838                     if (!iterResult.done)
37839                         return iterResult.value;
37840                     return ts.Debug.fail("Expected 'option.type' to have entries.");
37841             }
37842         }
37843         function makePadding(paddingLength) {
37844             return Array(paddingLength + 1).join(" ");
37845         }
37846         function isAllowedOption(_a) {
37847             var category = _a.category, name = _a.name;
37848             // Skip options which do not have a category or have category `Command_line_Options`
37849             // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line
37850             return category !== undefined
37851                 && category !== ts.Diagnostics.Command_line_Options
37852                 && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name));
37853         }
37854         function writeConfigurations() {
37855             // Filter applicable options to place in the file
37856             var categorizedOptions = ts.createMultiMap();
37857             for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) {
37858                 var option = optionDeclarations_1[_i];
37859                 var category = option.category;
37860                 if (isAllowedOption(option)) {
37861                     categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
37862                 }
37863             }
37864             // Serialize all options and their descriptions
37865             var marginLength = 0;
37866             var seenKnownKeys = 0;
37867             var entries = [];
37868             categorizedOptions.forEach(function (options, category) {
37869                 if (entries.length !== 0) {
37870                     entries.push({ value: "" });
37871                 }
37872                 entries.push({ value: "/* " + category + " */" });
37873                 for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
37874                     var option = options_1[_i];
37875                     var optionName = void 0;
37876                     if (compilerOptionsMap.has(option.name)) {
37877                         optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
37878                     }
37879                     else {
37880                         optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ",";
37881                     }
37882                     entries.push({
37883                         value: optionName,
37884                         description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"
37885                     });
37886                     marginLength = Math.max(optionName.length, marginLength);
37887                 }
37888             });
37889             // Write the output
37890             var tab = makePadding(2);
37891             var result = [];
37892             result.push("{");
37893             result.push(tab + "\"compilerOptions\": {");
37894             result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */");
37895             result.push("");
37896             // Print out each row, aligning all the descriptions on the same column.
37897             for (var _a = 0, entries_2 = entries; _a < entries_2.length; _a++) {
37898                 var entry = entries_2[_a];
37899                 var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b;
37900                 result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description)));
37901             }
37902             if (fileNames.length) {
37903                 result.push(tab + "},");
37904                 result.push(tab + "\"files\": [");
37905                 for (var i = 0; i < fileNames.length; i++) {
37906                     result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ","));
37907                 }
37908                 result.push(tab + "]");
37909             }
37910             else {
37911                 result.push(tab + "}");
37912             }
37913             result.push("}");
37914             return result.join(newLine) + newLine;
37915         }
37916     }
37917     ts.generateTSConfig = generateTSConfig;
37918     /* @internal */
37919     function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
37920         var result = {};
37921         var optionsNameMap = getOptionsNameMap().optionsNameMap;
37922         for (var name in options) {
37923             if (ts.hasProperty(options, name)) {
37924                 result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath);
37925             }
37926         }
37927         if (result.configFilePath) {
37928             result.configFilePath = toAbsolutePath(result.configFilePath);
37929         }
37930         return result;
37931     }
37932     ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths;
37933     function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
37934         if (option && !isNullOrUndefined(value)) {
37935             if (option.type === "list") {
37936                 var values = value;
37937                 if (option.element.isFilePath && values.length) {
37938                     return values.map(toAbsolutePath);
37939                 }
37940             }
37941             else if (option.isFilePath) {
37942                 return toAbsolutePath(value);
37943             }
37944         }
37945         return value;
37946     }
37947     /**
37948      * Parse the contents of a config file (tsconfig.json).
37949      * @param json The contents of the config file to parse
37950      * @param host Instance of ParseConfigHost used to enumerate files in folder.
37951      * @param basePath A root directory to resolve relative path entries in the config
37952      *    file to. e.g. outDir
37953      */
37954     function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
37955         return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
37956     }
37957     ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
37958     /**
37959      * Parse the contents of a config file (tsconfig.json).
37960      * @param jsonNode The contents of the config file to parse
37961      * @param host Instance of ParseConfigHost used to enumerate files in folder.
37962      * @param basePath A root directory to resolve relative path entries in the config
37963      *    file to. e.g. outDir
37964      */
37965     function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
37966         return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
37967     }
37968     ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
37969     /*@internal*/
37970     function setConfigFileInOptions(options, configFile) {
37971         if (configFile) {
37972             Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
37973         }
37974     }
37975     ts.setConfigFileInOptions = setConfigFileInOptions;
37976     function isNullOrUndefined(x) {
37977         return x === undefined || x === null; // eslint-disable-line no-null/no-null
37978     }
37979     function directoryOfCombinedPath(fileName, basePath) {
37980         // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
37981         // until consistent casing errors are reported
37982         return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
37983     }
37984     /**
37985      * Parse the contents of a config file from json or json source file (tsconfig.json).
37986      * @param json The contents of the config file to parse
37987      * @param sourceFile sourceFile corresponding to the Json
37988      * @param host Instance of ParseConfigHost used to enumerate files in folder.
37989      * @param basePath A root directory to resolve relative path entries in the config
37990      *    file to. e.g. outDir
37991      * @param resolutionStack Only present for backwards-compatibility. Should be empty.
37992      */
37993     function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) {
37994         if (existingOptions === void 0) { existingOptions = {}; }
37995         if (resolutionStack === void 0) { resolutionStack = []; }
37996         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
37997         ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
37998         var errors = [];
37999         var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
38000         var raw = parsedConfig.raw;
38001         var options = ts.extend(existingOptions, parsedConfig.options || {});
38002         var watchOptions = existingWatchOptions && parsedConfig.watchOptions ?
38003             ts.extend(existingWatchOptions, parsedConfig.watchOptions) :
38004             parsedConfig.watchOptions || existingWatchOptions;
38005         options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
38006         var configFileSpecs = getConfigFileSpecs();
38007         if (sourceFile)
38008             sourceFile.configFileSpecs = configFileSpecs;
38009         setConfigFileInOptions(options, sourceFile);
38010         var basePathForFileNames = ts.normalizePath(configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath);
38011         return {
38012             options: options,
38013             watchOptions: watchOptions,
38014             fileNames: getFileNames(basePathForFileNames),
38015             projectReferences: getProjectReferences(basePathForFileNames),
38016             typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
38017             raw: raw,
38018             errors: errors,
38019             // Wildcard directories (provided as part of a wildcard path) are stored in a
38020             // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
38021             // or a recursive directory. This information is used by filesystem watchers to monitor for
38022             // new entries in these paths.
38023             wildcardDirectories: getWildcardDirectories(configFileSpecs, basePathForFileNames, host.useCaseSensitiveFileNames),
38024             compileOnSave: !!raw.compileOnSave,
38025         };
38026         function getConfigFileSpecs() {
38027             var referencesOfRaw = getPropFromRaw("references", function (element) { return typeof element === "object"; }, "object");
38028             var filesSpecs = toPropValue(getSpecsFromRaw("files"));
38029             if (filesSpecs) {
38030                 var hasZeroOrNoReferences = referencesOfRaw === "no-prop" || ts.isArray(referencesOfRaw) && referencesOfRaw.length === 0;
38031                 var hasExtends = ts.hasProperty(raw, "extends");
38032                 if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
38033                     if (sourceFile) {
38034                         var fileName = configFileName || "tsconfig.json";
38035                         var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
38036                         var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
38037                         var error = nodeValue
38038                             ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
38039                             : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
38040                         errors.push(error);
38041                     }
38042                     else {
38043                         createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
38044                     }
38045                 }
38046             }
38047             var includeSpecs = toPropValue(getSpecsFromRaw("include"));
38048             var excludeOfRaw = getSpecsFromRaw("exclude");
38049             var excludeSpecs = toPropValue(excludeOfRaw);
38050             if (excludeOfRaw === "no-prop" && raw.compilerOptions) {
38051                 var outDir = raw.compilerOptions.outDir;
38052                 var declarationDir = raw.compilerOptions.declarationDir;
38053                 if (outDir || declarationDir) {
38054                     excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
38055                 }
38056             }
38057             if (filesSpecs === undefined && includeSpecs === undefined) {
38058                 includeSpecs = ["**/*"];
38059             }
38060             var validatedIncludeSpecs, validatedExcludeSpecs;
38061             // The exclude spec list is converted into a regular expression, which allows us to quickly
38062             // test whether a file or directory should be excluded before recursively traversing the
38063             // file system.
38064             if (includeSpecs) {
38065                 validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*disallowTrailingRecursion*/ true, sourceFile, "include");
38066             }
38067             if (excludeSpecs) {
38068                 validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*disallowTrailingRecursion*/ false, sourceFile, "exclude");
38069             }
38070             return {
38071                 filesSpecs: filesSpecs,
38072                 includeSpecs: includeSpecs,
38073                 excludeSpecs: excludeSpecs,
38074                 validatedFilesSpec: ts.filter(filesSpecs, ts.isString),
38075                 validatedIncludeSpecs: validatedIncludeSpecs,
38076                 validatedExcludeSpecs: validatedExcludeSpecs,
38077             };
38078         }
38079         function getFileNames(basePath) {
38080             var fileNames = getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, extraFileExtensions);
38081             if (shouldReportNoInputFiles(fileNames, canJsonReportNoInputFiles(raw), resolutionStack)) {
38082                 errors.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
38083             }
38084             return fileNames;
38085         }
38086         function getProjectReferences(basePath) {
38087             var projectReferences;
38088             var referencesOfRaw = getPropFromRaw("references", function (element) { return typeof element === "object"; }, "object");
38089             if (ts.isArray(referencesOfRaw)) {
38090                 for (var _i = 0, referencesOfRaw_1 = referencesOfRaw; _i < referencesOfRaw_1.length; _i++) {
38091                     var ref = referencesOfRaw_1[_i];
38092                     if (typeof ref.path !== "string") {
38093                         createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
38094                     }
38095                     else {
38096                         (projectReferences || (projectReferences = [])).push({
38097                             path: ts.getNormalizedAbsolutePath(ref.path, basePath),
38098                             originalPath: ref.path,
38099                             prepend: ref.prepend,
38100                             circular: ref.circular
38101                         });
38102                     }
38103                 }
38104             }
38105             return projectReferences;
38106         }
38107         function toPropValue(specResult) {
38108             return ts.isArray(specResult) ? specResult : undefined;
38109         }
38110         function getSpecsFromRaw(prop) {
38111             return getPropFromRaw(prop, ts.isString, "string");
38112         }
38113         function getPropFromRaw(prop, validateElement, elementTypeName) {
38114             if (ts.hasProperty(raw, prop) && !isNullOrUndefined(raw[prop])) {
38115                 if (ts.isArray(raw[prop])) {
38116                     var result = raw[prop];
38117                     if (!sourceFile && !ts.every(result, validateElement)) {
38118                         errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, elementTypeName));
38119                     }
38120                     return result;
38121                 }
38122                 else {
38123                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, "Array");
38124                     return "not-array";
38125                 }
38126             }
38127             return "no-prop";
38128         }
38129         function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
38130             if (!sourceFile) {
38131                 errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
38132             }
38133         }
38134     }
38135     function isErrorNoInputFiles(error) {
38136         return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
38137     }
38138     function getErrorForNoInputFiles(_a, configFileName) {
38139         var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
38140         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 || []));
38141     }
38142     function shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles, resolutionStack) {
38143         return fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
38144     }
38145     /*@internal*/
38146     function canJsonReportNoInputFiles(raw) {
38147         return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references");
38148     }
38149     ts.canJsonReportNoInputFiles = canJsonReportNoInputFiles;
38150     /*@internal*/
38151     function updateErrorForNoInputFiles(fileNames, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
38152         var existingErrors = configParseDiagnostics.length;
38153         if (shouldReportNoInputFiles(fileNames, canJsonReportNoInutFiles)) {
38154             configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
38155         }
38156         else {
38157             ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); });
38158         }
38159         return existingErrors !== configParseDiagnostics.length;
38160     }
38161     ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles;
38162     function isSuccessfulParsedTsconfig(value) {
38163         return !!value.options;
38164     }
38165     /**
38166      * This *just* extracts options/include/exclude/files out of a config file.
38167      * It does *not* resolve the included files.
38168      */
38169     function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) {
38170         var _a;
38171         basePath = ts.normalizeSlashes(basePath);
38172         var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
38173         if (resolutionStack.indexOf(resolvedPath) >= 0) {
38174             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArray(__spreadArray([], resolutionStack), [resolvedPath]).join(" -> ")));
38175             return { raw: json || convertToObject(sourceFile, errors) };
38176         }
38177         var ownConfig = json ?
38178             parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
38179             parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
38180         if ((_a = ownConfig.options) === null || _a === void 0 ? void 0 : _a.paths) {
38181             // If we end up needing to resolve relative paths from 'paths' relative to
38182             // the config file location, we'll need to know where that config file was.
38183             // Since 'paths' can be inherited from an extended config in another directory,
38184             // we wouldn't know which directory to use unless we store it here.
38185             ownConfig.options.pathsBasePath = basePath;
38186         }
38187         if (ownConfig.extendedConfigPath) {
38188             // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
38189             resolutionStack = resolutionStack.concat([resolvedPath]);
38190             var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, resolutionStack, errors, extendedConfigCache);
38191             if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
38192                 var baseRaw_1 = extendedConfig.raw;
38193                 var raw_1 = ownConfig.raw;
38194                 var relativeDifference_1;
38195                 var setPropertyInRawIfNotUndefined = function (propertyName) {
38196                     if (!raw_1[propertyName] && baseRaw_1[propertyName]) {
38197                         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); });
38198                     }
38199                 };
38200                 setPropertyInRawIfNotUndefined("include");
38201                 setPropertyInRawIfNotUndefined("exclude");
38202                 setPropertyInRawIfNotUndefined("files");
38203                 if (raw_1.compileOnSave === undefined) {
38204                     raw_1.compileOnSave = baseRaw_1.compileOnSave;
38205                 }
38206                 ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
38207                 ownConfig.watchOptions = ownConfig.watchOptions && extendedConfig.watchOptions ?
38208                     ts.assign({}, extendedConfig.watchOptions, ownConfig.watchOptions) :
38209                     ownConfig.watchOptions || extendedConfig.watchOptions;
38210                 // TODO extend type typeAcquisition
38211             }
38212         }
38213         return ownConfig;
38214     }
38215     function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
38216         if (ts.hasProperty(json, "excludes")) {
38217             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
38218         }
38219         var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
38220         // typingOptions has been deprecated and is only supported for backward compatibility purposes.
38221         // It should be removed in future releases - use typeAcquisition instead.
38222         var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
38223         var watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
38224         json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
38225         var extendedConfigPath;
38226         if (json.extends) {
38227             if (!ts.isString(json.extends)) {
38228                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
38229             }
38230             else {
38231                 var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
38232                 extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
38233             }
38234         }
38235         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
38236     }
38237     function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
38238         var options = getDefaultCompilerOptions(configFileName);
38239         var typeAcquisition, typingOptionstypeAcquisition;
38240         var watchOptions;
38241         var extendedConfigPath;
38242         var optionsIterator = {
38243             onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
38244                 var currentOption;
38245                 switch (parentOption) {
38246                     case "compilerOptions":
38247                         currentOption = options;
38248                         break;
38249                     case "watchOptions":
38250                         currentOption = (watchOptions || (watchOptions = {}));
38251                         break;
38252                     case "typeAcquisition":
38253                         currentOption = (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName)));
38254                         break;
38255                     case "typingOptions":
38256                         currentOption = (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
38257                         break;
38258                     default:
38259                         ts.Debug.fail("Unknown option");
38260                 }
38261                 currentOption[option.name] = normalizeOptionValue(option, basePath, value);
38262             },
38263             onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
38264                 switch (key) {
38265                     case "extends":
38266                         var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
38267                         extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
38268                             return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
38269                         });
38270                         return;
38271                 }
38272             },
38273             onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
38274                 if (key === "excludes") {
38275                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
38276                 }
38277             }
38278         };
38279         var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
38280         if (!typeAcquisition) {
38281             if (typingOptionstypeAcquisition) {
38282                 typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
38283                     {
38284                         enable: typingOptionstypeAcquisition.enableAutoDiscovery,
38285                         include: typingOptionstypeAcquisition.include,
38286                         exclude: typingOptionstypeAcquisition.exclude
38287                     } :
38288                     typingOptionstypeAcquisition;
38289             }
38290             else {
38291                 typeAcquisition = getDefaultTypeAcquisition(configFileName);
38292             }
38293         }
38294         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
38295     }
38296     function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
38297         extendedConfig = ts.normalizeSlashes(extendedConfig);
38298         if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) {
38299             var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
38300             if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
38301                 extendedConfigPath = extendedConfigPath + ".json";
38302                 if (!host.fileExists(extendedConfigPath)) {
38303                     errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
38304                     return undefined;
38305                 }
38306             }
38307             return extendedConfigPath;
38308         }
38309         // If the path isn't a rooted or relative path, resolve like a module
38310         var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true);
38311         if (resolved.resolvedModule) {
38312             return resolved.resolvedModule.resolvedFileName;
38313         }
38314         errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
38315         return undefined;
38316     }
38317     function getExtendedConfig(sourceFile, extendedConfigPath, host, resolutionStack, errors, extendedConfigCache) {
38318         var _a;
38319         var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath);
38320         var value;
38321         var extendedResult;
38322         var extendedConfig;
38323         if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
38324             (extendedResult = value.extendedResult, extendedConfig = value.extendedConfig);
38325         }
38326         else {
38327             extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
38328             if (!extendedResult.parseDiagnostics.length) {
38329                 extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, ts.getDirectoryPath(extendedConfigPath), ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
38330             }
38331             if (extendedConfigCache) {
38332                 extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig });
38333             }
38334         }
38335         if (sourceFile) {
38336             sourceFile.extendedSourceFiles = [extendedResult.fileName];
38337             if (extendedResult.extendedSourceFiles) {
38338                 (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
38339             }
38340         }
38341         if (extendedResult.parseDiagnostics.length) {
38342             errors.push.apply(errors, extendedResult.parseDiagnostics);
38343             return undefined;
38344         }
38345         return extendedConfig;
38346     }
38347     function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
38348         if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
38349             return false;
38350         }
38351         var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
38352         return typeof result === "boolean" && result;
38353     }
38354     function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
38355         var errors = [];
38356         var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
38357         return { options: options, errors: errors };
38358     }
38359     ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
38360     function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
38361         var errors = [];
38362         var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
38363         return { options: options, errors: errors };
38364     }
38365     ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
38366     function getDefaultCompilerOptions(configFileName) {
38367         var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
38368             ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
38369             : {};
38370         return options;
38371     }
38372     function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
38373         var options = getDefaultCompilerOptions(configFileName);
38374         convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, ts.compilerOptionsDidYouMeanDiagnostics, errors);
38375         if (configFileName) {
38376             options.configFilePath = ts.normalizeSlashes(configFileName);
38377         }
38378         return options;
38379     }
38380     function getDefaultTypeAcquisition(configFileName) {
38381         return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
38382     }
38383     function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
38384         var options = getDefaultTypeAcquisition(configFileName);
38385         var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
38386         convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), typeAcquisition, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
38387         return options;
38388     }
38389     function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
38390         return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors);
38391     }
38392     function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
38393         if (!jsonOptions) {
38394             return;
38395         }
38396         for (var id in jsonOptions) {
38397             var opt = optionsNameMap.get(id);
38398             if (opt) {
38399                 (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
38400             }
38401             else {
38402                 errors.push(createUnknownOptionError(id, diagnostics, ts.createCompilerDiagnostic));
38403             }
38404         }
38405         return defaultOptions;
38406     }
38407     /*@internal*/
38408     function convertJsonOption(opt, value, basePath, errors) {
38409         if (isCompilerOptionsValue(opt, value)) {
38410             var optType = opt.type;
38411             if (optType === "list" && ts.isArray(value)) {
38412                 return convertJsonOptionOfListType(opt, value, basePath, errors);
38413             }
38414             else if (!ts.isString(optType)) {
38415                 return convertJsonOptionOfCustomType(opt, value, errors);
38416             }
38417             var validatedValue = validateJsonOptionValue(opt, value, errors);
38418             return isNullOrUndefined(validatedValue) ? validatedValue : normalizeNonListOptionValue(opt, basePath, validatedValue);
38419         }
38420         else {
38421             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
38422         }
38423     }
38424     ts.convertJsonOption = convertJsonOption;
38425     function normalizeOptionValue(option, basePath, value) {
38426         if (isNullOrUndefined(value))
38427             return undefined;
38428         if (option.type === "list") {
38429             var listOption_1 = option;
38430             if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
38431                 return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
38432             }
38433             return value;
38434         }
38435         else if (!ts.isString(option.type)) {
38436             return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
38437         }
38438         return normalizeNonListOptionValue(option, basePath, value);
38439     }
38440     function normalizeNonListOptionValue(option, basePath, value) {
38441         if (option.isFilePath) {
38442             value = ts.getNormalizedAbsolutePath(value, basePath);
38443             if (value === "") {
38444                 value = ".";
38445             }
38446         }
38447         return value;
38448     }
38449     function validateJsonOptionValue(opt, value, errors) {
38450         var _a;
38451         if (isNullOrUndefined(value))
38452             return undefined;
38453         var d = (_a = opt.extraValidation) === null || _a === void 0 ? void 0 : _a.call(opt, value);
38454         if (!d)
38455             return value;
38456         errors.push(ts.createCompilerDiagnostic.apply(void 0, d));
38457         return undefined;
38458     }
38459     function convertJsonOptionOfCustomType(opt, value, errors) {
38460         if (isNullOrUndefined(value))
38461             return undefined;
38462         var key = value.toLowerCase();
38463         var val = opt.type.get(key);
38464         if (val !== undefined) {
38465             return validateJsonOptionValue(opt, val, errors);
38466         }
38467         else {
38468             errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
38469         }
38470     }
38471     function convertJsonOptionOfListType(option, values, basePath, errors) {
38472         return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
38473     }
38474     function trimString(s) {
38475         return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, "");
38476     }
38477     /**
38478      * Tests for a path that ends in a recursive directory wildcard.
38479      * Matches **, \**, **\, and \**\, but not a**b.
38480      *
38481      * NOTE: used \ in place of / above to avoid issues with multiline comments.
38482      *
38483      * Breakdown:
38484      *  (^|\/)      # matches either the beginning of the string or a directory separator.
38485      *  \*\*        # matches the recursive directory wildcard "**".
38486      *  \/?$        # matches an optional trailing directory separator at the end of the string.
38487      */
38488     var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/;
38489     /**
38490      * Tests for a path where .. appears after a recursive directory wildcard.
38491      * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\*
38492      *
38493      * NOTE: used \ in place of / above to avoid issues with multiline comments.
38494      *
38495      * Breakdown:
38496      *  (^|\/)      # matches either the beginning of the string or a directory separator.
38497      *  \*\*\/      # matches a recursive directory wildcard "**" followed by a directory separator.
38498      *  (.*\/)?     # optionally matches any number of characters followed by a directory separator.
38499      *  \.\.        # matches a parent directory path component ".."
38500      *  ($|\/)      # matches either the end of the string or a directory separator.
38501      */
38502     var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/;
38503     /**
38504      * Tests for a path containing a wildcard character in a directory component of the path.
38505      * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*.
38506      *
38507      * NOTE: used \ in place of / above to avoid issues with multiline comments.
38508      *
38509      * Breakdown:
38510      *  \/          # matches a directory separator.
38511      *  [^/]*?      # matches any number of characters excluding directory separators (non-greedy).
38512      *  [*?]        # matches either a wildcard character (* or ?)
38513      *  [^/]*       # matches any number of characters excluding directory separators (greedy).
38514      *  \/          # matches a directory separator.
38515      */
38516     var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//;
38517     /**
38518      * Matches the portion of a wildcard path that does not contain wildcards.
38519      * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d.
38520      *
38521      * NOTE: used \ in place of / above to avoid issues with multiline comments.
38522      *
38523      * Breakdown:
38524      *  ^                   # matches the beginning of the string
38525      *  [^*?]*              # matches any number of non-wildcard characters
38526      *  (?=\/[^/]*[*?])     # lookahead that matches a directory separator followed by
38527      *                      # a path component that contains at least one wildcard character (* or ?).
38528      */
38529     var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
38530     /**
38531      * Gets the file names from the provided config file specs that contain, files, include, exclude and
38532      * other properties needed to resolve the file names
38533      * @param configFileSpecs The config file specs extracted with file names to include, wildcards to include/exclude and other details
38534      * @param basePath The base path for any relative file specifications.
38535      * @param options Compiler options.
38536      * @param host The host used to resolve files and directories.
38537      * @param extraFileExtensions optionaly file extra file extension information from host
38538      */
38539     /* @internal */
38540     function getFileNamesFromConfigSpecs(configFileSpecs, basePath, options, host, extraFileExtensions) {
38541         if (extraFileExtensions === void 0) { extraFileExtensions = ts.emptyArray; }
38542         basePath = ts.normalizePath(basePath);
38543         var keyMapper = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
38544         // Literal file names (provided via the "files" array in tsconfig.json) are stored in a
38545         // file map with a possibly case insensitive key. We use this map later when when including
38546         // wildcard paths.
38547         var literalFileMap = new ts.Map();
38548         // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
38549         // file map with a possibly case insensitive key. We use this map to store paths matched
38550         // via wildcard, and to handle extension priority.
38551         var wildcardFileMap = new ts.Map();
38552         // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a
38553         // file map with a possibly case insensitive key. We use this map to store paths matched
38554         // via wildcard of *.json kind
38555         var wildCardJsonFileMap = new ts.Map();
38556         var validatedFilesSpec = configFileSpecs.validatedFilesSpec, validatedIncludeSpecs = configFileSpecs.validatedIncludeSpecs, validatedExcludeSpecs = configFileSpecs.validatedExcludeSpecs;
38557         // Rather than requery this for each file and filespec, we query the supported extensions
38558         // once and store it on the expansion context.
38559         var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
38560         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
38561         // Literal files are always included verbatim. An "include" or "exclude" specification cannot
38562         // remove a literal file.
38563         if (validatedFilesSpec) {
38564             for (var _i = 0, validatedFilesSpec_1 = validatedFilesSpec; _i < validatedFilesSpec_1.length; _i++) {
38565                 var fileName = validatedFilesSpec_1[_i];
38566                 var file = ts.getNormalizedAbsolutePath(fileName, basePath);
38567                 literalFileMap.set(keyMapper(file), file);
38568             }
38569         }
38570         var jsonOnlyIncludeRegexes;
38571         if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
38572             var _loop_6 = function (file) {
38573                 if (ts.fileExtensionIs(file, ".json" /* Json */)) {
38574                     // Valid only if *.json specified
38575                     if (!jsonOnlyIncludeRegexes) {
38576                         var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); });
38577                         var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; });
38578                         jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray;
38579                     }
38580                     var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); });
38581                     if (includeIndex !== -1) {
38582                         var key_1 = keyMapper(file);
38583                         if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) {
38584                             wildCardJsonFileMap.set(key_1, file);
38585                         }
38586                     }
38587                     return "continue";
38588                 }
38589                 // If we have already included a literal or wildcard path with a
38590                 // higher priority extension, we should skip this file.
38591                 //
38592                 // This handles cases where we may encounter both <file>.ts and
38593                 // <file>.d.ts (or <file>.js if "allowJs" is enabled) in the same
38594                 // directory when they are compilation outputs.
38595                 if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
38596                     return "continue";
38597                 }
38598                 // We may have included a wildcard path with a lower priority
38599                 // extension due to the user-defined order of entries in the
38600                 // "include" array. If there is a lower priority extension in the
38601                 // same directory, we should remove it.
38602                 removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
38603                 var key = keyMapper(file);
38604                 if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
38605                     wildcardFileMap.set(key, file);
38606                 }
38607             };
38608             for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
38609                 var file = _b[_a];
38610                 _loop_6(file);
38611             }
38612         }
38613         var literalFiles = ts.arrayFrom(literalFileMap.values());
38614         var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
38615         return literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values()));
38616     }
38617     ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
38618     /* @internal */
38619     function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames, currentDirectory) {
38620         var validatedFilesSpec = spec.validatedFilesSpec, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs;
38621         if (!ts.length(validatedIncludeSpecs) || !ts.length(validatedExcludeSpecs))
38622             return false;
38623         basePath = ts.normalizePath(basePath);
38624         var keyMapper = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
38625         if (validatedFilesSpec) {
38626             for (var _i = 0, validatedFilesSpec_2 = validatedFilesSpec; _i < validatedFilesSpec_2.length; _i++) {
38627                 var fileName = validatedFilesSpec_2[_i];
38628                 if (keyMapper(ts.getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck)
38629                     return false;
38630             }
38631         }
38632         return matchesExcludeWorker(pathToCheck, validatedExcludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath);
38633     }
38634     ts.isExcludedFile = isExcludedFile;
38635     /* @internal */
38636     function matchesExclude(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory) {
38637         return matchesExcludeWorker(pathToCheck, ts.filter(excludeSpecs, function (spec) { return !invalidDotDotAfterRecursiveWildcardPattern.test(spec); }), useCaseSensitiveFileNames, currentDirectory);
38638     }
38639     ts.matchesExclude = matchesExclude;
38640     function matchesExcludeWorker(pathToCheck, excludeSpecs, useCaseSensitiveFileNames, currentDirectory, basePath) {
38641         var excludePattern = ts.getRegularExpressionForWildcard(excludeSpecs, ts.combinePaths(ts.normalizePath(currentDirectory), basePath), "exclude");
38642         var excludeRegex = excludePattern && ts.getRegexFromPattern(excludePattern, useCaseSensitiveFileNames);
38643         if (!excludeRegex)
38644             return false;
38645         if (excludeRegex.test(pathToCheck))
38646             return true;
38647         return !ts.hasExtension(pathToCheck) && excludeRegex.test(ts.ensureTrailingDirectorySeparator(pathToCheck));
38648     }
38649     function validateSpecs(specs, errors, disallowTrailingRecursion, jsonSourceFile, specKey) {
38650         return specs.filter(function (spec) {
38651             if (!ts.isString(spec))
38652                 return false;
38653             var diag = specToDiagnostic(spec, disallowTrailingRecursion);
38654             if (diag !== undefined) {
38655                 errors.push(createDiagnostic.apply(void 0, diag));
38656             }
38657             return diag === undefined;
38658         });
38659         function createDiagnostic(message, spec) {
38660             var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
38661             return element ?
38662                 ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
38663                 ts.createCompilerDiagnostic(message, spec);
38664         }
38665     }
38666     function specToDiagnostic(spec, disallowTrailingRecursion) {
38667         if (disallowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
38668             return [ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec];
38669         }
38670         else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) {
38671             return [ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, spec];
38672         }
38673     }
38674     /**
38675      * Gets directories in a set of include patterns that should be watched for changes.
38676      */
38677     function getWildcardDirectories(_a, path, useCaseSensitiveFileNames) {
38678         var include = _a.validatedIncludeSpecs, exclude = _a.validatedExcludeSpecs;
38679         // We watch a directory recursively if it contains a wildcard anywhere in a directory segment
38680         // of the pattern:
38681         //
38682         //  /a/b/**/d   - Watch /a/b recursively to catch changes to any d in any subfolder recursively
38683         //  /a/b/*/d    - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
38684         //  /a/b        - Watch /a/b recursively to catch changes to anything in any recursive subfoler
38685         //
38686         // We watch a directory without recursion if it contains a wildcard in the file segment of
38687         // the pattern:
38688         //
38689         //  /a/b/*      - Watch /a/b directly to catch any new file
38690         //  /a/b/a?z    - Watch /a/b directly to catch any new file matching a?z
38691         var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
38692         var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
38693         var wildcardDirectories = {};
38694         if (include !== undefined) {
38695             var recursiveKeys = [];
38696             for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
38697                 var file = include_1[_i];
38698                 var spec = ts.normalizePath(ts.combinePaths(path, file));
38699                 if (excludeRegex && excludeRegex.test(spec)) {
38700                     continue;
38701                 }
38702                 var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
38703                 if (match) {
38704                     var key = match.key, flags = match.flags;
38705                     var existingFlags = wildcardDirectories[key];
38706                     if (existingFlags === undefined || existingFlags < flags) {
38707                         wildcardDirectories[key] = flags;
38708                         if (flags === 1 /* Recursive */) {
38709                             recursiveKeys.push(key);
38710                         }
38711                     }
38712                 }
38713             }
38714             // Remove any subpaths under an existing recursively watched directory.
38715             for (var key in wildcardDirectories) {
38716                 if (ts.hasProperty(wildcardDirectories, key)) {
38717                     for (var _b = 0, recursiveKeys_1 = recursiveKeys; _b < recursiveKeys_1.length; _b++) {
38718                         var recursiveKey = recursiveKeys_1[_b];
38719                         if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
38720                             delete wildcardDirectories[key];
38721                         }
38722                     }
38723                 }
38724             }
38725         }
38726         return wildcardDirectories;
38727     }
38728     function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
38729         var match = wildcardDirectoryPattern.exec(spec);
38730         if (match) {
38731             return {
38732                 key: useCaseSensitiveFileNames ? match[0] : ts.toFileNameLowerCase(match[0]),
38733                 flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */
38734             };
38735         }
38736         if (ts.isImplicitGlob(spec)) {
38737             return {
38738                 key: useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec),
38739                 flags: 1 /* Recursive */
38740             };
38741         }
38742         return undefined;
38743     }
38744     /**
38745      * Determines whether a literal or wildcard file has already been included that has a higher
38746      * extension priority.
38747      *
38748      * @param file The path to the file.
38749      * @param extensionPriority The priority of the extension.
38750      * @param context The expansion context.
38751      */
38752     function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
38753         var extensionPriority = ts.getExtensionPriority(file, extensions);
38754         var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions);
38755         for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) {
38756             var higherPriorityExtension = extensions[i];
38757             var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
38758             if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
38759                 return true;
38760             }
38761         }
38762         return false;
38763     }
38764     /**
38765      * Removes files included via wildcard expansion with a lower extension priority that have
38766      * already been included.
38767      *
38768      * @param file The path to the file.
38769      * @param extensionPriority The priority of the extension.
38770      * @param context The expansion context.
38771      */
38772     function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
38773         var extensionPriority = ts.getExtensionPriority(file, extensions);
38774         var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions);
38775         for (var i = nextExtensionPriority; i < extensions.length; i++) {
38776             var lowerPriorityExtension = extensions[i];
38777             var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension));
38778             wildcardFiles.delete(lowerPriorityPath);
38779         }
38780     }
38781     /**
38782      * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed.
38783      * Also converts enum values back to strings.
38784      */
38785     /* @internal */
38786     function convertCompilerOptionsForTelemetry(opts) {
38787         var out = {};
38788         for (var key in opts) {
38789             if (opts.hasOwnProperty(key)) {
38790                 var type = getOptionFromName(key);
38791                 if (type !== undefined) { // Ignore unknown options
38792                     out[key] = getOptionValueWithEmptyStrings(opts[key], type);
38793                 }
38794             }
38795         }
38796         return out;
38797     }
38798     ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
38799     function getOptionValueWithEmptyStrings(value, option) {
38800         switch (option.type) {
38801             case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
38802                 return "";
38803             case "string": // Could be any arbitrary string -- use empty string instead.
38804                 return "";
38805             case "number": // Allow numbers, but be sure to check it's actually a number.
38806                 return typeof value === "number" ? value : "";
38807             case "boolean":
38808                 return typeof value === "boolean" ? value : "";
38809             case "list":
38810                 var elementType_1 = option.element;
38811                 return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
38812             default:
38813                 return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
38814                     if (optionEnumValue === value) {
38815                         return optionStringValue;
38816                     }
38817                 }); // TODO: GH#18217
38818         }
38819     }
38820 })(ts || (ts = {}));
38821 var ts;
38822 (function (ts) {
38823     function trace(host) {
38824         host.trace(ts.formatMessage.apply(undefined, arguments));
38825     }
38826     ts.trace = trace;
38827     /* @internal */
38828     function isTraceEnabled(compilerOptions, host) {
38829         return !!compilerOptions.traceResolution && host.trace !== undefined;
38830     }
38831     ts.isTraceEnabled = isTraceEnabled;
38832     function withPackageId(packageInfo, r) {
38833         var packageId;
38834         if (r && packageInfo) {
38835             var packageJsonContent = packageInfo.packageJsonContent;
38836             if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
38837                 packageId = {
38838                     name: packageJsonContent.name,
38839                     subModuleName: r.path.slice(packageInfo.packageDirectory.length + ts.directorySeparator.length),
38840                     version: packageJsonContent.version
38841                 };
38842             }
38843         }
38844         return r && { path: r.path, extension: r.ext, packageId: packageId };
38845     }
38846     function noPackageId(r) {
38847         return withPackageId(/*packageInfo*/ undefined, r);
38848     }
38849     function removeIgnoredPackageId(r) {
38850         if (r) {
38851             ts.Debug.assert(r.packageId === undefined);
38852             return { path: r.path, ext: r.extension };
38853         }
38854     }
38855     /**
38856      * Kinds of file that we are currently looking for.
38857      * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
38858      */
38859     var Extensions;
38860     (function (Extensions) {
38861         Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
38862         Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
38863         Extensions[Extensions["Json"] = 2] = "Json";
38864         Extensions[Extensions["TSConfig"] = 3] = "TSConfig";
38865         Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */
38866     })(Extensions || (Extensions = {}));
38867     /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
38868     function resolvedTypeScriptOnly(resolved) {
38869         if (!resolved) {
38870             return undefined;
38871         }
38872         ts.Debug.assert(ts.extensionIsTS(resolved.extension));
38873         return { fileName: resolved.path, packageId: resolved.packageId };
38874     }
38875     function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, resultFromCache) {
38876         var _a;
38877         if (resultFromCache) {
38878             (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations);
38879             return resultFromCache;
38880         }
38881         return {
38882             resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
38883             failedLookupLocations: failedLookupLocations
38884         };
38885     }
38886     function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
38887         if (!ts.hasProperty(jsonContent, fieldName)) {
38888             if (state.traceEnabled) {
38889                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
38890             }
38891             return;
38892         }
38893         var value = jsonContent[fieldName];
38894         if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-null/no-null
38895             if (state.traceEnabled) {
38896                 // eslint-disable-next-line no-null/no-null
38897                 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);
38898             }
38899             return;
38900         }
38901         return value;
38902     }
38903     function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
38904         var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
38905         if (fileName === undefined) {
38906             return;
38907         }
38908         if (!fileName) {
38909             if (state.traceEnabled) {
38910                 trace(state.host, ts.Diagnostics.package_json_had_a_falsy_0_field, fieldName);
38911             }
38912             return;
38913         }
38914         var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
38915         if (state.traceEnabled) {
38916             trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
38917         }
38918         return path;
38919     }
38920     function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
38921         return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
38922             || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
38923     }
38924     function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
38925         return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
38926     }
38927     function readPackageJsonMainField(jsonContent, baseDirectory, state) {
38928         return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
38929     }
38930     function readPackageJsonTypesVersionsField(jsonContent, state) {
38931         var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
38932         if (typesVersions === undefined)
38933             return;
38934         if (state.traceEnabled) {
38935             trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
38936         }
38937         return typesVersions;
38938     }
38939     function readPackageJsonTypesVersionPaths(jsonContent, state) {
38940         var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
38941         if (typesVersions === undefined)
38942             return;
38943         if (state.traceEnabled) {
38944             for (var key in typesVersions) {
38945                 if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
38946                     trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
38947                 }
38948             }
38949         }
38950         var result = getPackageJsonTypesVersionsPaths(typesVersions);
38951         if (!result) {
38952             if (state.traceEnabled) {
38953                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
38954             }
38955             return;
38956         }
38957         var bestVersionKey = result.version, bestVersionPaths = result.paths;
38958         if (typeof bestVersionPaths !== "object") {
38959             if (state.traceEnabled) {
38960                 trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths);
38961             }
38962             return;
38963         }
38964         return result;
38965     }
38966     var typeScriptVersion;
38967     /* @internal */
38968     function getPackageJsonTypesVersionsPaths(typesVersions) {
38969         if (!typeScriptVersion)
38970             typeScriptVersion = new ts.Version(ts.version);
38971         for (var key in typesVersions) {
38972             if (!ts.hasProperty(typesVersions, key))
38973                 continue;
38974             var keyRange = ts.VersionRange.tryParse(key);
38975             if (keyRange === undefined) {
38976                 continue;
38977             }
38978             // return the first entry whose range matches the current compiler version.
38979             if (keyRange.test(typeScriptVersion)) {
38980                 return { version: key, paths: typesVersions[key] };
38981             }
38982         }
38983     }
38984     ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
38985     function getEffectiveTypeRoots(options, host) {
38986         if (options.typeRoots) {
38987             return options.typeRoots;
38988         }
38989         var currentDirectory;
38990         if (options.configFilePath) {
38991             currentDirectory = ts.getDirectoryPath(options.configFilePath);
38992         }
38993         else if (host.getCurrentDirectory) {
38994             currentDirectory = host.getCurrentDirectory();
38995         }
38996         if (currentDirectory !== undefined) {
38997             return getDefaultTypeRoots(currentDirectory, host);
38998         }
38999     }
39000     ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
39001     /**
39002      * Returns the path to every node_modules/@types directory from some ancestor directory.
39003      * Returns undefined if there are none.
39004      */
39005     function getDefaultTypeRoots(currentDirectory, host) {
39006         if (!host.directoryExists) {
39007             return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
39008             // And if it doesn't exist, tough.
39009         }
39010         var typeRoots;
39011         ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
39012             var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
39013             if (host.directoryExists(atTypes)) {
39014                 (typeRoots || (typeRoots = [])).push(atTypes);
39015             }
39016             return undefined;
39017         });
39018         return typeRoots;
39019     }
39020     var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
39021     /**
39022      * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
39023      * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
39024      * is assumed to be the same as root directory of the project.
39025      */
39026     function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) {
39027         var traceEnabled = isTraceEnabled(options, host);
39028         if (redirectedReference) {
39029             options = redirectedReference.commandLine.options;
39030         }
39031         var failedLookupLocations = [];
39032         var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
39033         var typeRoots = getEffectiveTypeRoots(options, host);
39034         if (traceEnabled) {
39035             if (containingFile === undefined) {
39036                 if (typeRoots === undefined) {
39037                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
39038                 }
39039                 else {
39040                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
39041                 }
39042             }
39043             else {
39044                 if (typeRoots === undefined) {
39045                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
39046                 }
39047                 else {
39048                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
39049                 }
39050             }
39051             if (redirectedReference) {
39052                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
39053             }
39054         }
39055         var resolved = primaryLookup();
39056         var primary = true;
39057         if (!resolved) {
39058             resolved = secondaryLookup();
39059             primary = false;
39060         }
39061         var resolvedTypeReferenceDirective;
39062         if (resolved) {
39063             var fileName = resolved.fileName, packageId = resolved.packageId;
39064             var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
39065             if (traceEnabled) {
39066                 if (packageId) {
39067                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_with_Package_ID_2_primary_Colon_3, typeReferenceDirectiveName, resolvedFileName, ts.packageIdToString(packageId), primary);
39068                 }
39069                 else {
39070                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
39071                 }
39072             }
39073             resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) };
39074         }
39075         return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
39076         function primaryLookup() {
39077             // Check primary library paths
39078             if (typeRoots && typeRoots.length) {
39079                 if (traceEnabled) {
39080                     trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
39081                 }
39082                 return ts.firstDefined(typeRoots, function (typeRoot) {
39083                     var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
39084                     var candidateDirectory = ts.getDirectoryPath(candidate);
39085                     var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
39086                     if (!directoryExists && traceEnabled) {
39087                         trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
39088                     }
39089                     return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
39090                 });
39091             }
39092             else {
39093                 if (traceEnabled) {
39094                     trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
39095                 }
39096             }
39097         }
39098         function secondaryLookup() {
39099             var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
39100             if (initialLocationForSecondaryLookup !== undefined) {
39101                 // check secondary locations
39102                 if (traceEnabled) {
39103                     trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
39104                 }
39105                 var result = void 0;
39106                 if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) {
39107                     var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
39108                     result = searchResult && searchResult.value;
39109                 }
39110                 else {
39111                     var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
39112                     result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
39113                 }
39114                 var resolvedFile = resolvedTypeScriptOnly(result);
39115                 if (!resolvedFile && traceEnabled) {
39116                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
39117                 }
39118                 return resolvedFile;
39119             }
39120             else {
39121                 if (traceEnabled) {
39122                     trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
39123                 }
39124             }
39125         }
39126     }
39127     ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
39128     /**
39129      * Given a set of options, returns the set of type directive names
39130      *   that should be included for this program automatically.
39131      * This list could either come from the config file,
39132      *   or from enumerating the types root + initial secondary types lookup location.
39133      * More type directives might appear in the program later as a result of loading actual source files;
39134      *   this list is only the set of defaults that are implicitly included.
39135      */
39136     function getAutomaticTypeDirectiveNames(options, host) {
39137         // Use explicit type list from tsconfig.json
39138         if (options.types) {
39139             return options.types;
39140         }
39141         // Walk the primary type lookup locations
39142         var result = [];
39143         if (host.directoryExists && host.getDirectories) {
39144             var typeRoots = getEffectiveTypeRoots(options, host);
39145             if (typeRoots) {
39146                 for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
39147                     var root = typeRoots_1[_i];
39148                     if (host.directoryExists(root)) {
39149                         for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
39150                             var typeDirectivePath = _b[_a];
39151                             var normalized = ts.normalizePath(typeDirectivePath);
39152                             var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
39153                             // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
39154                             // See `createNotNeededPackageJSON` in the types-publisher` repo.
39155                             // eslint-disable-next-line no-null/no-null
39156                             var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
39157                             if (!isNotNeededPackage) {
39158                                 var baseFileName = ts.getBaseFileName(normalized);
39159                                 // At this stage, skip results with leading dot.
39160                                 if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
39161                                     // Return just the type directive names
39162                                     result.push(baseFileName);
39163                                 }
39164                             }
39165                         }
39166                     }
39167                 }
39168             }
39169         }
39170         return result;
39171     }
39172     ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
39173     function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) {
39174         return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName);
39175     }
39176     ts.createModuleResolutionCache = createModuleResolutionCache;
39177     /*@internal*/
39178     function createCacheWithRedirects(options) {
39179         var ownMap = new ts.Map();
39180         var redirectsMap = new ts.Map();
39181         return {
39182             ownMap: ownMap,
39183             redirectsMap: redirectsMap,
39184             getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects,
39185             clear: clear,
39186             setOwnOptions: setOwnOptions,
39187             setOwnMap: setOwnMap
39188         };
39189         function setOwnOptions(newOptions) {
39190             options = newOptions;
39191         }
39192         function setOwnMap(newOwnMap) {
39193             ownMap = newOwnMap;
39194         }
39195         function getOrCreateMapOfCacheRedirects(redirectedReference) {
39196             if (!redirectedReference) {
39197                 return ownMap;
39198             }
39199             var path = redirectedReference.sourceFile.path;
39200             var redirects = redirectsMap.get(path);
39201             if (!redirects) {
39202                 // Reuse map if redirected reference map uses same resolution
39203                 redirects = !options || ts.optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? new ts.Map() : ownMap;
39204                 redirectsMap.set(path, redirects);
39205             }
39206             return redirects;
39207         }
39208         function clear() {
39209             ownMap.clear();
39210             redirectsMap.clear();
39211         }
39212     }
39213     ts.createCacheWithRedirects = createCacheWithRedirects;
39214     /*@internal*/
39215     function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
39216         return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap };
39217         function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
39218             var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
39219             return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); });
39220         }
39221         function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) {
39222             ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
39223             return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache);
39224         }
39225         function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
39226             var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
39227             var result = cache.get(key);
39228             if (!result) {
39229                 result = create();
39230                 cache.set(key, result);
39231             }
39232             return result;
39233         }
39234         function createPerModuleNameCache() {
39235             var directoryPathMap = new ts.Map();
39236             return { get: get, set: set };
39237             function get(directory) {
39238                 return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
39239             }
39240             /**
39241              * At first this function add entry directory -> module resolution result to the table.
39242              * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
39243              * and for every parent folder in set it adds entry: parent -> module resolution. .
39244              * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
39245              * Set of parent folders that should have the same result will be:
39246              * [
39247              *     /a/b/c/d, /a/b/c, /a/b
39248              * ]
39249              * this means that request for module resolution from file in any of these folder will be immediately found in cache.
39250              */
39251             function set(directory, result) {
39252                 var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
39253                 // if entry is already in cache do nothing
39254                 if (directoryPathMap.has(path)) {
39255                     return;
39256                 }
39257                 directoryPathMap.set(path, result);
39258                 var resolvedFileName = result.resolvedModule &&
39259                     (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
39260                 // find common prefix between directory and resolved file name
39261                 // this common prefix should be the shortest path that has the same resolution
39262                 // directory: /a/b/c/d/e
39263                 // resolvedFileName: /a/b/foo.d.ts
39264                 // commonPrefix: /a/b
39265                 // for failed lookups cache the result for every directory up to root
39266                 var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
39267                 var current = path;
39268                 while (current !== commonPrefix) {
39269                     var parent = ts.getDirectoryPath(current);
39270                     if (parent === current || directoryPathMap.has(parent)) {
39271                         break;
39272                     }
39273                     directoryPathMap.set(parent, result);
39274                     current = parent;
39275                 }
39276             }
39277             function getCommonPrefix(directory, resolution) {
39278                 var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
39279                 // find first position where directory and resolution differs
39280                 var i = 0;
39281                 var limit = Math.min(directory.length, resolutionDirectory.length);
39282                 while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
39283                     i++;
39284                 }
39285                 if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
39286                     return directory;
39287                 }
39288                 var rootLength = ts.getRootLength(directory);
39289                 if (i < rootLength) {
39290                     return undefined;
39291                 }
39292                 var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
39293                 if (sep === -1) {
39294                     return undefined;
39295                 }
39296                 return directory.substr(0, Math.max(sep, rootLength));
39297             }
39298         }
39299     }
39300     ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
39301     function resolveModuleNameFromCache(moduleName, containingFile, cache) {
39302         var containingDirectory = ts.getDirectoryPath(containingFile);
39303         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
39304         return perFolderCache && perFolderCache.get(moduleName);
39305     }
39306     ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
39307     function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
39308         var traceEnabled = isTraceEnabled(compilerOptions, host);
39309         if (redirectedReference) {
39310             compilerOptions = redirectedReference.commandLine.options;
39311         }
39312         if (traceEnabled) {
39313             trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
39314             if (redirectedReference) {
39315                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
39316             }
39317         }
39318         var containingDirectory = ts.getDirectoryPath(containingFile);
39319         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
39320         var result = perFolderCache && perFolderCache.get(moduleName);
39321         if (result) {
39322             if (traceEnabled) {
39323                 trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
39324             }
39325         }
39326         else {
39327             var moduleResolution = compilerOptions.moduleResolution;
39328             if (moduleResolution === undefined) {
39329                 moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
39330                 if (traceEnabled) {
39331                     trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
39332                 }
39333             }
39334             else {
39335                 if (traceEnabled) {
39336                     trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
39337                 }
39338             }
39339             ts.perfLogger.logStartResolveModule(moduleName /* , containingFile, ModuleResolutionKind[moduleResolution]*/);
39340             switch (moduleResolution) {
39341                 case ts.ModuleResolutionKind.NodeJs:
39342                     result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
39343                     break;
39344                 case ts.ModuleResolutionKind.Classic:
39345                     result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
39346                     break;
39347                 default:
39348                     return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution);
39349             }
39350             if (result && result.resolvedModule)
39351                 ts.perfLogger.logInfoEvent("Module \"" + moduleName + "\" resolved to \"" + result.resolvedModule.resolvedFileName + "\"");
39352             ts.perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null");
39353             if (perFolderCache) {
39354                 perFolderCache.set(moduleName, result);
39355                 if (!ts.isExternalModuleNameRelative(moduleName)) {
39356                     // put result in per-module name cache
39357                     cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result);
39358                 }
39359             }
39360         }
39361         if (traceEnabled) {
39362             if (result.resolvedModule) {
39363                 if (result.resolvedModule.packageId) {
39364                     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));
39365                 }
39366                 else {
39367                     trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
39368                 }
39369             }
39370             else {
39371                 trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
39372             }
39373         }
39374         return result;
39375     }
39376     ts.resolveModuleName = resolveModuleName;
39377     /**
39378      * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
39379      * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
39380      * can be resolved successfully by TypeScript compiler and runtime module loader.
39381      * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
39382      * fallback to standard resolution routine.
39383      *
39384      * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
39385      * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
39386      * be '/a/b/c/d'
39387      * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
39388      * will be resolved based on the content of the module name.
39389      * Structure of 'paths' compiler options
39390      * 'paths': {
39391      *    pattern-1: [...substitutions],
39392      *    pattern-2: [...substitutions],
39393      *    ...
39394      *    pattern-n: [...substitutions]
39395      * }
39396      * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
39397      * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
39398      * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
39399      * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
39400      * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
39401      * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
39402      * from the candidate location.
39403      * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
39404      * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
39405      * will be converted to absolute using baseUrl.
39406      * For example:
39407      * baseUrl: /a/b/c
39408      * "paths": {
39409      *     // match all module names
39410      *     "*": [
39411      *         "*",        // use matched name as is,
39412      *                     // <matched name> will be looked as /a/b/c/<matched name>
39413      *
39414      *         "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
39415      *                     // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
39416      *     ],
39417      *     // match module names that start with 'components/'
39418      *     "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
39419      *                                              // it is rooted so it will be final candidate location
39420      * }
39421      *
39422      * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
39423      * they were in the same location. For example lets say there are two files
39424      * '/local/src/content/file1.ts'
39425      * '/shared/components/contracts/src/content/protocols/file2.ts'
39426      * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
39427      * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
39428      * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
39429      * root dirs were merged together.
39430      * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
39431      * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
39432      * '/local/src/content/protocols/file2' and try to load it - failure.
39433      * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
39434      * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
39435      * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
39436      */
39437     function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
39438         var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
39439         if (resolved)
39440             return resolved.value;
39441         if (!ts.isExternalModuleNameRelative(moduleName)) {
39442             return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
39443         }
39444         else {
39445             return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
39446         }
39447     }
39448     function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
39449         var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths;
39450         if (paths && !ts.pathIsRelative(moduleName)) {
39451             if (state.traceEnabled) {
39452                 if (baseUrl) {
39453                     trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
39454                 }
39455                 trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
39456             }
39457             var baseDirectory = ts.getPathsBasePath(state.compilerOptions, state.host); // Always defined when 'paths' is defined
39458             return tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, /*onlyRecordFailures*/ false, state);
39459         }
39460     }
39461     function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
39462         if (!state.compilerOptions.rootDirs) {
39463             return undefined;
39464         }
39465         if (state.traceEnabled) {
39466             trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
39467         }
39468         var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
39469         var matchedRootDir;
39470         var matchedNormalizedPrefix;
39471         for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
39472             var rootDir = _a[_i];
39473             // rootDirs are expected to be absolute
39474             // in case of tsconfig.json this will happen automatically - compiler will expand relative names
39475             // using location of tsconfig.json as base location
39476             var normalizedRoot = ts.normalizePath(rootDir);
39477             if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
39478                 normalizedRoot += ts.directorySeparator;
39479             }
39480             var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
39481                 (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
39482             if (state.traceEnabled) {
39483                 trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
39484             }
39485             if (isLongestMatchingPrefix) {
39486                 matchedNormalizedPrefix = normalizedRoot;
39487                 matchedRootDir = rootDir;
39488             }
39489         }
39490         if (matchedNormalizedPrefix) {
39491             if (state.traceEnabled) {
39492                 trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
39493             }
39494             var suffix = candidate.substr(matchedNormalizedPrefix.length);
39495             // first - try to load from a initial location
39496             if (state.traceEnabled) {
39497                 trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
39498             }
39499             var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
39500             if (resolvedFileName) {
39501                 return resolvedFileName;
39502             }
39503             if (state.traceEnabled) {
39504                 trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
39505             }
39506             // then try to resolve using remaining entries in rootDirs
39507             for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
39508                 var rootDir = _c[_b];
39509                 if (rootDir === matchedRootDir) {
39510                     // skip the initially matched entry
39511                     continue;
39512                 }
39513                 var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
39514                 if (state.traceEnabled) {
39515                     trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
39516                 }
39517                 var baseDirectory = ts.getDirectoryPath(candidate_1);
39518                 var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
39519                 if (resolvedFileName_1) {
39520                     return resolvedFileName_1;
39521                 }
39522             }
39523             if (state.traceEnabled) {
39524                 trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
39525             }
39526         }
39527         return undefined;
39528     }
39529     function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
39530         var baseUrl = state.compilerOptions.baseUrl;
39531         if (!baseUrl) {
39532             return undefined;
39533         }
39534         if (state.traceEnabled) {
39535             trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
39536         }
39537         var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
39538         if (state.traceEnabled) {
39539             trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
39540         }
39541         return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
39542     }
39543     /**
39544      * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
39545      * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
39546      * Throws an error if the module can't be resolved.
39547      */
39548     /* @internal */
39549     function resolveJSModule(moduleName, initialDir, host) {
39550         var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
39551         if (!resolvedModule) {
39552             throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", "));
39553         }
39554         return resolvedModule.resolvedFileName;
39555     }
39556     ts.resolveJSModule = resolveJSModule;
39557     /* @internal */
39558     function tryResolveJSModule(moduleName, initialDir, host) {
39559         var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
39560         return resolvedModule && resolvedModule.resolvedFileName;
39561     }
39562     ts.tryResolveJSModule = tryResolveJSModule;
39563     var jsOnlyExtensions = [Extensions.JavaScript];
39564     var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
39565     var tsPlusJsonExtensions = __spreadArray(__spreadArray([], tsExtensions), [Extensions.Json]);
39566     var tsconfigExtensions = [Extensions.TSConfig];
39567     function tryResolveJSModuleWorker(moduleName, initialDir, host) {
39568         return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
39569     }
39570     function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) {
39571         return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
39572     }
39573     ts.nodeModuleNameResolver = nodeModuleNameResolver;
39574     function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) {
39575         var _a, _b;
39576         var traceEnabled = isTraceEnabled(compilerOptions, host);
39577         var failedLookupLocations = [];
39578         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
39579         var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); });
39580         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);
39581         function tryResolve(extensions) {
39582             var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
39583             var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
39584             if (resolved) {
39585                 return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
39586             }
39587             if (!ts.isExternalModuleNameRelative(moduleName)) {
39588                 if (traceEnabled) {
39589                     trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
39590                 }
39591                 var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
39592                 if (!resolved_1)
39593                     return undefined;
39594                 var resolvedValue = resolved_1.value;
39595                 if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
39596                     var path = realPath(resolvedValue.path, host, traceEnabled);
39597                     var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path;
39598                     resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath });
39599                 }
39600                 // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
39601                 return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
39602             }
39603             else {
39604                 var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
39605                 var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
39606                 // Treat explicit "node_modules" import as an external library import.
39607                 return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
39608             }
39609         }
39610     }
39611     function realPath(path, host, traceEnabled) {
39612         if (!host.realpath) {
39613             return path;
39614         }
39615         var real = ts.normalizePath(host.realpath(path));
39616         if (traceEnabled) {
39617             trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
39618         }
39619         ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real);
39620         return real;
39621     }
39622     function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
39623         if (state.traceEnabled) {
39624             trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
39625         }
39626         if (!ts.hasTrailingDirectorySeparator(candidate)) {
39627             if (!onlyRecordFailures) {
39628                 var parentOfCandidate = ts.getDirectoryPath(candidate);
39629                 if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
39630                     if (state.traceEnabled) {
39631                         trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
39632                     }
39633                     onlyRecordFailures = true;
39634                 }
39635             }
39636             var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
39637             if (resolvedFromFile) {
39638                 var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
39639                 var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
39640                 return withPackageId(packageInfo, resolvedFromFile);
39641             }
39642         }
39643         if (!onlyRecordFailures) {
39644             var candidateExists = ts.directoryProbablyExists(candidate, state.host);
39645             if (!candidateExists) {
39646                 if (state.traceEnabled) {
39647                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
39648                 }
39649                 onlyRecordFailures = true;
39650             }
39651         }
39652         return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
39653     }
39654     /*@internal*/
39655     ts.nodeModulesPathPart = "/node_modules/";
39656     /*@internal*/
39657     function pathContainsNodeModules(path) {
39658         return ts.stringContains(path, ts.nodeModulesPathPart);
39659     }
39660     ts.pathContainsNodeModules = pathContainsNodeModules;
39661     /**
39662      * This will be called on the successfully resolved path from `loadModuleFromFile`.
39663      * (Not needed for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
39664      *
39665      * packageDirectory is the directory of the package itself.
39666      *   For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
39667      *   For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
39668      *   For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
39669      *   For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
39670      */
39671     function parseNodeModuleFromPath(resolved) {
39672         var path = ts.normalizePath(resolved.path);
39673         var idx = path.lastIndexOf(ts.nodeModulesPathPart);
39674         if (idx === -1) {
39675             return undefined;
39676         }
39677         var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
39678         var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
39679         if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
39680             indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
39681         }
39682         return path.slice(0, indexAfterPackageName);
39683     }
39684     function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
39685         var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
39686         return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
39687     }
39688     function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
39689         return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
39690     }
39691     /**
39692      * @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
39693      * 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.
39694      */
39695     function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
39696         if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
39697             var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
39698             return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state);
39699         }
39700         // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
39701         var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
39702         if (resolvedByAddingExtension) {
39703             return resolvedByAddingExtension;
39704         }
39705         // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
39706         // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
39707         if (ts.hasJSFileExtension(candidate)) {
39708             var extensionless = ts.removeFileExtension(candidate);
39709             if (state.traceEnabled) {
39710                 var extension = candidate.substring(extensionless.length);
39711                 trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
39712             }
39713             return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
39714         }
39715     }
39716     /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
39717     function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) {
39718         if (!onlyRecordFailures) {
39719             // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
39720             var directory = ts.getDirectoryPath(candidate);
39721             if (directory) {
39722                 onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
39723             }
39724         }
39725         switch (extensions) {
39726             case Extensions.DtsOnly:
39727                 return tryExtension(".d.ts" /* Dts */);
39728             case Extensions.TypeScript:
39729                 return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
39730             case Extensions.JavaScript:
39731                 return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
39732             case Extensions.TSConfig:
39733             case Extensions.Json:
39734                 return tryExtension(".json" /* Json */);
39735         }
39736         function tryExtension(ext) {
39737             var path = tryFile(candidate + ext, onlyRecordFailures, state);
39738             return path === undefined ? undefined : { path: path, ext: ext };
39739         }
39740     }
39741     /** Return the file if it exists. */
39742     function tryFile(fileName, onlyRecordFailures, state) {
39743         if (!onlyRecordFailures) {
39744             if (state.host.fileExists(fileName)) {
39745                 if (state.traceEnabled) {
39746                     trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
39747                 }
39748                 return fileName;
39749             }
39750             else {
39751                 if (state.traceEnabled) {
39752                     trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
39753                 }
39754             }
39755         }
39756         state.failedLookupLocations.push(fileName);
39757         return undefined;
39758     }
39759     function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
39760         if (considerPackageJson === void 0) { considerPackageJson = true; }
39761         var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
39762         var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
39763         var versionPaths = packageInfo && packageInfo.versionPaths;
39764         return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
39765     }
39766     function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
39767         var host = state.host, traceEnabled = state.traceEnabled;
39768         var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host);
39769         var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
39770         if (directoryExists && host.fileExists(packageJsonPath)) {
39771             var packageJsonContent = ts.readJson(packageJsonPath, host);
39772             if (traceEnabled) {
39773                 trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
39774             }
39775             var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
39776             return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths };
39777         }
39778         else {
39779             if (directoryExists && traceEnabled) {
39780                 trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
39781             }
39782             // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
39783             state.failedLookupLocations.push(packageJsonPath);
39784         }
39785     }
39786     function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
39787         var packageFile;
39788         if (jsonContent) {
39789             switch (extensions) {
39790                 case Extensions.JavaScript:
39791                 case Extensions.Json:
39792                     packageFile = readPackageJsonMainField(jsonContent, candidate, state);
39793                     break;
39794                 case Extensions.TypeScript:
39795                     // When resolving typescript modules, try resolving using main field as well
39796                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
39797                     break;
39798                 case Extensions.DtsOnly:
39799                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
39800                     break;
39801                 case Extensions.TSConfig:
39802                     packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
39803                     break;
39804                 default:
39805                     return ts.Debug.assertNever(extensions);
39806             }
39807         }
39808         var loader = function (extensions, candidate, onlyRecordFailures, state) {
39809             var fromFile = tryFile(candidate, onlyRecordFailures, state);
39810             if (fromFile) {
39811                 var resolved = resolvedIfExtensionMatches(extensions, fromFile);
39812                 if (resolved) {
39813                     return noPackageId(resolved);
39814                 }
39815                 if (state.traceEnabled) {
39816                     trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
39817                 }
39818             }
39819             // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
39820             var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
39821             // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
39822             return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
39823         };
39824         var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
39825         var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
39826         var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
39827         if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) {
39828             var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
39829             if (state.traceEnabled) {
39830                 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);
39831             }
39832             var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
39833             if (result) {
39834                 return removeIgnoredPackageId(result.value);
39835             }
39836         }
39837         // It won't have a `packageId` set, because we disabled `considerPackageJson`.
39838         var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
39839         if (packageFileResult)
39840             return packageFileResult;
39841         return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
39842     }
39843     /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
39844     function resolvedIfExtensionMatches(extensions, path) {
39845         var ext = ts.tryGetExtensionFromPath(path);
39846         return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
39847     }
39848     /** True if `extension` is one of the supported `extensions`. */
39849     function extensionIsOk(extensions, extension) {
39850         switch (extensions) {
39851             case Extensions.JavaScript:
39852                 return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
39853             case Extensions.TSConfig:
39854             case Extensions.Json:
39855                 return extension === ".json" /* Json */;
39856             case Extensions.TypeScript:
39857                 return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
39858             case Extensions.DtsOnly:
39859                 return extension === ".d.ts" /* Dts */;
39860         }
39861     }
39862     /* @internal */
39863     function parsePackageName(moduleName) {
39864         var idx = moduleName.indexOf(ts.directorySeparator);
39865         if (moduleName[0] === "@") {
39866             idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
39867         }
39868         return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
39869     }
39870     ts.parsePackageName = parsePackageName;
39871     function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
39872         return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
39873     }
39874     function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
39875         // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
39876         return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
39877     }
39878     function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
39879         var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
39880         return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
39881             if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
39882                 var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
39883                 if (resolutionFromCache) {
39884                     return resolutionFromCache;
39885                 }
39886                 return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
39887             }
39888         });
39889     }
39890     function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) {
39891         var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
39892         var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
39893         if (!nodeModulesFolderExists && state.traceEnabled) {
39894             trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
39895         }
39896         var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
39897         if (packageResult) {
39898             return packageResult;
39899         }
39900         if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
39901             var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
39902             var nodeModulesAtTypesExists = nodeModulesFolderExists;
39903             if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
39904                 if (state.traceEnabled) {
39905                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
39906                 }
39907                 nodeModulesAtTypesExists = false;
39908             }
39909             return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state);
39910         }
39911     }
39912     function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) {
39913         var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
39914         // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
39915         var packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
39916         if (packageInfo) {
39917             var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
39918             if (fromFile) {
39919                 return noPackageId(fromFile);
39920             }
39921             var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
39922             return withPackageId(packageInfo, fromDirectory);
39923         }
39924         var loader = function (extensions, candidate, onlyRecordFailures, state) {
39925             var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
39926                 loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
39927             return withPackageId(packageInfo, pathAndExtension);
39928         };
39929         var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
39930         if (rest !== "") { // If "rest" is empty, we just did this search above.
39931             var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
39932             // 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.
39933             packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
39934             if (packageInfo && packageInfo.versionPaths) {
39935                 if (state.traceEnabled) {
39936                     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);
39937                 }
39938                 var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
39939                 var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, loader, !packageDirectoryExists, state);
39940                 if (fromPaths) {
39941                     return fromPaths.value;
39942                 }
39943             }
39944         }
39945         return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
39946     }
39947     function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) {
39948         var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName);
39949         if (matchedPattern) {
39950             var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
39951             var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
39952             if (state.traceEnabled) {
39953                 trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
39954             }
39955             var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
39956                 var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
39957                 // When baseUrl is not specified, the command line parser resolves relative paths to the config file location.
39958                 var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
39959                 if (state.traceEnabled) {
39960                     trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
39961                 }
39962                 // A path mapping may have an extension, in contrast to an import, which should omit it.
39963                 var extension = ts.tryGetExtensionFromPath(subst);
39964                 if (extension !== undefined) {
39965                     var path_1 = tryFile(candidate, onlyRecordFailures, state);
39966                     if (path_1 !== undefined) {
39967                         return noPackageId({ path: path_1, ext: extension });
39968                     }
39969                 }
39970                 return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
39971             });
39972             return { value: resolved };
39973         }
39974     }
39975     /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
39976     var mangledScopedPackageSeparator = "__";
39977     /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
39978     function mangleScopedPackageNameWithTrace(packageName, state) {
39979         var mangled = mangleScopedPackageName(packageName);
39980         if (state.traceEnabled && mangled !== packageName) {
39981             trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
39982         }
39983         return mangled;
39984     }
39985     /* @internal */
39986     function getTypesPackageName(packageName) {
39987         return "@types/" + mangleScopedPackageName(packageName);
39988     }
39989     ts.getTypesPackageName = getTypesPackageName;
39990     /* @internal */
39991     function mangleScopedPackageName(packageName) {
39992         if (ts.startsWith(packageName, "@")) {
39993             var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
39994             if (replaceSlash !== packageName) {
39995                 return replaceSlash.slice(1); // Take off the "@"
39996             }
39997         }
39998         return packageName;
39999     }
40000     ts.mangleScopedPackageName = mangleScopedPackageName;
40001     /* @internal */
40002     function getPackageNameFromTypesPackageName(mangledName) {
40003         var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
40004         if (withoutAtTypePrefix !== mangledName) {
40005             return unmangleScopedPackageName(withoutAtTypePrefix);
40006         }
40007         return mangledName;
40008     }
40009     ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
40010     /* @internal */
40011     function unmangleScopedPackageName(typesPackageName) {
40012         return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
40013             "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
40014             typesPackageName;
40015     }
40016     ts.unmangleScopedPackageName = unmangleScopedPackageName;
40017     function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
40018         var result = cache && cache.get(containingDirectory);
40019         if (result) {
40020             if (state.traceEnabled) {
40021                 trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
40022             }
40023             state.resultFromCache = result;
40024             return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
40025         }
40026     }
40027     function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
40028         var traceEnabled = isTraceEnabled(compilerOptions, host);
40029         var failedLookupLocations = [];
40030         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
40031         var containingDirectory = ts.getDirectoryPath(containingFile);
40032         var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
40033         // No originalPath because classic resolution doesn't resolve realPath
40034         return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, state.resultFromCache);
40035         function tryResolve(extensions) {
40036             var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
40037             if (resolvedUsingSettings) {
40038                 return { value: resolvedUsingSettings };
40039             }
40040             if (!ts.isExternalModuleNameRelative(moduleName)) {
40041                 var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
40042                 // Climb up parent directories looking for a module.
40043                 var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
40044                     var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
40045                     if (resolutionFromCache) {
40046                         return resolutionFromCache;
40047                     }
40048                     var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
40049                     return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
40050                 });
40051                 if (resolved_3) {
40052                     return resolved_3;
40053                 }
40054                 if (extensions === Extensions.TypeScript) {
40055                     // If we didn't find the file normally, look it up in @types.
40056                     return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
40057                 }
40058             }
40059             else {
40060                 var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
40061                 return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
40062             }
40063         }
40064     }
40065     ts.classicNameResolver = classicNameResolver;
40066     /**
40067      * A host may load a module from a global cache of typings.
40068      * This is the minumum code needed to expose that functionality; the rest is in the host.
40069      */
40070     /* @internal */
40071     function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) {
40072         var traceEnabled = isTraceEnabled(compilerOptions, host);
40073         if (traceEnabled) {
40074             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);
40075         }
40076         var failedLookupLocations = [];
40077         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
40078         var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
40079         return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache);
40080     }
40081     ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
40082     /**
40083      * Wraps value to SearchResult.
40084      * @returns undefined if value is undefined or { value } otherwise
40085      */
40086     function toSearchResult(value) {
40087         return value !== undefined ? { value: value } : undefined;
40088     }
40089 })(ts || (ts = {}));
40090 /* @internal */
40091 var ts;
40092 (function (ts) {
40093     var ModuleInstanceState;
40094     (function (ModuleInstanceState) {
40095         ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
40096         ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
40097         ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
40098     })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
40099     function getModuleInstanceState(node, visited) {
40100         if (node.body && !node.body.parent) {
40101             // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
40102             ts.setParent(node.body, node);
40103             ts.setParentRecursive(node.body, /*incremental*/ false);
40104         }
40105         return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
40106     }
40107     ts.getModuleInstanceState = getModuleInstanceState;
40108     function getModuleInstanceStateCached(node, visited) {
40109         if (visited === void 0) { visited = new ts.Map(); }
40110         var nodeId = ts.getNodeId(node);
40111         if (visited.has(nodeId)) {
40112             return visited.get(nodeId) || 0 /* NonInstantiated */;
40113         }
40114         visited.set(nodeId, undefined);
40115         var result = getModuleInstanceStateWorker(node, visited);
40116         visited.set(nodeId, result);
40117         return result;
40118     }
40119     function getModuleInstanceStateWorker(node, visited) {
40120         // A module is uninstantiated if it contains only
40121         switch (node.kind) {
40122             // 1. interface declarations, type alias declarations
40123             case 253 /* InterfaceDeclaration */:
40124             case 254 /* TypeAliasDeclaration */:
40125                 return 0 /* NonInstantiated */;
40126             // 2. const enum declarations
40127             case 255 /* EnumDeclaration */:
40128                 if (ts.isEnumConst(node)) {
40129                     return 2 /* ConstEnumOnly */;
40130                 }
40131                 break;
40132             // 3. non-exported import declarations
40133             case 261 /* ImportDeclaration */:
40134             case 260 /* ImportEqualsDeclaration */:
40135                 if (!(ts.hasSyntacticModifier(node, 1 /* Export */))) {
40136                     return 0 /* NonInstantiated */;
40137                 }
40138                 break;
40139             // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
40140             case 267 /* ExportDeclaration */:
40141                 var exportDeclaration = node;
40142                 if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 268 /* NamedExports */) {
40143                     var state = 0 /* NonInstantiated */;
40144                     for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) {
40145                         var specifier = _a[_i];
40146                         var specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
40147                         if (specifierState > state) {
40148                             state = specifierState;
40149                         }
40150                         if (state === 1 /* Instantiated */) {
40151                             return state;
40152                         }
40153                     }
40154                     return state;
40155                 }
40156                 break;
40157             // 5. other uninstantiated module declarations.
40158             case 257 /* ModuleBlock */: {
40159                 var state_1 = 0 /* NonInstantiated */;
40160                 ts.forEachChild(node, function (n) {
40161                     var childState = getModuleInstanceStateCached(n, visited);
40162                     switch (childState) {
40163                         case 0 /* NonInstantiated */:
40164                             // child is non-instantiated - continue searching
40165                             return;
40166                         case 2 /* ConstEnumOnly */:
40167                             // child is const enum only - record state and continue searching
40168                             state_1 = 2 /* ConstEnumOnly */;
40169                             return;
40170                         case 1 /* Instantiated */:
40171                             // child is instantiated - record state and stop
40172                             state_1 = 1 /* Instantiated */;
40173                             return true;
40174                         default:
40175                             ts.Debug.assertNever(childState);
40176                     }
40177                 });
40178                 return state_1;
40179             }
40180             case 256 /* ModuleDeclaration */:
40181                 return getModuleInstanceState(node, visited);
40182             case 78 /* Identifier */:
40183                 // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
40184                 // be considered the same as type alias
40185                 if (node.isInJSDocNamespace) {
40186                     return 0 /* NonInstantiated */;
40187                 }
40188         }
40189         return 1 /* Instantiated */;
40190     }
40191     function getModuleInstanceStateForAliasTarget(specifier, visited) {
40192         var name = specifier.propertyName || specifier.name;
40193         var p = specifier.parent;
40194         while (p) {
40195             if (ts.isBlock(p) || ts.isModuleBlock(p) || ts.isSourceFile(p)) {
40196                 var statements = p.statements;
40197                 var found = void 0;
40198                 for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
40199                     var statement = statements_2[_i];
40200                     if (ts.nodeHasName(statement, name)) {
40201                         if (!statement.parent) {
40202                             ts.setParent(statement, p);
40203                             ts.setParentRecursive(statement, /*incremental*/ false);
40204                         }
40205                         var state = getModuleInstanceStateCached(statement, visited);
40206                         if (found === undefined || state > found) {
40207                             found = state;
40208                         }
40209                         if (found === 1 /* Instantiated */) {
40210                             return found;
40211                         }
40212                     }
40213                 }
40214                 if (found !== undefined) {
40215                     return found;
40216                 }
40217             }
40218             p = p.parent;
40219         }
40220         return 1 /* Instantiated */; // Couldn't locate, assume could refer to a value
40221     }
40222     var ContainerFlags;
40223     (function (ContainerFlags) {
40224         // The current node is not a container, and no container manipulation should happen before
40225         // recursing into it.
40226         ContainerFlags[ContainerFlags["None"] = 0] = "None";
40227         // The current node is a container.  It should be set as the current container (and block-
40228         // container) before recursing into it.  The current node does not have locals.  Examples:
40229         //
40230         //      Classes, ObjectLiterals, TypeLiterals, Interfaces...
40231         ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
40232         // The current node is a block-scoped-container.  It should be set as the current block-
40233         // container before recursing into it.  Examples:
40234         //
40235         //      Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
40236         ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
40237         // The current node is the container of a control flow path. The current control flow should
40238         // be saved and restored, and a new control flow initialized within the container.
40239         ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
40240         ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
40241         ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
40242         ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
40243         ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
40244         ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod";
40245     })(ContainerFlags || (ContainerFlags = {}));
40246     function initFlowNode(node) {
40247         ts.Debug.attachFlowNodeDebugInfo(node);
40248         return node;
40249     }
40250     var binder = createBinder();
40251     function bindSourceFile(file, options) {
40252         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("bind" /* Bind */, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true);
40253         ts.performance.mark("beforeBind");
40254         ts.perfLogger.logStartBindFile("" + file.fileName);
40255         binder(file, options);
40256         ts.perfLogger.logStopBindFile();
40257         ts.performance.mark("afterBind");
40258         ts.performance.measure("Bind", "beforeBind", "afterBind");
40259         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
40260     }
40261     ts.bindSourceFile = bindSourceFile;
40262     function createBinder() {
40263         var file;
40264         var options;
40265         var languageVersion;
40266         var parent;
40267         var container;
40268         var thisParentContainer; // Container one level up
40269         var blockScopeContainer;
40270         var lastContainer;
40271         var delayedTypeAliases;
40272         var seenThisKeyword;
40273         // state used by control flow analysis
40274         var currentFlow;
40275         var currentBreakTarget;
40276         var currentContinueTarget;
40277         var currentReturnTarget;
40278         var currentTrueTarget;
40279         var currentFalseTarget;
40280         var currentExceptionTarget;
40281         var preSwitchCaseFlow;
40282         var activeLabelList;
40283         var hasExplicitReturn;
40284         // state used for emit helpers
40285         var emitFlags;
40286         // If this file is an external module, then it is automatically in strict-mode according to
40287         // ES6.  If it is not an external module, then we'll determine if it is in strict mode or
40288         // not depending on if we see "use strict" in certain places or if we hit a class/namespace
40289         // or if compiler options contain alwaysStrict.
40290         var inStrictMode;
40291         // If we are binding an assignment pattern, we will bind certain expressions differently.
40292         var inAssignmentPattern = false;
40293         var symbolCount = 0;
40294         var Symbol;
40295         var classifiableNames;
40296         var unreachableFlow = { flags: 1 /* Unreachable */ };
40297         var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
40298         /**
40299          * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
40300          * 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)
40301          * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
40302          */
40303         function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
40304             return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
40305         }
40306         function bindSourceFile(f, opts) {
40307             file = f;
40308             options = opts;
40309             languageVersion = ts.getEmitScriptTarget(options);
40310             inStrictMode = bindInStrictMode(file, opts);
40311             classifiableNames = new ts.Set();
40312             symbolCount = 0;
40313             Symbol = ts.objectAllocator.getSymbolConstructor();
40314             // Attach debugging information if necessary
40315             ts.Debug.attachFlowNodeDebugInfo(unreachableFlow);
40316             ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
40317             if (!file.locals) {
40318                 bind(file);
40319                 file.symbolCount = symbolCount;
40320                 file.classifiableNames = classifiableNames;
40321                 delayedBindJSDocTypedefTag();
40322             }
40323             file = undefined;
40324             options = undefined;
40325             languageVersion = undefined;
40326             parent = undefined;
40327             container = undefined;
40328             thisParentContainer = undefined;
40329             blockScopeContainer = undefined;
40330             lastContainer = undefined;
40331             delayedTypeAliases = undefined;
40332             seenThisKeyword = false;
40333             currentFlow = undefined;
40334             currentBreakTarget = undefined;
40335             currentContinueTarget = undefined;
40336             currentReturnTarget = undefined;
40337             currentTrueTarget = undefined;
40338             currentFalseTarget = undefined;
40339             currentExceptionTarget = undefined;
40340             activeLabelList = undefined;
40341             hasExplicitReturn = false;
40342             inAssignmentPattern = false;
40343             emitFlags = 0 /* None */;
40344         }
40345         return bindSourceFile;
40346         function bindInStrictMode(file, opts) {
40347             if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
40348                 // bind in strict mode source files with alwaysStrict option
40349                 return true;
40350             }
40351             else {
40352                 return !!file.externalModuleIndicator;
40353             }
40354         }
40355         function createSymbol(flags, name) {
40356             symbolCount++;
40357             return new Symbol(flags, name);
40358         }
40359         function addDeclarationToSymbol(symbol, node, symbolFlags) {
40360             symbol.flags |= symbolFlags;
40361             node.symbol = symbol;
40362             symbol.declarations = ts.appendIfUnique(symbol.declarations, node);
40363             if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
40364                 symbol.exports = ts.createSymbolTable();
40365             }
40366             if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
40367                 symbol.members = ts.createSymbolTable();
40368             }
40369             // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
40370             if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) {
40371                 symbol.constEnumOnlyModule = false;
40372             }
40373             if (symbolFlags & 111551 /* Value */) {
40374                 ts.setValueDeclaration(symbol, node);
40375             }
40376         }
40377         // Should not be called on a declaration with a computed property name,
40378         // unless it is a well known Symbol.
40379         function getDeclarationName(node) {
40380             if (node.kind === 266 /* ExportAssignment */) {
40381                 return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
40382             }
40383             var name = ts.getNameOfDeclaration(node);
40384             if (name) {
40385                 if (ts.isAmbientModule(node)) {
40386                     var moduleName = ts.getTextOfIdentifierOrLiteral(name);
40387                     return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\"");
40388                 }
40389                 if (name.kind === 158 /* ComputedPropertyName */) {
40390                     var nameExpression = name.expression;
40391                     // treat computed property names where expression is string/numeric literal as just string/numeric literal
40392                     if (ts.isStringOrNumericLiteralLike(nameExpression)) {
40393                         return ts.escapeLeadingUnderscores(nameExpression.text);
40394                     }
40395                     if (ts.isSignedNumericLiteral(nameExpression)) {
40396                         return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
40397                     }
40398                     ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
40399                     return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
40400                 }
40401                 if (ts.isWellKnownSymbolSyntactically(name)) {
40402                     return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name));
40403                 }
40404                 if (ts.isPrivateIdentifier(name)) {
40405                     // containingClass exists because private names only allowed inside classes
40406                     var containingClass = ts.getContainingClass(node);
40407                     if (!containingClass) {
40408                         // we can get here in cases where there is already a parse error.
40409                         return undefined;
40410                     }
40411                     var containingClassSymbol = containingClass.symbol;
40412                     return ts.getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
40413                 }
40414                 return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
40415             }
40416             switch (node.kind) {
40417                 case 166 /* Constructor */:
40418                     return "__constructor" /* Constructor */;
40419                 case 174 /* FunctionType */:
40420                 case 169 /* CallSignature */:
40421                 case 313 /* JSDocSignature */:
40422                     return "__call" /* Call */;
40423                 case 175 /* ConstructorType */:
40424                 case 170 /* ConstructSignature */:
40425                     return "__new" /* New */;
40426                 case 171 /* IndexSignature */:
40427                     return "__index" /* Index */;
40428                 case 267 /* ExportDeclaration */:
40429                     return "__export" /* ExportStar */;
40430                 case 297 /* SourceFile */:
40431                     // json file should behave as
40432                     // module.exports = ...
40433                     return "export=" /* ExportEquals */;
40434                 case 216 /* BinaryExpression */:
40435                     if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
40436                         // module.exports = ...
40437                         return "export=" /* ExportEquals */;
40438                     }
40439                     ts.Debug.fail("Unknown binary declaration kind");
40440                     break;
40441                 case 308 /* JSDocFunctionType */:
40442                     return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
40443                 case 160 /* Parameter */:
40444                     // Parameters with names are handled at the top of this function.  Parameters
40445                     // without names can only come from JSDocFunctionTypes.
40446                     ts.Debug.assert(node.parent.kind === 308 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
40447                     var functionType = node.parent;
40448                     var index = functionType.parameters.indexOf(node);
40449                     return "arg" + index;
40450             }
40451         }
40452         function getDisplayName(node) {
40453             return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.checkDefined(getDeclarationName(node)));
40454         }
40455         /**
40456          * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
40457          * @param symbolTable - The symbol table which node will be added to.
40458          * @param parent - node's parent declaration.
40459          * @param node - The declaration to be added to the symbol table
40460          * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
40461          * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
40462          */
40463         function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) {
40464             ts.Debug.assert(!ts.hasDynamicName(node));
40465             var isDefaultExport = ts.hasSyntacticModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default";
40466             // The exported symbol for an export default function/class node is always named "default"
40467             var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node);
40468             var symbol;
40469             if (name === undefined) {
40470                 symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
40471             }
40472             else {
40473                 // Check and see if the symbol table already has a symbol with this name.  If not,
40474                 // create a new symbol with this name and add it to the table.  Note that we don't
40475                 // give the new symbol any flags *yet*.  This ensures that it will not conflict
40476                 // with the 'excludes' flags we pass in.
40477                 //
40478                 // If we do get an existing symbol, see if it conflicts with the new symbol we're
40479                 // creating.  For example, a 'var' symbol and a 'class' symbol will conflict within
40480                 // the same symbol table.  If we have a conflict, report the issue on each
40481                 // declaration we have for this symbol, and then create a new symbol for this
40482                 // declaration.
40483                 //
40484                 // Note that when properties declared in Javascript constructors
40485                 // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
40486                 // Always. This allows the common Javascript pattern of overwriting a prototype method
40487                 // with an bound instance method of the same type: `this.method = this.method.bind(this)`
40488                 //
40489                 // If we created a new symbol, either because we didn't have a symbol with this name
40490                 // in the symbol table, or we conflicted with an existing symbol, then just add this
40491                 // node as the sole declaration of the new symbol.
40492                 //
40493                 // Otherwise, we'll be merging into a compatible existing symbol (for example when
40494                 // you have multiple 'vars' with the same name in the same container).  In this case
40495                 // just add this node into the declarations list of the symbol.
40496                 symbol = symbolTable.get(name);
40497                 if (includes & 2885600 /* Classifiable */) {
40498                     classifiableNames.add(name);
40499                 }
40500                 if (!symbol) {
40501                     symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
40502                     if (isReplaceableByMethod)
40503                         symbol.isReplaceableByMethod = true;
40504                 }
40505                 else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
40506                     // A symbol already exists, so don't add this as a declaration.
40507                     return symbol;
40508                 }
40509                 else if (symbol.flags & excludes) {
40510                     if (symbol.isReplaceableByMethod) {
40511                         // Javascript constructor-declared symbols can be discarded in favor of
40512                         // prototype symbols like methods.
40513                         symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
40514                     }
40515                     else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
40516                         // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
40517                         if (ts.isNamedDeclaration(node)) {
40518                             ts.setParent(node.name, node);
40519                         }
40520                         // Report errors every position with duplicate declaration
40521                         // Report errors on previous encountered declarations
40522                         var message_1 = symbol.flags & 2 /* BlockScopedVariable */
40523                             ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
40524                             : ts.Diagnostics.Duplicate_identifier_0;
40525                         var messageNeedsName_1 = true;
40526                         if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
40527                             message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
40528                             messageNeedsName_1 = false;
40529                         }
40530                         var multipleDefaultExports_1 = false;
40531                         if (ts.length(symbol.declarations)) {
40532                             // If the current node is a default export of some sort, then check if
40533                             // there are any other default exports that we need to error on.
40534                             // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
40535                             if (isDefaultExport) {
40536                                 message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
40537                                 messageNeedsName_1 = false;
40538                                 multipleDefaultExports_1 = true;
40539                             }
40540                             else {
40541                                 // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
40542                                 // Error on multiple export default in the following case:
40543                                 // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
40544                                 // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
40545                                 if (symbol.declarations && symbol.declarations.length &&
40546                                     (node.kind === 266 /* ExportAssignment */ && !node.isExportEquals)) {
40547                                     message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
40548                                     messageNeedsName_1 = false;
40549                                     multipleDefaultExports_1 = true;
40550                                 }
40551                             }
40552                         }
40553                         var relatedInformation_1 = [];
40554                         if (ts.isTypeAliasDeclaration(node) && ts.nodeIsMissing(node.type) && ts.hasSyntacticModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
40555                             // export type T; - may have meant export type { T }?
40556                             relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { " + ts.unescapeLeadingUnderscores(node.name.escapedText) + " }"));
40557                         }
40558                         var declarationName_1 = ts.getNameOfDeclaration(node) || node;
40559                         ts.forEach(symbol.declarations, function (declaration, index) {
40560                             var decl = ts.getNameOfDeclaration(declaration) || declaration;
40561                             var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
40562                             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);
40563                             if (multipleDefaultExports_1) {
40564                                 relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
40565                             }
40566                         });
40567                         var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
40568                         file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArray([diag], relatedInformation_1)));
40569                         symbol = createSymbol(0 /* None */, name);
40570                     }
40571                 }
40572             }
40573             addDeclarationToSymbol(symbol, node, includes);
40574             if (symbol.parent) {
40575                 ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
40576             }
40577             else {
40578                 symbol.parent = parent;
40579             }
40580             return symbol;
40581         }
40582         function declareModuleMember(node, symbolFlags, symbolExcludes) {
40583             var hasExportModifier = !!(ts.getCombinedModifierFlags(node) & 1 /* Export */) || jsdocTreatAsExported(node);
40584             if (symbolFlags & 2097152 /* Alias */) {
40585                 if (node.kind === 270 /* ExportSpecifier */ || (node.kind === 260 /* ImportEqualsDeclaration */ && hasExportModifier)) {
40586                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
40587                 }
40588                 else {
40589                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
40590                 }
40591             }
40592             else {
40593                 // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
40594                 // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
40595                 //
40596                 //   1. We treat locals and exports of the same name as mutually exclusive within a container.
40597                 //      That means the binder will issue a Duplicate Identifier error if you mix locals and exports
40598                 //      with the same name in the same container.
40599                 //      TODO: Make this a more specific error and decouple it from the exclusion logic.
40600                 //   2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
40601                 //      but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
40602                 //      when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
40603                 // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
40604                 //       during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
40605                 //       and this case is specially handled. Module augmentations should only be merged with original module definition
40606                 //       and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
40607                 if (ts.isJSDocTypeAlias(node))
40608                     ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
40609                 if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* ExportContext */)) {
40610                     if (!container.locals || (ts.hasSyntacticModifier(node, 512 /* Default */) && !getDeclarationName(node))) {
40611                         return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
40612                     }
40613                     var exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
40614                     var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
40615                     local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
40616                     node.localSymbol = local;
40617                     return local;
40618                 }
40619                 else {
40620                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
40621                 }
40622             }
40623         }
40624         function jsdocTreatAsExported(node) {
40625             if (node.parent && ts.isModuleDeclaration(node)) {
40626                 node = node.parent;
40627             }
40628             if (!ts.isJSDocTypeAlias(node))
40629                 return false;
40630             // jsdoc typedef handling is a bit of a doozy, but to summarize, treat the typedef as exported if:
40631             // 1. It has an explicit name (since by default typedefs are always directly exported, either at the top level or in a container), or
40632             if (!ts.isJSDocEnumTag(node) && !!node.fullName)
40633                 return true;
40634             // 2. The thing a nameless typedef pulls its name from is implicitly a direct export (either by assignment or actual export flag).
40635             var declName = ts.getNameOfDeclaration(node);
40636             if (!declName)
40637                 return false;
40638             if (ts.isPropertyAccessEntityNameExpression(declName.parent) && isTopLevelNamespaceAssignment(declName.parent))
40639                 return true;
40640             if (ts.isDeclaration(declName.parent) && ts.getCombinedModifierFlags(declName.parent) & 1 /* Export */)
40641                 return true;
40642             // This could potentially be simplified by having `delayedBindJSDocTypedefTag` pass in an override for `hasExportModifier`, since it should
40643             // already have calculated and branched on most of this.
40644             return false;
40645         }
40646         // All container nodes are kept on a linked list in declaration order. This list is used by
40647         // the getLocalNameOfContainer function in the type checker to validate that the local name
40648         // used for a container is unique.
40649         function bindContainer(node, containerFlags) {
40650             // Before we recurse into a node's children, we first save the existing parent, container
40651             // and block-container.  Then after we pop out of processing the children, we restore
40652             // these saved values.
40653             var saveContainer = container;
40654             var saveThisParentContainer = thisParentContainer;
40655             var savedBlockScopeContainer = blockScopeContainer;
40656             // Depending on what kind of node this is, we may have to adjust the current container
40657             // and block-container.   If the current node is a container, then it is automatically
40658             // considered the current block-container as well.  Also, for containers that we know
40659             // may contain locals, we eagerly initialize the .locals field. We do this because
40660             // it's highly likely that the .locals will be needed to place some child in (for example,
40661             // a parameter, or variable declaration).
40662             //
40663             // However, we do not proactively create the .locals for block-containers because it's
40664             // totally normal and common for block-containers to never actually have a block-scoped
40665             // variable in them.  We don't want to end up allocating an object for every 'block' we
40666             // run into when most of them won't be necessary.
40667             //
40668             // Finally, if this is a block-container, then we clear out any existing .locals object
40669             // it may contain within it.  This happens in incremental scenarios.  Because we can be
40670             // reusing a node from a previous compilation, that node may have had 'locals' created
40671             // for it.  We must clear this so we don't accidentally move any stale data forward from
40672             // a previous compilation.
40673             if (containerFlags & 1 /* IsContainer */) {
40674                 if (node.kind !== 209 /* ArrowFunction */) {
40675                     thisParentContainer = container;
40676                 }
40677                 container = blockScopeContainer = node;
40678                 if (containerFlags & 32 /* HasLocals */) {
40679                     container.locals = ts.createSymbolTable();
40680                 }
40681                 addToContainerChain(container);
40682             }
40683             else if (containerFlags & 2 /* IsBlockScopedContainer */) {
40684                 blockScopeContainer = node;
40685                 blockScopeContainer.locals = undefined;
40686             }
40687             if (containerFlags & 4 /* IsControlFlowContainer */) {
40688                 var saveCurrentFlow = currentFlow;
40689                 var saveBreakTarget = currentBreakTarget;
40690                 var saveContinueTarget = currentContinueTarget;
40691                 var saveReturnTarget = currentReturnTarget;
40692                 var saveExceptionTarget = currentExceptionTarget;
40693                 var saveActiveLabelList = activeLabelList;
40694                 var saveHasExplicitReturn = hasExplicitReturn;
40695                 var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasSyntacticModifier(node, 256 /* Async */) &&
40696                     !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
40697                 // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
40698                 // similarly to break statements that exit to a label just past the statement body.
40699                 if (!isIIFE) {
40700                     currentFlow = initFlowNode({ flags: 2 /* Start */ });
40701                     if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) {
40702                         currentFlow.node = node;
40703                     }
40704                 }
40705                 // We create a return control flow graph for IIFEs and constructors. For constructors
40706                 // we use the return control flow graph in strict property initialization checks.
40707                 currentReturnTarget = isIIFE || node.kind === 166 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) ? createBranchLabel() : undefined;
40708                 currentExceptionTarget = undefined;
40709                 currentBreakTarget = undefined;
40710                 currentContinueTarget = undefined;
40711                 activeLabelList = undefined;
40712                 hasExplicitReturn = false;
40713                 bindChildren(node);
40714                 // Reset all reachability check related flags on node (for incremental scenarios)
40715                 node.flags &= ~2816 /* ReachabilityAndEmitFlags */;
40716                 if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
40717                     node.flags |= 256 /* HasImplicitReturn */;
40718                     if (hasExplicitReturn)
40719                         node.flags |= 512 /* HasExplicitReturn */;
40720                     node.endFlowNode = currentFlow;
40721                 }
40722                 if (node.kind === 297 /* SourceFile */) {
40723                     node.flags |= emitFlags;
40724                 }
40725                 if (currentReturnTarget) {
40726                     addAntecedent(currentReturnTarget, currentFlow);
40727                     currentFlow = finishFlowLabel(currentReturnTarget);
40728                     if (node.kind === 166 /* Constructor */ || (ts.isInJSFile(node) && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */))) {
40729                         node.returnFlowNode = currentFlow;
40730                     }
40731                 }
40732                 if (!isIIFE) {
40733                     currentFlow = saveCurrentFlow;
40734                 }
40735                 currentBreakTarget = saveBreakTarget;
40736                 currentContinueTarget = saveContinueTarget;
40737                 currentReturnTarget = saveReturnTarget;
40738                 currentExceptionTarget = saveExceptionTarget;
40739                 activeLabelList = saveActiveLabelList;
40740                 hasExplicitReturn = saveHasExplicitReturn;
40741             }
40742             else if (containerFlags & 64 /* IsInterface */) {
40743                 seenThisKeyword = false;
40744                 bindChildren(node);
40745                 node.flags = seenThisKeyword ? node.flags | 128 /* ContainsThis */ : node.flags & ~128 /* ContainsThis */;
40746             }
40747             else {
40748                 bindChildren(node);
40749             }
40750             container = saveContainer;
40751             thisParentContainer = saveThisParentContainer;
40752             blockScopeContainer = savedBlockScopeContainer;
40753         }
40754         function bindEachFunctionsFirst(nodes) {
40755             bindEach(nodes, function (n) { return n.kind === 251 /* FunctionDeclaration */ ? bind(n) : undefined; });
40756             bindEach(nodes, function (n) { return n.kind !== 251 /* FunctionDeclaration */ ? bind(n) : undefined; });
40757         }
40758         function bindEach(nodes, bindFunction) {
40759             if (bindFunction === void 0) { bindFunction = bind; }
40760             if (nodes === undefined) {
40761                 return;
40762             }
40763             ts.forEach(nodes, bindFunction);
40764         }
40765         function bindEachChild(node) {
40766             ts.forEachChild(node, bind, bindEach);
40767         }
40768         function bindChildren(node) {
40769             var saveInAssignmentPattern = inAssignmentPattern;
40770             // Most nodes aren't valid in an assignment pattern, so we clear the value here
40771             // and set it before we descend into nodes that could actually be part of an assignment pattern.
40772             inAssignmentPattern = false;
40773             if (checkUnreachable(node)) {
40774                 bindEachChild(node);
40775                 bindJSDoc(node);
40776                 inAssignmentPattern = saveInAssignmentPattern;
40777                 return;
40778             }
40779             if (node.kind >= 232 /* FirstStatement */ && node.kind <= 248 /* LastStatement */ && !options.allowUnreachableCode) {
40780                 node.flowNode = currentFlow;
40781             }
40782             switch (node.kind) {
40783                 case 236 /* WhileStatement */:
40784                     bindWhileStatement(node);
40785                     break;
40786                 case 235 /* DoStatement */:
40787                     bindDoStatement(node);
40788                     break;
40789                 case 237 /* ForStatement */:
40790                     bindForStatement(node);
40791                     break;
40792                 case 238 /* ForInStatement */:
40793                 case 239 /* ForOfStatement */:
40794                     bindForInOrForOfStatement(node);
40795                     break;
40796                 case 234 /* IfStatement */:
40797                     bindIfStatement(node);
40798                     break;
40799                 case 242 /* ReturnStatement */:
40800                 case 246 /* ThrowStatement */:
40801                     bindReturnOrThrow(node);
40802                     break;
40803                 case 241 /* BreakStatement */:
40804                 case 240 /* ContinueStatement */:
40805                     bindBreakOrContinueStatement(node);
40806                     break;
40807                 case 247 /* TryStatement */:
40808                     bindTryStatement(node);
40809                     break;
40810                 case 244 /* SwitchStatement */:
40811                     bindSwitchStatement(node);
40812                     break;
40813                 case 258 /* CaseBlock */:
40814                     bindCaseBlock(node);
40815                     break;
40816                 case 284 /* CaseClause */:
40817                     bindCaseClause(node);
40818                     break;
40819                 case 233 /* ExpressionStatement */:
40820                     bindExpressionStatement(node);
40821                     break;
40822                 case 245 /* LabeledStatement */:
40823                     bindLabeledStatement(node);
40824                     break;
40825                 case 214 /* PrefixUnaryExpression */:
40826                     bindPrefixUnaryExpressionFlow(node);
40827                     break;
40828                 case 215 /* PostfixUnaryExpression */:
40829                     bindPostfixUnaryExpressionFlow(node);
40830                     break;
40831                 case 216 /* BinaryExpression */:
40832                     if (ts.isDestructuringAssignment(node)) {
40833                         // Carry over whether we are in an assignment pattern to
40834                         // binary expressions that could actually be an initializer
40835                         inAssignmentPattern = saveInAssignmentPattern;
40836                         bindDestructuringAssignmentFlow(node);
40837                         return;
40838                     }
40839                     bindBinaryExpressionFlow(node);
40840                     break;
40841                 case 210 /* DeleteExpression */:
40842                     bindDeleteExpressionFlow(node);
40843                     break;
40844                 case 217 /* ConditionalExpression */:
40845                     bindConditionalExpressionFlow(node);
40846                     break;
40847                 case 249 /* VariableDeclaration */:
40848                     bindVariableDeclarationFlow(node);
40849                     break;
40850                 case 201 /* PropertyAccessExpression */:
40851                 case 202 /* ElementAccessExpression */:
40852                     bindAccessExpressionFlow(node);
40853                     break;
40854                 case 203 /* CallExpression */:
40855                     bindCallExpressionFlow(node);
40856                     break;
40857                 case 225 /* NonNullExpression */:
40858                     bindNonNullExpressionFlow(node);
40859                     break;
40860                 case 331 /* JSDocTypedefTag */:
40861                 case 324 /* JSDocCallbackTag */:
40862                 case 325 /* JSDocEnumTag */:
40863                     bindJSDocTypeAlias(node);
40864                     break;
40865                 // In source files and blocks, bind functions first to match hoisting that occurs at runtime
40866                 case 297 /* SourceFile */: {
40867                     bindEachFunctionsFirst(node.statements);
40868                     bind(node.endOfFileToken);
40869                     break;
40870                 }
40871                 case 230 /* Block */:
40872                 case 257 /* ModuleBlock */:
40873                     bindEachFunctionsFirst(node.statements);
40874                     break;
40875                 case 198 /* BindingElement */:
40876                     bindBindingElementFlow(node);
40877                     break;
40878                 case 200 /* ObjectLiteralExpression */:
40879                 case 199 /* ArrayLiteralExpression */:
40880                 case 288 /* PropertyAssignment */:
40881                 case 220 /* SpreadElement */:
40882                     // Carry over whether we are in an assignment pattern of Object and Array literals
40883                     // as well as their children that are valid assignment targets.
40884                     inAssignmentPattern = saveInAssignmentPattern;
40885                 // falls through
40886                 default:
40887                     bindEachChild(node);
40888                     break;
40889             }
40890             bindJSDoc(node);
40891             inAssignmentPattern = saveInAssignmentPattern;
40892         }
40893         function isNarrowingExpression(expr) {
40894             switch (expr.kind) {
40895                 case 78 /* Identifier */:
40896                 case 79 /* PrivateIdentifier */:
40897                 case 107 /* ThisKeyword */:
40898                 case 201 /* PropertyAccessExpression */:
40899                 case 202 /* ElementAccessExpression */:
40900                     return containsNarrowableReference(expr);
40901                 case 203 /* CallExpression */:
40902                     return hasNarrowableArgument(expr);
40903                 case 207 /* ParenthesizedExpression */:
40904                 case 225 /* NonNullExpression */:
40905                     return isNarrowingExpression(expr.expression);
40906                 case 216 /* BinaryExpression */:
40907                     return isNarrowingBinaryExpression(expr);
40908                 case 214 /* PrefixUnaryExpression */:
40909                     return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
40910                 case 211 /* TypeOfExpression */:
40911                     return isNarrowingExpression(expr.expression);
40912             }
40913             return false;
40914         }
40915         function isNarrowableReference(expr) {
40916             return expr.kind === 78 /* Identifier */ || expr.kind === 79 /* PrivateIdentifier */ || expr.kind === 107 /* ThisKeyword */ || expr.kind === 105 /* SuperKeyword */ ||
40917                 (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
40918                 ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right) ||
40919                 ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) ||
40920                 ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left);
40921         }
40922         function containsNarrowableReference(expr) {
40923             return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression);
40924         }
40925         function hasNarrowableArgument(expr) {
40926             if (expr.arguments) {
40927                 for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
40928                     var argument = _a[_i];
40929                     if (containsNarrowableReference(argument)) {
40930                         return true;
40931                     }
40932                 }
40933             }
40934             if (expr.expression.kind === 201 /* PropertyAccessExpression */ &&
40935                 containsNarrowableReference(expr.expression.expression)) {
40936                 return true;
40937             }
40938             return false;
40939         }
40940         function isNarrowingTypeofOperands(expr1, expr2) {
40941             return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
40942         }
40943         function isNarrowableInOperands(left, right) {
40944             return ts.isStringLiteralLike(left) && isNarrowingExpression(right);
40945         }
40946         function isNarrowingBinaryExpression(expr) {
40947             switch (expr.operatorToken.kind) {
40948                 case 62 /* EqualsToken */:
40949                 case 74 /* BarBarEqualsToken */:
40950                 case 75 /* AmpersandAmpersandEqualsToken */:
40951                 case 76 /* QuestionQuestionEqualsToken */:
40952                     return containsNarrowableReference(expr.left);
40953                 case 34 /* EqualsEqualsToken */:
40954                 case 35 /* ExclamationEqualsToken */:
40955                 case 36 /* EqualsEqualsEqualsToken */:
40956                 case 37 /* ExclamationEqualsEqualsToken */:
40957                     return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
40958                         isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
40959                 case 101 /* InstanceOfKeyword */:
40960                     return isNarrowableOperand(expr.left);
40961                 case 100 /* InKeyword */:
40962                     return isNarrowableInOperands(expr.left, expr.right);
40963                 case 27 /* CommaToken */:
40964                     return isNarrowingExpression(expr.right);
40965             }
40966             return false;
40967         }
40968         function isNarrowableOperand(expr) {
40969             switch (expr.kind) {
40970                 case 207 /* ParenthesizedExpression */:
40971                     return isNarrowableOperand(expr.expression);
40972                 case 216 /* BinaryExpression */:
40973                     switch (expr.operatorToken.kind) {
40974                         case 62 /* EqualsToken */:
40975                             return isNarrowableOperand(expr.left);
40976                         case 27 /* CommaToken */:
40977                             return isNarrowableOperand(expr.right);
40978                     }
40979             }
40980             return containsNarrowableReference(expr);
40981         }
40982         function createBranchLabel() {
40983             return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined });
40984         }
40985         function createLoopLabel() {
40986             return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined });
40987         }
40988         function createReduceLabel(target, antecedents, antecedent) {
40989             return initFlowNode({ flags: 1024 /* ReduceLabel */, target: target, antecedents: antecedents, antecedent: antecedent });
40990         }
40991         function setFlowNodeReferenced(flow) {
40992             // On first reference we set the Referenced flag, thereafter we set the Shared flag
40993             flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */;
40994         }
40995         function addAntecedent(label, antecedent) {
40996             if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
40997                 (label.antecedents || (label.antecedents = [])).push(antecedent);
40998                 setFlowNodeReferenced(antecedent);
40999             }
41000         }
41001         function createFlowCondition(flags, antecedent, expression) {
41002             if (antecedent.flags & 1 /* Unreachable */) {
41003                 return antecedent;
41004             }
41005             if (!expression) {
41006                 return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
41007             }
41008             if ((expression.kind === 109 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
41009                 expression.kind === 94 /* FalseKeyword */ && flags & 32 /* TrueCondition */) &&
41010                 !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) {
41011                 return unreachableFlow;
41012             }
41013             if (!isNarrowingExpression(expression)) {
41014                 return antecedent;
41015             }
41016             setFlowNodeReferenced(antecedent);
41017             return initFlowNode({ flags: flags, antecedent: antecedent, node: expression });
41018         }
41019         function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
41020             setFlowNodeReferenced(antecedent);
41021             return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd });
41022         }
41023         function createFlowMutation(flags, antecedent, node) {
41024             setFlowNodeReferenced(antecedent);
41025             var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node });
41026             if (currentExceptionTarget) {
41027                 addAntecedent(currentExceptionTarget, result);
41028             }
41029             return result;
41030         }
41031         function createFlowCall(antecedent, node) {
41032             setFlowNodeReferenced(antecedent);
41033             return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node });
41034         }
41035         function finishFlowLabel(flow) {
41036             var antecedents = flow.antecedents;
41037             if (!antecedents) {
41038                 return unreachableFlow;
41039             }
41040             if (antecedents.length === 1) {
41041                 return antecedents[0];
41042             }
41043             return flow;
41044         }
41045         function isStatementCondition(node) {
41046             var parent = node.parent;
41047             switch (parent.kind) {
41048                 case 234 /* IfStatement */:
41049                 case 236 /* WhileStatement */:
41050                 case 235 /* DoStatement */:
41051                     return parent.expression === node;
41052                 case 237 /* ForStatement */:
41053                 case 217 /* ConditionalExpression */:
41054                     return parent.condition === node;
41055             }
41056             return false;
41057         }
41058         function isLogicalExpression(node) {
41059             while (true) {
41060                 if (node.kind === 207 /* ParenthesizedExpression */) {
41061                     node = node.expression;
41062                 }
41063                 else if (node.kind === 214 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) {
41064                     node = node.operand;
41065                 }
41066                 else {
41067                     return node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ||
41068                         node.operatorToken.kind === 56 /* BarBarToken */ ||
41069                         node.operatorToken.kind === 60 /* QuestionQuestionToken */);
41070                 }
41071             }
41072         }
41073         function isLogicalAssignmentExpression(node) {
41074             node = ts.skipParentheses(node);
41075             return ts.isBinaryExpression(node) && ts.isLogicalOrCoalescingAssignmentOperator(node.operatorToken.kind);
41076         }
41077         function isTopLevelLogicalExpression(node) {
41078             while (ts.isParenthesizedExpression(node.parent) ||
41079                 ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 53 /* ExclamationToken */) {
41080                 node = node.parent;
41081             }
41082             return !isStatementCondition(node) &&
41083                 !isLogicalAssignmentExpression(node.parent) &&
41084                 !isLogicalExpression(node.parent) &&
41085                 !(ts.isOptionalChain(node.parent) && node.parent.expression === node);
41086         }
41087         function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
41088             var savedTrueTarget = currentTrueTarget;
41089             var savedFalseTarget = currentFalseTarget;
41090             currentTrueTarget = trueTarget;
41091             currentFalseTarget = falseTarget;
41092             action(value);
41093             currentTrueTarget = savedTrueTarget;
41094             currentFalseTarget = savedFalseTarget;
41095         }
41096         function bindCondition(node, trueTarget, falseTarget) {
41097             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
41098             if (!node || !isLogicalAssignmentExpression(node) && !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) {
41099                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
41100                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
41101             }
41102         }
41103         function bindIterativeStatement(node, breakTarget, continueTarget) {
41104             var saveBreakTarget = currentBreakTarget;
41105             var saveContinueTarget = currentContinueTarget;
41106             currentBreakTarget = breakTarget;
41107             currentContinueTarget = continueTarget;
41108             bind(node);
41109             currentBreakTarget = saveBreakTarget;
41110             currentContinueTarget = saveContinueTarget;
41111         }
41112         function setContinueTarget(node, target) {
41113             var label = activeLabelList;
41114             while (label && node.parent.kind === 245 /* LabeledStatement */) {
41115                 label.continueTarget = target;
41116                 label = label.next;
41117                 node = node.parent;
41118             }
41119             return target;
41120         }
41121         function bindWhileStatement(node) {
41122             var preWhileLabel = setContinueTarget(node, createLoopLabel());
41123             var preBodyLabel = createBranchLabel();
41124             var postWhileLabel = createBranchLabel();
41125             addAntecedent(preWhileLabel, currentFlow);
41126             currentFlow = preWhileLabel;
41127             bindCondition(node.expression, preBodyLabel, postWhileLabel);
41128             currentFlow = finishFlowLabel(preBodyLabel);
41129             bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
41130             addAntecedent(preWhileLabel, currentFlow);
41131             currentFlow = finishFlowLabel(postWhileLabel);
41132         }
41133         function bindDoStatement(node) {
41134             var preDoLabel = createLoopLabel();
41135             var preConditionLabel = setContinueTarget(node, createBranchLabel());
41136             var postDoLabel = createBranchLabel();
41137             addAntecedent(preDoLabel, currentFlow);
41138             currentFlow = preDoLabel;
41139             bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
41140             addAntecedent(preConditionLabel, currentFlow);
41141             currentFlow = finishFlowLabel(preConditionLabel);
41142             bindCondition(node.expression, preDoLabel, postDoLabel);
41143             currentFlow = finishFlowLabel(postDoLabel);
41144         }
41145         function bindForStatement(node) {
41146             var preLoopLabel = setContinueTarget(node, createLoopLabel());
41147             var preBodyLabel = createBranchLabel();
41148             var postLoopLabel = createBranchLabel();
41149             bind(node.initializer);
41150             addAntecedent(preLoopLabel, currentFlow);
41151             currentFlow = preLoopLabel;
41152             bindCondition(node.condition, preBodyLabel, postLoopLabel);
41153             currentFlow = finishFlowLabel(preBodyLabel);
41154             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
41155             bind(node.incrementor);
41156             addAntecedent(preLoopLabel, currentFlow);
41157             currentFlow = finishFlowLabel(postLoopLabel);
41158         }
41159         function bindForInOrForOfStatement(node) {
41160             var preLoopLabel = setContinueTarget(node, createLoopLabel());
41161             var postLoopLabel = createBranchLabel();
41162             bind(node.expression);
41163             addAntecedent(preLoopLabel, currentFlow);
41164             currentFlow = preLoopLabel;
41165             if (node.kind === 239 /* ForOfStatement */) {
41166                 bind(node.awaitModifier);
41167             }
41168             addAntecedent(postLoopLabel, currentFlow);
41169             bind(node.initializer);
41170             if (node.initializer.kind !== 250 /* VariableDeclarationList */) {
41171                 bindAssignmentTargetFlow(node.initializer);
41172             }
41173             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
41174             addAntecedent(preLoopLabel, currentFlow);
41175             currentFlow = finishFlowLabel(postLoopLabel);
41176         }
41177         function bindIfStatement(node) {
41178             var thenLabel = createBranchLabel();
41179             var elseLabel = createBranchLabel();
41180             var postIfLabel = createBranchLabel();
41181             bindCondition(node.expression, thenLabel, elseLabel);
41182             currentFlow = finishFlowLabel(thenLabel);
41183             bind(node.thenStatement);
41184             addAntecedent(postIfLabel, currentFlow);
41185             currentFlow = finishFlowLabel(elseLabel);
41186             bind(node.elseStatement);
41187             addAntecedent(postIfLabel, currentFlow);
41188             currentFlow = finishFlowLabel(postIfLabel);
41189         }
41190         function bindReturnOrThrow(node) {
41191             bind(node.expression);
41192             if (node.kind === 242 /* ReturnStatement */) {
41193                 hasExplicitReturn = true;
41194                 if (currentReturnTarget) {
41195                     addAntecedent(currentReturnTarget, currentFlow);
41196                 }
41197             }
41198             currentFlow = unreachableFlow;
41199         }
41200         function findActiveLabel(name) {
41201             for (var label = activeLabelList; label; label = label.next) {
41202                 if (label.name === name) {
41203                     return label;
41204                 }
41205             }
41206             return undefined;
41207         }
41208         function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
41209             var flowLabel = node.kind === 241 /* BreakStatement */ ? breakTarget : continueTarget;
41210             if (flowLabel) {
41211                 addAntecedent(flowLabel, currentFlow);
41212                 currentFlow = unreachableFlow;
41213             }
41214         }
41215         function bindBreakOrContinueStatement(node) {
41216             bind(node.label);
41217             if (node.label) {
41218                 var activeLabel = findActiveLabel(node.label.escapedText);
41219                 if (activeLabel) {
41220                     activeLabel.referenced = true;
41221                     bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
41222                 }
41223             }
41224             else {
41225                 bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
41226             }
41227         }
41228         function bindTryStatement(node) {
41229             // We conservatively assume that *any* code in the try block can cause an exception, but we only need
41230             // to track code that causes mutations (because only mutations widen the possible control flow type of
41231             // a variable). The exceptionLabel is the target label for control flows that result from exceptions.
41232             // We add all mutation flow nodes as antecedents of this label such that we can analyze them as possible
41233             // antecedents of the start of catch or finally blocks. Furthermore, we add the current control flow to
41234             // represent exceptions that occur before any mutations.
41235             var saveReturnTarget = currentReturnTarget;
41236             var saveExceptionTarget = currentExceptionTarget;
41237             var normalExitLabel = createBranchLabel();
41238             var returnLabel = createBranchLabel();
41239             var exceptionLabel = createBranchLabel();
41240             if (node.finallyBlock) {
41241                 currentReturnTarget = returnLabel;
41242             }
41243             addAntecedent(exceptionLabel, currentFlow);
41244             currentExceptionTarget = exceptionLabel;
41245             bind(node.tryBlock);
41246             addAntecedent(normalExitLabel, currentFlow);
41247             if (node.catchClause) {
41248                 // Start of catch clause is the target of exceptions from try block.
41249                 currentFlow = finishFlowLabel(exceptionLabel);
41250                 // The currentExceptionTarget now represents control flows from exceptions in the catch clause.
41251                 // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block
41252                 // acts like a second try block.
41253                 exceptionLabel = createBranchLabel();
41254                 addAntecedent(exceptionLabel, currentFlow);
41255                 currentExceptionTarget = exceptionLabel;
41256                 bind(node.catchClause);
41257                 addAntecedent(normalExitLabel, currentFlow);
41258             }
41259             currentReturnTarget = saveReturnTarget;
41260             currentExceptionTarget = saveExceptionTarget;
41261             if (node.finallyBlock) {
41262                 // Possible ways control can reach the finally block:
41263                 // 1) Normal completion of try block of a try-finally or try-catch-finally
41264                 // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally
41265                 // 3) Return in try or catch block of a try-finally or try-catch-finally
41266                 // 4) Exception in try block of a try-finally
41267                 // 5) Exception in catch block of a try-catch-finally
41268                 // When analyzing a control flow graph that starts inside a finally block we want to consider all
41269                 // five possibilities above. However, when analyzing a control flow graph that starts outside (past)
41270                 // the finally block, we only want to consider the first two (if we're past a finally block then it
41271                 // must have completed normally). Likewise, when analyzing a control flow graph from return statements
41272                 // in try or catch blocks in an IIFE, we only want to consider the third. To make this possible, we
41273                 // inject a ReduceLabel node into the control flow graph. This node contains an alternate reduced
41274                 // set of antecedents for the pre-finally label. As control flow analysis passes by a ReduceLabel
41275                 // node, the pre-finally label is temporarily switched to the reduced antecedent set.
41276                 var finallyLabel = createBranchLabel();
41277                 finallyLabel.antecedents = ts.concatenate(ts.concatenate(normalExitLabel.antecedents, exceptionLabel.antecedents), returnLabel.antecedents);
41278                 currentFlow = finallyLabel;
41279                 bind(node.finallyBlock);
41280                 if (currentFlow.flags & 1 /* Unreachable */) {
41281                     // If the end of the finally block is unreachable, the end of the entire try statement is unreachable.
41282                     currentFlow = unreachableFlow;
41283                 }
41284                 else {
41285                     // If we have an IIFE return target and return statements in the try or catch blocks, add a control
41286                     // flow that goes back through the finally block and back through only the return statements.
41287                     if (currentReturnTarget && returnLabel.antecedents) {
41288                         addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedents, currentFlow));
41289                     }
41290                     // If we have an outer exception target (i.e. a containing try-finally or try-catch-finally), add a
41291                     // control flow that goes back through the finally blok and back through each possible exception source.
41292                     if (currentExceptionTarget && exceptionLabel.antecedents) {
41293                         addAntecedent(currentExceptionTarget, createReduceLabel(finallyLabel, exceptionLabel.antecedents, currentFlow));
41294                     }
41295                     // If the end of the finally block is reachable, but the end of the try and catch blocks are not,
41296                     // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should
41297                     // result in an unreachable current control flow.
41298                     currentFlow = normalExitLabel.antecedents ? createReduceLabel(finallyLabel, normalExitLabel.antecedents, currentFlow) : unreachableFlow;
41299                 }
41300             }
41301             else {
41302                 currentFlow = finishFlowLabel(normalExitLabel);
41303             }
41304         }
41305         function bindSwitchStatement(node) {
41306             var postSwitchLabel = createBranchLabel();
41307             bind(node.expression);
41308             var saveBreakTarget = currentBreakTarget;
41309             var savePreSwitchCaseFlow = preSwitchCaseFlow;
41310             currentBreakTarget = postSwitchLabel;
41311             preSwitchCaseFlow = currentFlow;
41312             bind(node.caseBlock);
41313             addAntecedent(postSwitchLabel, currentFlow);
41314             var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 285 /* DefaultClause */; });
41315             // We mark a switch statement as possibly exhaustive if it has no default clause and if all
41316             // case clauses have unreachable end points (e.g. they all return). Note, we no longer need
41317             // this property in control flow analysis, it's there only for backwards compatibility.
41318             node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
41319             if (!hasDefault) {
41320                 addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
41321             }
41322             currentBreakTarget = saveBreakTarget;
41323             preSwitchCaseFlow = savePreSwitchCaseFlow;
41324             currentFlow = finishFlowLabel(postSwitchLabel);
41325         }
41326         function bindCaseBlock(node) {
41327             var clauses = node.clauses;
41328             var isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
41329             var fallthroughFlow = unreachableFlow;
41330             for (var i = 0; i < clauses.length; i++) {
41331                 var clauseStart = i;
41332                 while (!clauses[i].statements.length && i + 1 < clauses.length) {
41333                     bind(clauses[i]);
41334                     i++;
41335                 }
41336                 var preCaseLabel = createBranchLabel();
41337                 addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
41338                 addAntecedent(preCaseLabel, fallthroughFlow);
41339                 currentFlow = finishFlowLabel(preCaseLabel);
41340                 var clause = clauses[i];
41341                 bind(clause);
41342                 fallthroughFlow = currentFlow;
41343                 if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
41344                     clause.fallthroughFlowNode = currentFlow;
41345                 }
41346             }
41347         }
41348         function bindCaseClause(node) {
41349             var saveCurrentFlow = currentFlow;
41350             currentFlow = preSwitchCaseFlow;
41351             bind(node.expression);
41352             currentFlow = saveCurrentFlow;
41353             bindEach(node.statements);
41354         }
41355         function bindExpressionStatement(node) {
41356             bind(node.expression);
41357             maybeBindExpressionFlowIfCall(node.expression);
41358         }
41359         function maybeBindExpressionFlowIfCall(node) {
41360             // A top level or LHS of comma expression call expression with a dotted function name and at least one argument
41361             // is potentially an assertion and is therefore included in the control flow.
41362             if (node.kind === 203 /* CallExpression */) {
41363                 var call = node;
41364                 if (ts.isDottedName(call.expression) && call.expression.kind !== 105 /* SuperKeyword */) {
41365                     currentFlow = createFlowCall(currentFlow, call);
41366                 }
41367             }
41368         }
41369         function bindLabeledStatement(node) {
41370             var postStatementLabel = createBranchLabel();
41371             activeLabelList = {
41372                 next: activeLabelList,
41373                 name: node.label.escapedText,
41374                 breakTarget: postStatementLabel,
41375                 continueTarget: undefined,
41376                 referenced: false
41377             };
41378             bind(node.label);
41379             bind(node.statement);
41380             if (!activeLabelList.referenced && !options.allowUnusedLabels) {
41381                 errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
41382             }
41383             activeLabelList = activeLabelList.next;
41384             addAntecedent(postStatementLabel, currentFlow);
41385             currentFlow = finishFlowLabel(postStatementLabel);
41386         }
41387         function bindDestructuringTargetFlow(node) {
41388             if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) {
41389                 bindAssignmentTargetFlow(node.left);
41390             }
41391             else {
41392                 bindAssignmentTargetFlow(node);
41393             }
41394         }
41395         function bindAssignmentTargetFlow(node) {
41396             if (isNarrowableReference(node)) {
41397                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
41398             }
41399             else if (node.kind === 199 /* ArrayLiteralExpression */) {
41400                 for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
41401                     var e = _a[_i];
41402                     if (e.kind === 220 /* SpreadElement */) {
41403                         bindAssignmentTargetFlow(e.expression);
41404                     }
41405                     else {
41406                         bindDestructuringTargetFlow(e);
41407                     }
41408                 }
41409             }
41410             else if (node.kind === 200 /* ObjectLiteralExpression */) {
41411                 for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
41412                     var p = _c[_b];
41413                     if (p.kind === 288 /* PropertyAssignment */) {
41414                         bindDestructuringTargetFlow(p.initializer);
41415                     }
41416                     else if (p.kind === 289 /* ShorthandPropertyAssignment */) {
41417                         bindAssignmentTargetFlow(p.name);
41418                     }
41419                     else if (p.kind === 290 /* SpreadAssignment */) {
41420                         bindAssignmentTargetFlow(p.expression);
41421                     }
41422                 }
41423             }
41424         }
41425         function bindLogicalLikeExpression(node, trueTarget, falseTarget) {
41426             var preRightLabel = createBranchLabel();
41427             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 75 /* AmpersandAmpersandEqualsToken */) {
41428                 bindCondition(node.left, preRightLabel, falseTarget);
41429             }
41430             else {
41431                 bindCondition(node.left, trueTarget, preRightLabel);
41432             }
41433             currentFlow = finishFlowLabel(preRightLabel);
41434             bind(node.operatorToken);
41435             if (ts.isLogicalOrCoalescingAssignmentOperator(node.operatorToken.kind)) {
41436                 doWithConditionalBranches(bind, node.right, trueTarget, falseTarget);
41437                 bindAssignmentTargetFlow(node.left);
41438                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
41439                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
41440             }
41441             else {
41442                 bindCondition(node.right, trueTarget, falseTarget);
41443             }
41444         }
41445         function bindPrefixUnaryExpressionFlow(node) {
41446             if (node.operator === 53 /* ExclamationToken */) {
41447                 var saveTrueTarget = currentTrueTarget;
41448                 currentTrueTarget = currentFalseTarget;
41449                 currentFalseTarget = saveTrueTarget;
41450                 bindEachChild(node);
41451                 currentFalseTarget = currentTrueTarget;
41452                 currentTrueTarget = saveTrueTarget;
41453             }
41454             else {
41455                 bindEachChild(node);
41456                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
41457                     bindAssignmentTargetFlow(node.operand);
41458                 }
41459             }
41460         }
41461         function bindPostfixUnaryExpressionFlow(node) {
41462             bindEachChild(node);
41463             if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
41464                 bindAssignmentTargetFlow(node.operand);
41465             }
41466         }
41467         function bindDestructuringAssignmentFlow(node) {
41468             if (inAssignmentPattern) {
41469                 inAssignmentPattern = false;
41470                 bind(node.operatorToken);
41471                 bind(node.right);
41472                 inAssignmentPattern = true;
41473                 bind(node.left);
41474             }
41475             else {
41476                 inAssignmentPattern = true;
41477                 bind(node.left);
41478                 inAssignmentPattern = false;
41479                 bind(node.operatorToken);
41480                 bind(node.right);
41481             }
41482             bindAssignmentTargetFlow(node.left);
41483         }
41484         var BindBinaryExpressionFlowState;
41485         (function (BindBinaryExpressionFlowState) {
41486             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren";
41487             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft";
41488             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken";
41489             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight";
41490             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind";
41491         })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {}));
41492         function bindBinaryExpressionFlow(node) {
41493             var workStacks = {
41494                 expr: [node],
41495                 state: [1 /* MaybeBindLeft */],
41496                 inStrictMode: [undefined],
41497                 parent: [undefined],
41498             };
41499             var stackIndex = 0;
41500             while (stackIndex >= 0) {
41501                 node = workStacks.expr[stackIndex];
41502                 switch (workStacks.state[stackIndex]) {
41503                     case 0 /* BindThenBindChildren */: {
41504                         // This state is used only when recuring, to emulate the work that `bind` does before
41505                         // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work.
41506                         ts.setParent(node, parent);
41507                         var saveInStrictMode = inStrictMode;
41508                         bindWorker(node);
41509                         var saveParent = parent;
41510                         parent = node;
41511                         advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent);
41512                         break;
41513                     }
41514                     case 1 /* MaybeBindLeft */: {
41515                         var operator = node.operatorToken.kind;
41516                         // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions
41517                         // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too
41518                         // For now, though, since the common cases are chained `+`, leaving it recursive is fine
41519                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */ ||
41520                             ts.isLogicalOrCoalescingAssignmentOperator(operator)) {
41521                             if (isTopLevelLogicalExpression(node)) {
41522                                 var postExpressionLabel = createBranchLabel();
41523                                 bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel);
41524                                 currentFlow = finishFlowLabel(postExpressionLabel);
41525                             }
41526                             else {
41527                                 bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget);
41528                             }
41529                             completeNode();
41530                         }
41531                         else {
41532                             advanceState(2 /* BindToken */);
41533                             maybeBind(node.left);
41534                         }
41535                         break;
41536                     }
41537                     case 2 /* BindToken */: {
41538                         if (node.operatorToken.kind === 27 /* CommaToken */) {
41539                             maybeBindExpressionFlowIfCall(node.left);
41540                         }
41541                         advanceState(3 /* BindRight */);
41542                         maybeBind(node.operatorToken);
41543                         break;
41544                     }
41545                     case 3 /* BindRight */: {
41546                         advanceState(4 /* FinishBind */);
41547                         maybeBind(node.right);
41548                         break;
41549                     }
41550                     case 4 /* FinishBind */: {
41551                         var operator = node.operatorToken.kind;
41552                         if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
41553                             bindAssignmentTargetFlow(node.left);
41554                             if (operator === 62 /* EqualsToken */ && node.left.kind === 202 /* ElementAccessExpression */) {
41555                                 var elementAccess = node.left;
41556                                 if (isNarrowableOperand(elementAccess.expression)) {
41557                                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
41558                                 }
41559                             }
41560                         }
41561                         completeNode();
41562                         break;
41563                     }
41564                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow");
41565                 }
41566             }
41567             /**
41568              * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new
41569              * head state; so `advanceState` must be called before any `maybeBind` during a state's execution.
41570              */
41571             function advanceState(state, isInStrictMode, parent) {
41572                 workStacks.state[stackIndex] = state;
41573                 if (isInStrictMode !== undefined) {
41574                     workStacks.inStrictMode[stackIndex] = isInStrictMode;
41575                 }
41576                 if (parent !== undefined) {
41577                     workStacks.parent[stackIndex] = parent;
41578                 }
41579             }
41580             function completeNode() {
41581                 if (workStacks.inStrictMode[stackIndex] !== undefined) {
41582                     inStrictMode = workStacks.inStrictMode[stackIndex];
41583                     parent = workStacks.parent[stackIndex];
41584                 }
41585                 stackIndex--;
41586             }
41587             /**
41588              * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it
41589              */
41590             function maybeBind(node) {
41591                 if (node && ts.isBinaryExpression(node) && !ts.isDestructuringAssignment(node)) {
41592                     stackIndex++;
41593                     workStacks.expr[stackIndex] = node;
41594                     workStacks.state[stackIndex] = 0 /* BindThenBindChildren */;
41595                     workStacks.inStrictMode[stackIndex] = undefined;
41596                     workStacks.parent[stackIndex] = undefined;
41597                 }
41598                 else {
41599                     bind(node);
41600                 }
41601             }
41602         }
41603         function bindDeleteExpressionFlow(node) {
41604             bindEachChild(node);
41605             if (node.expression.kind === 201 /* PropertyAccessExpression */) {
41606                 bindAssignmentTargetFlow(node.expression);
41607             }
41608         }
41609         function bindConditionalExpressionFlow(node) {
41610             var trueLabel = createBranchLabel();
41611             var falseLabel = createBranchLabel();
41612             var postExpressionLabel = createBranchLabel();
41613             bindCondition(node.condition, trueLabel, falseLabel);
41614             currentFlow = finishFlowLabel(trueLabel);
41615             bind(node.questionToken);
41616             bind(node.whenTrue);
41617             addAntecedent(postExpressionLabel, currentFlow);
41618             currentFlow = finishFlowLabel(falseLabel);
41619             bind(node.colonToken);
41620             bind(node.whenFalse);
41621             addAntecedent(postExpressionLabel, currentFlow);
41622             currentFlow = finishFlowLabel(postExpressionLabel);
41623         }
41624         function bindInitializedVariableFlow(node) {
41625             var name = !ts.isOmittedExpression(node) ? node.name : undefined;
41626             if (ts.isBindingPattern(name)) {
41627                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
41628                     var child = _a[_i];
41629                     bindInitializedVariableFlow(child);
41630                 }
41631             }
41632             else {
41633                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
41634             }
41635         }
41636         function bindVariableDeclarationFlow(node) {
41637             bindEachChild(node);
41638             if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
41639                 bindInitializedVariableFlow(node);
41640             }
41641         }
41642         function bindBindingElementFlow(node) {
41643             if (ts.isBindingPattern(node.name)) {
41644                 // When evaluating a binding pattern, the initializer is evaluated before the binding pattern, per:
41645                 // - https://tc39.es/ecma262/#sec-destructuring-binding-patterns-runtime-semantics-iteratorbindinginitialization
41646                 //   - `BindingElement: BindingPattern Initializer?`
41647                 // - https://tc39.es/ecma262/#sec-runtime-semantics-keyedbindinginitialization
41648                 //   - `BindingElement: BindingPattern Initializer?`
41649                 bindEach(node.decorators);
41650                 bindEach(node.modifiers);
41651                 bind(node.dotDotDotToken);
41652                 bind(node.propertyName);
41653                 bind(node.initializer);
41654                 bind(node.name);
41655             }
41656             else {
41657                 bindEachChild(node);
41658             }
41659         }
41660         function bindJSDocTypeAlias(node) {
41661             ts.setParent(node.tagName, node);
41662             if (node.kind !== 325 /* JSDocEnumTag */ && node.fullName) {
41663                 ts.setParent(node.fullName, node);
41664                 ts.setParentRecursive(node.fullName, /*incremental*/ false);
41665             }
41666         }
41667         function bindJSDocClassTag(node) {
41668             bindEachChild(node);
41669             var host = ts.getHostSignatureFromJSDoc(node);
41670             if (host && host.kind !== 165 /* MethodDeclaration */) {
41671                 addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
41672             }
41673         }
41674         function bindOptionalExpression(node, trueTarget, falseTarget) {
41675             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
41676             if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) {
41677                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
41678                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
41679             }
41680         }
41681         function bindOptionalChainRest(node) {
41682             switch (node.kind) {
41683                 case 201 /* PropertyAccessExpression */:
41684                     bind(node.questionDotToken);
41685                     bind(node.name);
41686                     break;
41687                 case 202 /* ElementAccessExpression */:
41688                     bind(node.questionDotToken);
41689                     bind(node.argumentExpression);
41690                     break;
41691                 case 203 /* CallExpression */:
41692                     bind(node.questionDotToken);
41693                     bindEach(node.typeArguments);
41694                     bindEach(node.arguments);
41695                     break;
41696             }
41697         }
41698         function bindOptionalChain(node, trueTarget, falseTarget) {
41699             // For an optional chain, we emulate the behavior of a logical expression:
41700             //
41701             // a?.b         -> a && a.b
41702             // a?.b.c       -> a && a.b.c
41703             // a?.b?.c      -> a && a.b && a.b.c
41704             // a?.[x = 1]   -> a && a[x = 1]
41705             //
41706             // To do this we descend through the chain until we reach the root of a chain (the expression with a `?.`)
41707             // and build it's CFA graph as if it were the first condition (`a && ...`). Then we bind the rest
41708             // of the node as part of the "true" branch, and continue to do so as we ascend back up to the outermost
41709             // chain node. We then treat the entire node as the right side of the expression.
41710             var preChainLabel = ts.isOptionalChainRoot(node) ? createBranchLabel() : undefined;
41711             bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
41712             if (preChainLabel) {
41713                 currentFlow = finishFlowLabel(preChainLabel);
41714             }
41715             doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
41716             if (ts.isOutermostOptionalChain(node)) {
41717                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
41718                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
41719             }
41720         }
41721         function bindOptionalChainFlow(node) {
41722             if (isTopLevelLogicalExpression(node)) {
41723                 var postExpressionLabel = createBranchLabel();
41724                 bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
41725                 currentFlow = finishFlowLabel(postExpressionLabel);
41726             }
41727             else {
41728                 bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
41729             }
41730         }
41731         function bindNonNullExpressionFlow(node) {
41732             if (ts.isOptionalChain(node)) {
41733                 bindOptionalChainFlow(node);
41734             }
41735             else {
41736                 bindEachChild(node);
41737             }
41738         }
41739         function bindAccessExpressionFlow(node) {
41740             if (ts.isOptionalChain(node)) {
41741                 bindOptionalChainFlow(node);
41742             }
41743             else {
41744                 bindEachChild(node);
41745             }
41746         }
41747         function bindCallExpressionFlow(node) {
41748             if (ts.isOptionalChain(node)) {
41749                 bindOptionalChainFlow(node);
41750             }
41751             else {
41752                 // If the target of the call expression is a function expression or arrow function we have
41753                 // an immediately invoked function expression (IIFE). Initialize the flowNode property to
41754                 // the current control flow (which includes evaluation of the IIFE arguments).
41755                 var expr = ts.skipParentheses(node.expression);
41756                 if (expr.kind === 208 /* FunctionExpression */ || expr.kind === 209 /* ArrowFunction */) {
41757                     bindEach(node.typeArguments);
41758                     bindEach(node.arguments);
41759                     bind(node.expression);
41760                 }
41761                 else {
41762                     bindEachChild(node);
41763                     if (node.expression.kind === 105 /* SuperKeyword */) {
41764                         currentFlow = createFlowCall(currentFlow, node);
41765                     }
41766                 }
41767             }
41768             if (node.expression.kind === 201 /* PropertyAccessExpression */) {
41769                 var propertyAccess = node.expression;
41770                 if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
41771                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
41772                 }
41773             }
41774         }
41775         function getContainerFlags(node) {
41776             switch (node.kind) {
41777                 case 221 /* ClassExpression */:
41778                 case 252 /* ClassDeclaration */:
41779                 case 255 /* EnumDeclaration */:
41780                 case 200 /* ObjectLiteralExpression */:
41781                 case 177 /* TypeLiteral */:
41782                 case 312 /* JSDocTypeLiteral */:
41783                 case 281 /* JsxAttributes */:
41784                     return 1 /* IsContainer */;
41785                 case 253 /* InterfaceDeclaration */:
41786                     return 1 /* IsContainer */ | 64 /* IsInterface */;
41787                 case 256 /* ModuleDeclaration */:
41788                 case 254 /* TypeAliasDeclaration */:
41789                 case 190 /* MappedType */:
41790                     return 1 /* IsContainer */ | 32 /* HasLocals */;
41791                 case 297 /* SourceFile */:
41792                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
41793                 case 165 /* MethodDeclaration */:
41794                     if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
41795                         return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */;
41796                     }
41797                 // falls through
41798                 case 166 /* Constructor */:
41799                 case 251 /* FunctionDeclaration */:
41800                 case 164 /* MethodSignature */:
41801                 case 167 /* GetAccessor */:
41802                 case 168 /* SetAccessor */:
41803                 case 169 /* CallSignature */:
41804                 case 313 /* JSDocSignature */:
41805                 case 308 /* JSDocFunctionType */:
41806                 case 174 /* FunctionType */:
41807                 case 170 /* ConstructSignature */:
41808                 case 171 /* IndexSignature */:
41809                 case 175 /* ConstructorType */:
41810                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
41811                 case 208 /* FunctionExpression */:
41812                 case 209 /* ArrowFunction */:
41813                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
41814                 case 257 /* ModuleBlock */:
41815                     return 4 /* IsControlFlowContainer */;
41816                 case 163 /* PropertyDeclaration */:
41817                     return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
41818                 case 287 /* CatchClause */:
41819                 case 237 /* ForStatement */:
41820                 case 238 /* ForInStatement */:
41821                 case 239 /* ForOfStatement */:
41822                 case 258 /* CaseBlock */:
41823                     return 2 /* IsBlockScopedContainer */;
41824                 case 230 /* Block */:
41825                     // do not treat blocks directly inside a function as a block-scoped-container.
41826                     // Locals that reside in this block should go to the function locals. Otherwise 'x'
41827                     // would not appear to be a redeclaration of a block scoped local in the following
41828                     // example:
41829                     //
41830                     //      function foo() {
41831                     //          var x;
41832                     //          let x;
41833                     //      }
41834                     //
41835                     // If we placed 'var x' into the function locals and 'let x' into the locals of
41836                     // the block, then there would be no collision.
41837                     //
41838                     // By not creating a new block-scoped-container here, we ensure that both 'var x'
41839                     // and 'let x' go into the Function-container's locals, and we do get a collision
41840                     // conflict.
41841                     return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
41842             }
41843             return 0 /* None */;
41844         }
41845         function addToContainerChain(next) {
41846             if (lastContainer) {
41847                 lastContainer.nextContainer = next;
41848             }
41849             lastContainer = next;
41850         }
41851         function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
41852             switch (container.kind) {
41853                 // Modules, source files, and classes need specialized handling for how their
41854                 // members are declared (for example, a member of a class will go into a specific
41855                 // symbol table depending on if it is static or not). We defer to specialized
41856                 // handlers to take care of declaring these child members.
41857                 case 256 /* ModuleDeclaration */:
41858                     return declareModuleMember(node, symbolFlags, symbolExcludes);
41859                 case 297 /* SourceFile */:
41860                     return declareSourceFileMember(node, symbolFlags, symbolExcludes);
41861                 case 221 /* ClassExpression */:
41862                 case 252 /* ClassDeclaration */:
41863                     return declareClassMember(node, symbolFlags, symbolExcludes);
41864                 case 255 /* EnumDeclaration */:
41865                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
41866                 case 177 /* TypeLiteral */:
41867                 case 312 /* JSDocTypeLiteral */:
41868                 case 200 /* ObjectLiteralExpression */:
41869                 case 253 /* InterfaceDeclaration */:
41870                 case 281 /* JsxAttributes */:
41871                     // Interface/Object-types always have their children added to the 'members' of
41872                     // their container. They are only accessible through an instance of their
41873                     // container, and are never in scope otherwise (even inside the body of the
41874                     // object / type / interface declaring them). An exception is type parameters,
41875                     // which are in scope without qualification (similar to 'locals').
41876                     return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
41877                 case 174 /* FunctionType */:
41878                 case 175 /* ConstructorType */:
41879                 case 169 /* CallSignature */:
41880                 case 170 /* ConstructSignature */:
41881                 case 313 /* JSDocSignature */:
41882                 case 171 /* IndexSignature */:
41883                 case 165 /* MethodDeclaration */:
41884                 case 164 /* MethodSignature */:
41885                 case 166 /* Constructor */:
41886                 case 167 /* GetAccessor */:
41887                 case 168 /* SetAccessor */:
41888                 case 251 /* FunctionDeclaration */:
41889                 case 208 /* FunctionExpression */:
41890                 case 209 /* ArrowFunction */:
41891                 case 308 /* JSDocFunctionType */:
41892                 case 331 /* JSDocTypedefTag */:
41893                 case 324 /* JSDocCallbackTag */:
41894                 case 254 /* TypeAliasDeclaration */:
41895                 case 190 /* MappedType */:
41896                     // All the children of these container types are never visible through another
41897                     // symbol (i.e. through another symbol's 'exports' or 'members').  Instead,
41898                     // they're only accessed 'lexically' (i.e. from code that exists underneath
41899                     // their container in the tree). To accomplish this, we simply add their declared
41900                     // symbol to the 'locals' of the container.  These symbols can then be found as
41901                     // the type checker walks up the containers, checking them for matching names.
41902                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
41903             }
41904         }
41905         function declareClassMember(node, symbolFlags, symbolExcludes) {
41906             return ts.hasSyntacticModifier(node, 32 /* Static */)
41907                 ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
41908                 : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
41909         }
41910         function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
41911             return ts.isExternalModule(file)
41912                 ? declareModuleMember(node, symbolFlags, symbolExcludes)
41913                 : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
41914         }
41915         function hasExportDeclarations(node) {
41916             var body = ts.isSourceFile(node) ? node : ts.tryCast(node.body, ts.isModuleBlock);
41917             return !!body && body.statements.some(function (s) { return ts.isExportDeclaration(s) || ts.isExportAssignment(s); });
41918         }
41919         function setExportContextFlag(node) {
41920             // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
41921             // declarations with export modifiers) is an export context in which declarations are implicitly exported.
41922             if (node.flags & 8388608 /* Ambient */ && !hasExportDeclarations(node)) {
41923                 node.flags |= 64 /* ExportContext */;
41924             }
41925             else {
41926                 node.flags &= ~64 /* ExportContext */;
41927             }
41928         }
41929         function bindModuleDeclaration(node) {
41930             setExportContextFlag(node);
41931             if (ts.isAmbientModule(node)) {
41932                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
41933                     errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
41934                 }
41935                 if (ts.isModuleAugmentationExternal(node)) {
41936                     declareModuleSymbol(node);
41937                 }
41938                 else {
41939                     var pattern = void 0;
41940                     if (node.name.kind === 10 /* StringLiteral */) {
41941                         var text = node.name.text;
41942                         if (ts.hasZeroOrOneAsteriskCharacter(text)) {
41943                             pattern = ts.tryParsePattern(text);
41944                         }
41945                         else {
41946                             errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
41947                         }
41948                     }
41949                     var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
41950                     file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
41951                 }
41952             }
41953             else {
41954                 var state = declareModuleSymbol(node);
41955                 if (state !== 0 /* NonInstantiated */) {
41956                     var symbol = node.symbol;
41957                     // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
41958                     symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
41959                         // Current must be `const enum` only
41960                         && state === 2 /* ConstEnumOnly */
41961                         // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
41962                         && symbol.constEnumOnlyModule !== false;
41963                 }
41964             }
41965         }
41966         function declareModuleSymbol(node) {
41967             var state = getModuleInstanceState(node);
41968             var instantiated = state !== 0 /* NonInstantiated */;
41969             declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
41970             return state;
41971         }
41972         function bindFunctionOrConstructorType(node) {
41973             // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
41974             // to the one we would get for: { <...>(...): T }
41975             //
41976             // We do that by making an anonymous type literal symbol, and then setting the function
41977             // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
41978             // from an actual type literal symbol you would have gotten had you used the long form.
41979             var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
41980             addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
41981             var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
41982             addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
41983             typeLiteralSymbol.members = ts.createSymbolTable();
41984             typeLiteralSymbol.members.set(symbol.escapedName, symbol);
41985         }
41986         function bindObjectLiteralExpression(node) {
41987             var ElementKind;
41988             (function (ElementKind) {
41989                 ElementKind[ElementKind["Property"] = 1] = "Property";
41990                 ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
41991             })(ElementKind || (ElementKind = {}));
41992             if (inStrictMode && !ts.isAssignmentTarget(node)) {
41993                 var seen = new ts.Map();
41994                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
41995                     var prop = _a[_i];
41996                     if (prop.kind === 290 /* SpreadAssignment */ || prop.name.kind !== 78 /* Identifier */) {
41997                         continue;
41998                     }
41999                     var identifier = prop.name;
42000                     // ECMA-262 11.1.5 Object Initializer
42001                     // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
42002                     // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
42003                     // IsDataDescriptor(propId.descriptor) is true.
42004                     //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
42005                     //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
42006                     //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
42007                     // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
42008                     var currentKind = prop.kind === 288 /* PropertyAssignment */ || prop.kind === 289 /* ShorthandPropertyAssignment */ || prop.kind === 165 /* MethodDeclaration */
42009                         ? 1 /* Property */
42010                         : 2 /* Accessor */;
42011                     var existingKind = seen.get(identifier.escapedText);
42012                     if (!existingKind) {
42013                         seen.set(identifier.escapedText, currentKind);
42014                         continue;
42015                     }
42016                     if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
42017                         var span = ts.getErrorSpanForNode(file, identifier);
42018                         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));
42019                     }
42020                 }
42021             }
42022             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
42023         }
42024         function bindJsxAttributes(node) {
42025             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
42026         }
42027         function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
42028             return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
42029         }
42030         function bindAnonymousDeclaration(node, symbolFlags, name) {
42031             var symbol = createSymbol(symbolFlags, name);
42032             if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
42033                 symbol.parent = container.symbol;
42034             }
42035             addDeclarationToSymbol(symbol, node, symbolFlags);
42036             return symbol;
42037         }
42038         function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
42039             switch (blockScopeContainer.kind) {
42040                 case 256 /* ModuleDeclaration */:
42041                     declareModuleMember(node, symbolFlags, symbolExcludes);
42042                     break;
42043                 case 297 /* SourceFile */:
42044                     if (ts.isExternalOrCommonJsModule(container)) {
42045                         declareModuleMember(node, symbolFlags, symbolExcludes);
42046                         break;
42047                     }
42048                 // falls through
42049                 default:
42050                     if (!blockScopeContainer.locals) {
42051                         blockScopeContainer.locals = ts.createSymbolTable();
42052                         addToContainerChain(blockScopeContainer);
42053                     }
42054                     declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
42055             }
42056         }
42057         function delayedBindJSDocTypedefTag() {
42058             if (!delayedTypeAliases) {
42059                 return;
42060             }
42061             var saveContainer = container;
42062             var saveLastContainer = lastContainer;
42063             var saveBlockScopeContainer = blockScopeContainer;
42064             var saveParent = parent;
42065             var saveCurrentFlow = currentFlow;
42066             for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
42067                 var typeAlias = delayedTypeAliases_1[_i];
42068                 var host = ts.getJSDocHost(typeAlias);
42069                 container = (host && ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); })) || file;
42070                 blockScopeContainer = (host && ts.getEnclosingBlockScopeContainer(host)) || file;
42071                 currentFlow = initFlowNode({ flags: 2 /* Start */ });
42072                 parent = typeAlias;
42073                 bind(typeAlias.typeExpression);
42074                 var declName = ts.getNameOfDeclaration(typeAlias);
42075                 if ((ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && ts.isPropertyAccessEntityNameExpression(declName.parent)) {
42076                     // typedef anchored to an A.B.C assignment - we need to bind into B's namespace under name C
42077                     var isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
42078                     if (isTopLevel) {
42079                         bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!ts.findAncestor(declName, function (d) { return ts.isPropertyAccessExpression(d) && d.name.escapedText === "prototype"; }), /*containerIsClass*/ false);
42080                         var oldContainer = container;
42081                         switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
42082                             case 1 /* ExportsProperty */:
42083                             case 2 /* ModuleExports */:
42084                                 if (!ts.isExternalOrCommonJsModule(file)) {
42085                                     container = undefined;
42086                                 }
42087                                 else {
42088                                     container = file;
42089                                 }
42090                                 break;
42091                             case 4 /* ThisProperty */:
42092                                 container = declName.parent.expression;
42093                                 break;
42094                             case 3 /* PrototypeProperty */:
42095                                 container = declName.parent.expression.name;
42096                                 break;
42097                             case 5 /* Property */:
42098                                 container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file
42099                                     : ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name
42100                                         : declName.parent.expression;
42101                                 break;
42102                             case 0 /* None */:
42103                                 return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
42104                         }
42105                         if (container) {
42106                             declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
42107                         }
42108                         container = oldContainer;
42109                     }
42110                 }
42111                 else if (ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 78 /* Identifier */) {
42112                     parent = typeAlias.parent;
42113                     bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
42114                 }
42115                 else {
42116                     bind(typeAlias.fullName);
42117                 }
42118             }
42119             container = saveContainer;
42120             lastContainer = saveLastContainer;
42121             blockScopeContainer = saveBlockScopeContainer;
42122             parent = saveParent;
42123             currentFlow = saveCurrentFlow;
42124         }
42125         // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
42126         // check for reserved words used as identifiers in strict mode code, as well as `yield` or `await` in
42127         // [Yield] or [Await] contexts, respectively.
42128         function checkContextualIdentifier(node) {
42129             // Report error only if there are no parse errors in file
42130             if (!file.parseDiagnostics.length &&
42131                 !(node.flags & 8388608 /* Ambient */) &&
42132                 !(node.flags & 4194304 /* JSDoc */) &&
42133                 !ts.isIdentifierName(node)) {
42134                 // strict mode identifiers
42135                 if (inStrictMode &&
42136                     node.originalKeywordKind >= 116 /* FirstFutureReservedWord */ &&
42137                     node.originalKeywordKind <= 124 /* LastFutureReservedWord */) {
42138                     file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
42139                 }
42140                 else if (node.originalKeywordKind === 130 /* AwaitKeyword */) {
42141                     if (ts.isExternalModule(file) && ts.isInTopLevelContext(node)) {
42142                         file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module, ts.declarationNameToString(node)));
42143                     }
42144                     else if (node.flags & 32768 /* AwaitContext */) {
42145                         file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, ts.declarationNameToString(node)));
42146                     }
42147                 }
42148                 else if (node.originalKeywordKind === 124 /* YieldKeyword */ && node.flags & 8192 /* YieldContext */) {
42149                     file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, ts.declarationNameToString(node)));
42150                 }
42151             }
42152         }
42153         function getStrictModeIdentifierMessage(node) {
42154             // Provide specialized messages to help the user understand why we think they're in
42155             // strict mode.
42156             if (ts.getContainingClass(node)) {
42157                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
42158             }
42159             if (file.externalModuleIndicator) {
42160                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
42161             }
42162             return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
42163         }
42164         // The binder visits every node, so this is a good place to check for
42165         // the reserved private name (there is only one)
42166         function checkPrivateIdentifier(node) {
42167             if (node.escapedText === "#constructor") {
42168                 // Report error only if there are no parse errors in file
42169                 if (!file.parseDiagnostics.length) {
42170                     file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.constructor_is_a_reserved_word, ts.declarationNameToString(node)));
42171                 }
42172             }
42173         }
42174         function checkStrictModeBinaryExpression(node) {
42175             if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
42176                 // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
42177                 // Assignment operator(11.13) or of a PostfixExpression(11.3)
42178                 checkStrictModeEvalOrArguments(node, node.left);
42179             }
42180         }
42181         function checkStrictModeCatchClause(node) {
42182             // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
42183             // Catch production is eval or arguments
42184             if (inStrictMode && node.variableDeclaration) {
42185                 checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
42186             }
42187         }
42188         function checkStrictModeDeleteExpression(node) {
42189             // Grammar checking
42190             if (inStrictMode && node.expression.kind === 78 /* Identifier */) {
42191                 // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
42192                 // UnaryExpression is a direct reference to a variable, function argument, or function name
42193                 var span = ts.getErrorSpanForNode(file, node.expression);
42194                 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
42195             }
42196         }
42197         function isEvalOrArgumentsIdentifier(node) {
42198             return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
42199         }
42200         function checkStrictModeEvalOrArguments(contextNode, name) {
42201             if (name && name.kind === 78 /* Identifier */) {
42202                 var identifier = name;
42203                 if (isEvalOrArgumentsIdentifier(identifier)) {
42204                     // We check first if the name is inside class declaration or class expression; if so give explicit message
42205                     // otherwise report generic error message.
42206                     var span = ts.getErrorSpanForNode(file, name);
42207                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
42208                 }
42209             }
42210         }
42211         function getStrictModeEvalOrArgumentsMessage(node) {
42212             // Provide specialized messages to help the user understand why we think they're in
42213             // strict mode.
42214             if (ts.getContainingClass(node)) {
42215                 return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
42216             }
42217             if (file.externalModuleIndicator) {
42218                 return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
42219             }
42220             return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
42221         }
42222         function checkStrictModeFunctionName(node) {
42223             if (inStrictMode) {
42224                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
42225                 checkStrictModeEvalOrArguments(node, node.name);
42226             }
42227         }
42228         function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
42229             // Provide specialized messages to help the user understand why we think they're in
42230             // strict mode.
42231             if (ts.getContainingClass(node)) {
42232                 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;
42233             }
42234             if (file.externalModuleIndicator) {
42235                 return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
42236             }
42237             return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
42238         }
42239         function checkStrictModeFunctionDeclaration(node) {
42240             if (languageVersion < 2 /* ES2015 */) {
42241                 // Report error if function is not top level function declaration
42242                 if (blockScopeContainer.kind !== 297 /* SourceFile */ &&
42243                     blockScopeContainer.kind !== 256 /* ModuleDeclaration */ &&
42244                     !ts.isFunctionLike(blockScopeContainer)) {
42245                     // We check first if the name is inside class declaration or class expression; if so give explicit message
42246                     // otherwise report generic error message.
42247                     var errorSpan = ts.getErrorSpanForNode(file, node);
42248                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
42249                 }
42250             }
42251         }
42252         function checkStrictModeNumericLiteral(node) {
42253             if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
42254                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
42255             }
42256         }
42257         function checkStrictModePostfixUnaryExpression(node) {
42258             // Grammar checking
42259             // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
42260             // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
42261             // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
42262             if (inStrictMode) {
42263                 checkStrictModeEvalOrArguments(node, node.operand);
42264             }
42265         }
42266         function checkStrictModePrefixUnaryExpression(node) {
42267             // Grammar checking
42268             if (inStrictMode) {
42269                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
42270                     checkStrictModeEvalOrArguments(node, node.operand);
42271                 }
42272             }
42273         }
42274         function checkStrictModeWithStatement(node) {
42275             // Grammar checking for withStatement
42276             if (inStrictMode) {
42277                 errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
42278             }
42279         }
42280         function checkStrictModeLabeledStatement(node) {
42281             // Grammar checking for labeledStatement
42282             if (inStrictMode && options.target >= 2 /* ES2015 */) {
42283                 if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
42284                     errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
42285                 }
42286             }
42287         }
42288         function errorOnFirstToken(node, message, arg0, arg1, arg2) {
42289             var span = ts.getSpanOfTokenAtPosition(file, node.pos);
42290             file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
42291         }
42292         function errorOrSuggestionOnNode(isError, node, message) {
42293             errorOrSuggestionOnRange(isError, node, node, message);
42294         }
42295         function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
42296             addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
42297         }
42298         function addErrorOrSuggestionDiagnostic(isError, range, message) {
42299             var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
42300             if (isError) {
42301                 file.bindDiagnostics.push(diag);
42302             }
42303             else {
42304                 file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
42305             }
42306         }
42307         function bind(node) {
42308             if (!node) {
42309                 return;
42310             }
42311             ts.setParent(node, parent);
42312             var saveInStrictMode = inStrictMode;
42313             // Even though in the AST the jsdoc @typedef node belongs to the current node,
42314             // its symbol might be in the same scope with the current node's symbol. Consider:
42315             //
42316             //     /** @typedef {string | number} MyType */
42317             //     function foo();
42318             //
42319             // Here the current node is "foo", which is a container, but the scope of "MyType" should
42320             // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
42321             // and skip binding this tag later when binding all the other jsdoc tags.
42322             // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
42323             // and then potentially add the symbol to an appropriate symbol table. Possible
42324             // destination symbol tables are:
42325             //
42326             //  1) The 'exports' table of the current container's symbol.
42327             //  2) The 'members' table of the current container's symbol.
42328             //  3) The 'locals' table of the current container.
42329             //
42330             // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
42331             // (like TypeLiterals for example) will not be put in any table.
42332             bindWorker(node);
42333             // Then we recurse into the children of the node to bind them as well. For certain
42334             // symbols we do specialized work when we recurse. For example, we'll keep track of
42335             // the current 'container' node when it changes. This helps us know which symbol table
42336             // a local should go into for example. Since terminal nodes are known not to have
42337             // children, as an optimization we don't process those.
42338             if (node.kind > 156 /* LastToken */) {
42339                 var saveParent = parent;
42340                 parent = node;
42341                 var containerFlags = getContainerFlags(node);
42342                 if (containerFlags === 0 /* None */) {
42343                     bindChildren(node);
42344                 }
42345                 else {
42346                     bindContainer(node, containerFlags);
42347                 }
42348                 parent = saveParent;
42349             }
42350             else {
42351                 var saveParent = parent;
42352                 if (node.kind === 1 /* EndOfFileToken */)
42353                     parent = node;
42354                 bindJSDoc(node);
42355                 parent = saveParent;
42356             }
42357             inStrictMode = saveInStrictMode;
42358         }
42359         function bindJSDoc(node) {
42360             if (ts.hasJSDocNodes(node)) {
42361                 if (ts.isInJSFile(node)) {
42362                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
42363                         var j = _a[_i];
42364                         bind(j);
42365                     }
42366                 }
42367                 else {
42368                     for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
42369                         var j = _c[_b];
42370                         ts.setParent(j, node);
42371                         ts.setParentRecursive(j, /*incremental*/ false);
42372                     }
42373                 }
42374             }
42375         }
42376         function updateStrictModeStatementList(statements) {
42377             if (!inStrictMode) {
42378                 for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
42379                     var statement = statements_3[_i];
42380                     if (!ts.isPrologueDirective(statement)) {
42381                         return;
42382                     }
42383                     if (isUseStrictPrologueDirective(statement)) {
42384                         inStrictMode = true;
42385                         return;
42386                     }
42387                 }
42388             }
42389         }
42390         /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
42391         function isUseStrictPrologueDirective(node) {
42392             var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
42393             // Note: the node text must be exactly "use strict" or 'use strict'.  It is not ok for the
42394             // string to contain unicode escapes (as per ES5).
42395             return nodeText === '"use strict"' || nodeText === "'use strict'";
42396         }
42397         function bindWorker(node) {
42398             switch (node.kind) {
42399                 /* Strict mode checks */
42400                 case 78 /* Identifier */:
42401                     // for typedef type names with namespaces, bind the new jsdoc type symbol here
42402                     // because it requires all containing namespaces to be in effect, namely the
42403                     // current "blockScopeContainer" needs to be set to its immediate namespace parent.
42404                     if (node.isInJSDocNamespace) {
42405                         var parentNode = node.parent;
42406                         while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
42407                             parentNode = parentNode.parent;
42408                         }
42409                         bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
42410                         break;
42411                     }
42412                 // falls through
42413                 case 107 /* ThisKeyword */:
42414                     if (currentFlow && (ts.isExpression(node) || parent.kind === 289 /* ShorthandPropertyAssignment */)) {
42415                         node.flowNode = currentFlow;
42416                     }
42417                     return checkContextualIdentifier(node);
42418                 case 157 /* QualifiedName */:
42419                     if (currentFlow && parent.kind === 176 /* TypeQuery */) {
42420                         node.flowNode = currentFlow;
42421                     }
42422                     break;
42423                 case 105 /* SuperKeyword */:
42424                     node.flowNode = currentFlow;
42425                     break;
42426                 case 79 /* PrivateIdentifier */:
42427                     return checkPrivateIdentifier(node);
42428                 case 201 /* PropertyAccessExpression */:
42429                 case 202 /* ElementAccessExpression */:
42430                     var expr = node;
42431                     if (currentFlow && isNarrowableReference(expr)) {
42432                         expr.flowNode = currentFlow;
42433                     }
42434                     if (ts.isSpecialPropertyDeclaration(expr)) {
42435                         bindSpecialPropertyDeclaration(expr);
42436                     }
42437                     if (ts.isInJSFile(expr) &&
42438                         file.commonJsModuleIndicator &&
42439                         ts.isModuleExportsAccessExpression(expr) &&
42440                         !lookupSymbolForName(blockScopeContainer, "module")) {
42441                         declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */);
42442                     }
42443                     break;
42444                 case 216 /* BinaryExpression */:
42445                     var specialKind = ts.getAssignmentDeclarationKind(node);
42446                     switch (specialKind) {
42447                         case 1 /* ExportsProperty */:
42448                             bindExportsPropertyAssignment(node);
42449                             break;
42450                         case 2 /* ModuleExports */:
42451                             bindModuleExportsAssignment(node);
42452                             break;
42453                         case 3 /* PrototypeProperty */:
42454                             bindPrototypePropertyAssignment(node.left, node);
42455                             break;
42456                         case 6 /* Prototype */:
42457                             bindPrototypeAssignment(node);
42458                             break;
42459                         case 4 /* ThisProperty */:
42460                             bindThisPropertyAssignment(node);
42461                             break;
42462                         case 5 /* Property */:
42463                             var expression = node.left.expression;
42464                             if (ts.isInJSFile(node) && ts.isIdentifier(expression)) {
42465                                 var symbol = lookupSymbolForName(blockScopeContainer, expression.escapedText);
42466                                 if (ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration)) {
42467                                     bindThisPropertyAssignment(node);
42468                                     break;
42469                                 }
42470                             }
42471                             bindSpecialPropertyAssignment(node);
42472                             break;
42473                         case 0 /* None */:
42474                             // Nothing to do
42475                             break;
42476                         default:
42477                             ts.Debug.fail("Unknown binary expression special property assignment kind");
42478                     }
42479                     return checkStrictModeBinaryExpression(node);
42480                 case 287 /* CatchClause */:
42481                     return checkStrictModeCatchClause(node);
42482                 case 210 /* DeleteExpression */:
42483                     return checkStrictModeDeleteExpression(node);
42484                 case 8 /* NumericLiteral */:
42485                     return checkStrictModeNumericLiteral(node);
42486                 case 215 /* PostfixUnaryExpression */:
42487                     return checkStrictModePostfixUnaryExpression(node);
42488                 case 214 /* PrefixUnaryExpression */:
42489                     return checkStrictModePrefixUnaryExpression(node);
42490                 case 243 /* WithStatement */:
42491                     return checkStrictModeWithStatement(node);
42492                 case 245 /* LabeledStatement */:
42493                     return checkStrictModeLabeledStatement(node);
42494                 case 187 /* ThisType */:
42495                     seenThisKeyword = true;
42496                     return;
42497                 case 172 /* TypePredicate */:
42498                     break; // Binding the children will handle everything
42499                 case 159 /* TypeParameter */:
42500                     return bindTypeParameter(node);
42501                 case 160 /* Parameter */:
42502                     return bindParameter(node);
42503                 case 249 /* VariableDeclaration */:
42504                     return bindVariableDeclarationOrBindingElement(node);
42505                 case 198 /* BindingElement */:
42506                     node.flowNode = currentFlow;
42507                     return bindVariableDeclarationOrBindingElement(node);
42508                 case 163 /* PropertyDeclaration */:
42509                 case 162 /* PropertySignature */:
42510                     return bindPropertyWorker(node);
42511                 case 288 /* PropertyAssignment */:
42512                 case 289 /* ShorthandPropertyAssignment */:
42513                     return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
42514                 case 291 /* EnumMember */:
42515                     return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
42516                 case 169 /* CallSignature */:
42517                 case 170 /* ConstructSignature */:
42518                 case 171 /* IndexSignature */:
42519                     return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
42520                 case 165 /* MethodDeclaration */:
42521                 case 164 /* MethodSignature */:
42522                     // If this is an ObjectLiteralExpression method, then it sits in the same space
42523                     // as other properties in the object literal.  So we use SymbolFlags.PropertyExcludes
42524                     // so that it will conflict with any other object literal members with the same
42525                     // name.
42526                     return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
42527                 case 251 /* FunctionDeclaration */:
42528                     return bindFunctionDeclaration(node);
42529                 case 166 /* Constructor */:
42530                     return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
42531                 case 167 /* GetAccessor */:
42532                     return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
42533                 case 168 /* SetAccessor */:
42534                     return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
42535                 case 174 /* FunctionType */:
42536                 case 308 /* JSDocFunctionType */:
42537                 case 313 /* JSDocSignature */:
42538                 case 175 /* ConstructorType */:
42539                     return bindFunctionOrConstructorType(node);
42540                 case 177 /* TypeLiteral */:
42541                 case 312 /* JSDocTypeLiteral */:
42542                 case 190 /* MappedType */:
42543                     return bindAnonymousTypeWorker(node);
42544                 case 319 /* JSDocClassTag */:
42545                     return bindJSDocClassTag(node);
42546                 case 200 /* ObjectLiteralExpression */:
42547                     return bindObjectLiteralExpression(node);
42548                 case 208 /* FunctionExpression */:
42549                 case 209 /* ArrowFunction */:
42550                     return bindFunctionExpression(node);
42551                 case 203 /* CallExpression */:
42552                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
42553                     switch (assignmentKind) {
42554                         case 7 /* ObjectDefinePropertyValue */:
42555                             return bindObjectDefinePropertyAssignment(node);
42556                         case 8 /* ObjectDefinePropertyExports */:
42557                             return bindObjectDefinePropertyExport(node);
42558                         case 9 /* ObjectDefinePrototypeProperty */:
42559                             return bindObjectDefinePrototypeProperty(node);
42560                         case 0 /* None */:
42561                             break; // Nothing to do
42562                         default:
42563                             return ts.Debug.fail("Unknown call expression assignment declaration kind");
42564                     }
42565                     if (ts.isInJSFile(node)) {
42566                         bindCallExpression(node);
42567                     }
42568                     break;
42569                 // Members of classes, interfaces, and modules
42570                 case 221 /* ClassExpression */:
42571                 case 252 /* ClassDeclaration */:
42572                     // All classes are automatically in strict mode in ES6.
42573                     inStrictMode = true;
42574                     return bindClassLikeDeclaration(node);
42575                 case 253 /* InterfaceDeclaration */:
42576                     return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
42577                 case 254 /* TypeAliasDeclaration */:
42578                     return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
42579                 case 255 /* EnumDeclaration */:
42580                     return bindEnumDeclaration(node);
42581                 case 256 /* ModuleDeclaration */:
42582                     return bindModuleDeclaration(node);
42583                 // Jsx-attributes
42584                 case 281 /* JsxAttributes */:
42585                     return bindJsxAttributes(node);
42586                 case 280 /* JsxAttribute */:
42587                     return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
42588                 // Imports and exports
42589                 case 260 /* ImportEqualsDeclaration */:
42590                 case 263 /* NamespaceImport */:
42591                 case 265 /* ImportSpecifier */:
42592                 case 270 /* ExportSpecifier */:
42593                     return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
42594                 case 259 /* NamespaceExportDeclaration */:
42595                     return bindNamespaceExportDeclaration(node);
42596                 case 262 /* ImportClause */:
42597                     return bindImportClause(node);
42598                 case 267 /* ExportDeclaration */:
42599                     return bindExportDeclaration(node);
42600                 case 266 /* ExportAssignment */:
42601                     return bindExportAssignment(node);
42602                 case 297 /* SourceFile */:
42603                     updateStrictModeStatementList(node.statements);
42604                     return bindSourceFileIfExternalModule();
42605                 case 230 /* Block */:
42606                     if (!ts.isFunctionLike(node.parent)) {
42607                         return;
42608                     }
42609                 // falls through
42610                 case 257 /* ModuleBlock */:
42611                     return updateStrictModeStatementList(node.statements);
42612                 case 326 /* JSDocParameterTag */:
42613                     if (node.parent.kind === 313 /* JSDocSignature */) {
42614                         return bindParameter(node);
42615                     }
42616                     if (node.parent.kind !== 312 /* JSDocTypeLiteral */) {
42617                         break;
42618                     }
42619                 // falls through
42620                 case 333 /* JSDocPropertyTag */:
42621                     var propTag = node;
42622                     var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 307 /* JSDocOptionalType */ ?
42623                         4 /* Property */ | 16777216 /* Optional */ :
42624                         4 /* Property */;
42625                     return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
42626                 case 331 /* JSDocTypedefTag */:
42627                 case 324 /* JSDocCallbackTag */:
42628                 case 325 /* JSDocEnumTag */:
42629                     return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
42630             }
42631         }
42632         function bindPropertyWorker(node) {
42633             return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
42634         }
42635         function bindAnonymousTypeWorker(node) {
42636             return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
42637         }
42638         function bindSourceFileIfExternalModule() {
42639             setExportContextFlag(file);
42640             if (ts.isExternalModule(file)) {
42641                 bindSourceFileAsExternalModule();
42642             }
42643             else if (ts.isJsonSourceFile(file)) {
42644                 bindSourceFileAsExternalModule();
42645                 // Create symbol equivalent for the module.exports = {}
42646                 var originalSymbol = file.symbol;
42647                 declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
42648                 file.symbol = originalSymbol;
42649             }
42650         }
42651         function bindSourceFileAsExternalModule() {
42652             bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
42653         }
42654         function bindExportAssignment(node) {
42655             if (!container.symbol || !container.symbol.exports) {
42656                 // Export assignment in some sort of block construct
42657                 bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node));
42658             }
42659             else {
42660                 var flags = ts.exportAssignmentIsAlias(node)
42661                     // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
42662                     ? 2097152 /* Alias */
42663                     // An export default clause with any other expression exports a value
42664                     : 4 /* Property */;
42665                 // If there is an `export default x;` alias declaration, can't `export default` anything else.
42666                 // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
42667                 var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
42668                 if (node.isExportEquals) {
42669                     // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
42670                     ts.setValueDeclaration(symbol, node);
42671                 }
42672             }
42673         }
42674         function bindNamespaceExportDeclaration(node) {
42675             if (node.modifiers && node.modifiers.length) {
42676                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
42677             }
42678             var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level
42679                 : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files
42680                     : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files
42681                         : undefined;
42682             if (diag) {
42683                 file.bindDiagnostics.push(createDiagnosticForNode(node, diag));
42684             }
42685             else {
42686                 file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
42687                 declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
42688             }
42689         }
42690         function bindExportDeclaration(node) {
42691             if (!container.symbol || !container.symbol.exports) {
42692                 // Export * in some sort of block construct
42693                 bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
42694             }
42695             else if (!node.exportClause) {
42696                 // All export * declarations are collected in an __export symbol
42697                 declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
42698             }
42699             else if (ts.isNamespaceExport(node.exportClause)) {
42700                 // declareSymbol walks up parents to find name text, parent _must_ be set
42701                 // but won't be set by the normal binder walk until `bindChildren` later on.
42702                 ts.setParent(node.exportClause, node);
42703                 declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
42704             }
42705         }
42706         function bindImportClause(node) {
42707             if (node.name) {
42708                 declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
42709             }
42710         }
42711         function setCommonJsModuleIndicator(node) {
42712             if (file.externalModuleIndicator) {
42713                 return false;
42714             }
42715             if (!file.commonJsModuleIndicator) {
42716                 file.commonJsModuleIndicator = node;
42717                 bindSourceFileAsExternalModule();
42718             }
42719             return true;
42720         }
42721         function bindObjectDefinePropertyExport(node) {
42722             if (!setCommonJsModuleIndicator(node)) {
42723                 return;
42724             }
42725             var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) {
42726                 if (symbol) {
42727                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
42728                 }
42729                 return symbol;
42730             });
42731             if (symbol) {
42732                 var flags = 4 /* Property */ | 1048576 /* ExportValue */;
42733                 declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
42734             }
42735         }
42736         function bindExportsPropertyAssignment(node) {
42737             // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
42738             // expression is the declaration
42739             if (!setCommonJsModuleIndicator(node)) {
42740                 return;
42741             }
42742             var symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ undefined, function (id, symbol) {
42743                 if (symbol) {
42744                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
42745                 }
42746                 return symbol;
42747             });
42748             if (symbol) {
42749                 var isAlias = ts.isAliasableExpression(node.right) && (ts.isExportsIdentifier(node.left.expression) || ts.isModuleExportsAccessExpression(node.left.expression));
42750                 var flags = isAlias ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */;
42751                 ts.setParent(node.left, node);
42752                 declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
42753             }
42754         }
42755         function bindModuleExportsAssignment(node) {
42756             // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
42757             // is still pointing to 'module.exports'.
42758             // We do not want to consider this as 'export=' since a module can have only one of these.
42759             // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
42760             if (!setCommonJsModuleIndicator(node)) {
42761                 return;
42762             }
42763             var assignedExpression = ts.getRightMostAssignedExpression(node.right);
42764             if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
42765                 return;
42766             }
42767             if (ts.isObjectLiteralExpression(assignedExpression) && ts.every(assignedExpression.properties, ts.isShorthandPropertyAssignment)) {
42768                 ts.forEach(assignedExpression.properties, bindExportAssignedObjectMemberAlias);
42769                 return;
42770             }
42771             // 'module.exports = expr' assignment
42772             var flags = ts.exportAssignmentIsAlias(node)
42773                 ? 2097152 /* Alias */
42774                 : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
42775             var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
42776             ts.setValueDeclaration(symbol, node);
42777         }
42778         function bindExportAssignedObjectMemberAlias(node) {
42779             declareSymbol(file.symbol.exports, file.symbol, node, 2097152 /* Alias */ | 67108864 /* Assignment */, 0 /* None */);
42780         }
42781         function bindThisPropertyAssignment(node) {
42782             ts.Debug.assert(ts.isInJSFile(node));
42783             // private identifiers *must* be declared (even in JS files)
42784             var hasPrivateIdentifier = (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && ts.isPrivateIdentifier(node.left.name))
42785                 || (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name));
42786             if (hasPrivateIdentifier) {
42787                 return;
42788             }
42789             var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
42790             switch (thisContainer.kind) {
42791                 case 251 /* FunctionDeclaration */:
42792                 case 208 /* FunctionExpression */:
42793                     var constructorSymbol = thisContainer.symbol;
42794                     // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
42795                     if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) {
42796                         var l = thisContainer.parent.left;
42797                         if (ts.isBindableStaticAccessExpression(l) && ts.isPrototypeAccess(l.expression)) {
42798                             constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
42799                         }
42800                     }
42801                     if (constructorSymbol && constructorSymbol.valueDeclaration) {
42802                         // Declare a 'member' if the container is an ES5 class or ES6 constructor
42803                         constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
42804                         // It's acceptable for multiple 'this' assignments of the same identifier to occur
42805                         if (ts.hasDynamicName(node)) {
42806                             bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol);
42807                         }
42808                         else {
42809                             declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
42810                         }
42811                         addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
42812                     }
42813                     break;
42814                 case 166 /* Constructor */:
42815                 case 163 /* PropertyDeclaration */:
42816                 case 165 /* MethodDeclaration */:
42817                 case 167 /* GetAccessor */:
42818                 case 168 /* SetAccessor */:
42819                     // this.foo assignment in a JavaScript class
42820                     // Bind this property to the containing class
42821                     var containingClass = thisContainer.parent;
42822                     var symbolTable = ts.hasSyntacticModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
42823                     if (ts.hasDynamicName(node)) {
42824                         bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol);
42825                     }
42826                     else {
42827                         declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true);
42828                     }
42829                     break;
42830                 case 297 /* SourceFile */:
42831                     // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
42832                     if (ts.hasDynamicName(node)) {
42833                         break;
42834                     }
42835                     else if (thisContainer.commonJsModuleIndicator) {
42836                         declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
42837                     }
42838                     else {
42839                         declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
42840                     }
42841                     break;
42842                 default:
42843                     ts.Debug.failBadSyntaxKind(thisContainer);
42844             }
42845         }
42846         function bindDynamicallyNamedThisPropertyAssignment(node, symbol) {
42847             bindAnonymousDeclaration(node, 4 /* Property */, "__computed" /* Computed */);
42848             addLateBoundAssignmentDeclarationToSymbol(node, symbol);
42849         }
42850         function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
42851             if (symbol) {
42852                 (symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = new ts.Map())).set(ts.getNodeId(node), node);
42853             }
42854         }
42855         function bindSpecialPropertyDeclaration(node) {
42856             if (node.expression.kind === 107 /* ThisKeyword */) {
42857                 bindThisPropertyAssignment(node);
42858             }
42859             else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 297 /* SourceFile */) {
42860                 if (ts.isPrototypeAccess(node.expression)) {
42861                     bindPrototypePropertyAssignment(node, node.parent);
42862                 }
42863                 else {
42864                     bindStaticPropertyAssignment(node);
42865                 }
42866             }
42867         }
42868         /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
42869         function bindPrototypeAssignment(node) {
42870             ts.setParent(node.left, node);
42871             ts.setParent(node.right, node);
42872             bindPropertyAssignment(node.left.expression, node.left, /*isPrototypeProperty*/ false, /*containerIsClass*/ true);
42873         }
42874         function bindObjectDefinePrototypeProperty(node) {
42875             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
42876             if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
42877                 // Ensure the namespace symbol becomes class-like
42878                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
42879             }
42880             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
42881         }
42882         /**
42883          * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
42884          * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
42885          */
42886         function bindPrototypePropertyAssignment(lhs, parent) {
42887             // Look up the function in the local scope, since prototype assignments should
42888             // follow the function declaration
42889             var classPrototype = lhs.expression;
42890             var constructorFunction = classPrototype.expression;
42891             // Fix up parent pointers since we're going to use these nodes before we bind into them
42892             ts.setParent(constructorFunction, classPrototype);
42893             ts.setParent(classPrototype, lhs);
42894             ts.setParent(lhs, parent);
42895             bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true, /*containerIsClass*/ true);
42896         }
42897         function bindObjectDefinePropertyAssignment(node) {
42898             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
42899             var isToplevel = node.parent.parent.kind === 297 /* SourceFile */;
42900             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
42901             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
42902         }
42903         function bindSpecialPropertyAssignment(node) {
42904             var _a;
42905             // Class declarations in Typescript do not allow property declarations
42906             var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, container) || lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer);
42907             if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
42908                 return;
42909             }
42910             var rootExpr = ts.getLeftmostAccessExpression(node.left);
42911             if (ts.isIdentifier(rootExpr) && ((_a = lookupSymbolForName(container, rootExpr.escapedText)) === null || _a === void 0 ? void 0 : _a.flags) & 2097152 /* Alias */) {
42912                 return;
42913             }
42914             // Fix up parent pointers since we're going to use these nodes before we bind into them
42915             ts.setParent(node.left, node);
42916             ts.setParent(node.right, node);
42917             if (ts.isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
42918                 // This can be an alias for the 'exports' or 'module.exports' names, e.g.
42919                 //    var util = module.exports;
42920                 //    util.property = function ...
42921                 bindExportsPropertyAssignment(node);
42922             }
42923             else if (ts.hasDynamicName(node)) {
42924                 bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
42925                 var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false);
42926                 addLateBoundAssignmentDeclarationToSymbol(node, sym);
42927             }
42928             else {
42929                 bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticNameExpression));
42930             }
42931         }
42932         /**
42933          * 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.
42934          * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
42935          */
42936         function bindStaticPropertyAssignment(node) {
42937             ts.Debug.assert(!ts.isIdentifier(node));
42938             ts.setParent(node.expression, node);
42939             bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
42940         }
42941         function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
42942             if ((namespaceSymbol === null || namespaceSymbol === void 0 ? void 0 : namespaceSymbol.flags) & 2097152 /* Alias */) {
42943                 return namespaceSymbol;
42944             }
42945             if (isToplevel && !isPrototypeProperty) {
42946                 // make symbols or add declarations for intermediate containers
42947                 var flags_2 = 1536 /* Module */ | 67108864 /* Assignment */;
42948                 var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
42949                 namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) {
42950                     if (symbol) {
42951                         addDeclarationToSymbol(symbol, id, flags_2);
42952                         return symbol;
42953                     }
42954                     else {
42955                         var table = parent ? parent.exports :
42956                             file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
42957                         return declareSymbol(table, parent, id, flags_2, excludeFlags_1);
42958                     }
42959                 });
42960             }
42961             if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
42962                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
42963             }
42964             return namespaceSymbol;
42965         }
42966         function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
42967             if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
42968                 return;
42969             }
42970             // Set up the members collection if it doesn't exist already
42971             var symbolTable = isPrototypeProperty ?
42972                 (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
42973                 (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
42974             var includes = 0 /* None */;
42975             var excludes = 0 /* None */;
42976             // Method-like
42977             if (ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration))) {
42978                 includes = 8192 /* Method */;
42979                 excludes = 103359 /* MethodExcludes */;
42980             }
42981             // Maybe accessor-like
42982             else if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
42983                 if (ts.some(declaration.arguments[2].properties, function (p) {
42984                     var id = ts.getNameOfDeclaration(p);
42985                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "set";
42986                 })) {
42987                     // We mix in `SymbolFLags.Property` so in the checker `getTypeOfVariableParameterOrProperty` is used for this
42988                     // symbol, instead of `getTypeOfAccessor` (which will assert as there is no real accessor declaration)
42989                     includes |= 65536 /* SetAccessor */ | 4 /* Property */;
42990                     excludes |= 78783 /* SetAccessorExcludes */;
42991                 }
42992                 if (ts.some(declaration.arguments[2].properties, function (p) {
42993                     var id = ts.getNameOfDeclaration(p);
42994                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "get";
42995                 })) {
42996                     includes |= 32768 /* GetAccessor */ | 4 /* Property */;
42997                     excludes |= 46015 /* GetAccessorExcludes */;
42998                 }
42999             }
43000             if (includes === 0 /* None */) {
43001                 includes = 4 /* Property */;
43002                 excludes = 0 /* PropertyExcludes */;
43003             }
43004             declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
43005         }
43006         function isTopLevelNamespaceAssignment(propertyAccess) {
43007             return ts.isBinaryExpression(propertyAccess.parent)
43008                 ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 297 /* SourceFile */
43009                 : propertyAccess.parent.parent.kind === 297 /* SourceFile */;
43010         }
43011         function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
43012             var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer);
43013             var isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
43014             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
43015             bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
43016         }
43017         /**
43018          * Javascript expando values are:
43019          * - Functions
43020          * - classes
43021          * - namespaces
43022          * - variables initialized with function expressions
43023          * -                       with class expressions
43024          * -                       with empty object literals
43025          * -                       with non-empty object literals if assigned to the prototype property
43026          */
43027         function isExpandoSymbol(symbol) {
43028             if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
43029                 return true;
43030             }
43031             var node = symbol.valueDeclaration;
43032             if (node && ts.isCallExpression(node)) {
43033                 return !!ts.getAssignedExpandoInitializer(node);
43034             }
43035             var init = !node ? undefined :
43036                 ts.isVariableDeclaration(node) ? node.initializer :
43037                     ts.isBinaryExpression(node) ? node.right :
43038                         ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
43039                             undefined;
43040             init = init && ts.getRightMostAssignedExpression(init);
43041             if (init) {
43042                 var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
43043                 return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && (init.operatorToken.kind === 56 /* BarBarToken */ || init.operatorToken.kind === 60 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
43044             }
43045             return false;
43046         }
43047         function getParentOfBinaryExpression(expr) {
43048             while (ts.isBinaryExpression(expr.parent)) {
43049                 expr = expr.parent;
43050             }
43051             return expr.parent;
43052         }
43053         function lookupSymbolForPropertyAccess(node, lookupContainer) {
43054             if (lookupContainer === void 0) { lookupContainer = container; }
43055             if (ts.isIdentifier(node)) {
43056                 return lookupSymbolForName(lookupContainer, node.escapedText);
43057             }
43058             else {
43059                 var symbol = lookupSymbolForPropertyAccess(node.expression);
43060                 return symbol && symbol.exports && symbol.exports.get(ts.getElementOrPropertyAccessName(node));
43061             }
43062         }
43063         function forEachIdentifierInEntityName(e, parent, action) {
43064             if (isExportsOrModuleExportsOrAlias(file, e)) {
43065                 return file.symbol;
43066             }
43067             else if (ts.isIdentifier(e)) {
43068                 return action(e, lookupSymbolForPropertyAccess(e), parent);
43069             }
43070             else {
43071                 var s = forEachIdentifierInEntityName(e.expression, parent, action);
43072                 var name = ts.getNameOrArgument(e);
43073                 // unreachable
43074                 if (ts.isPrivateIdentifier(name)) {
43075                     ts.Debug.fail("unexpected PrivateIdentifier");
43076                 }
43077                 return action(name, s && s.exports && s.exports.get(ts.getElementOrPropertyAccessName(e)), s);
43078             }
43079         }
43080         function bindCallExpression(node) {
43081             // We're only inspecting call expressions to detect CommonJS modules, so we can skip
43082             // this check if we've already seen the module indicator
43083             if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
43084                 setCommonJsModuleIndicator(node);
43085             }
43086         }
43087         function bindClassLikeDeclaration(node) {
43088             if (node.kind === 252 /* ClassDeclaration */) {
43089                 bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
43090             }
43091             else {
43092                 var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
43093                 bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
43094                 // Add name of class expression into the map for semantic classifier
43095                 if (node.name) {
43096                     classifiableNames.add(node.name.escapedText);
43097                 }
43098             }
43099             var symbol = node.symbol;
43100             // TypeScript 1.0 spec (April 2014): 8.4
43101             // Every class automatically contains a static property member named 'prototype', the
43102             // type of which is an instantiation of the class type with type Any supplied as a type
43103             // argument for each type parameter. It is an error to explicitly declare a static
43104             // property member with the name 'prototype'.
43105             //
43106             // Note: we check for this here because this class may be merging into a module.  The
43107             // module might have an exported variable called 'prototype'.  We can't allow that as
43108             // that would clash with the built-in 'prototype' for the class.
43109             var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
43110             var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
43111             if (symbolExport) {
43112                 if (node.name) {
43113                     ts.setParent(node.name, node);
43114                 }
43115                 file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
43116             }
43117             symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
43118             prototypeSymbol.parent = symbol;
43119         }
43120         function bindEnumDeclaration(node) {
43121             return ts.isEnumConst(node)
43122                 ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
43123                 : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
43124         }
43125         function bindVariableDeclarationOrBindingElement(node) {
43126             if (inStrictMode) {
43127                 checkStrictModeEvalOrArguments(node, node.name);
43128             }
43129             if (!ts.isBindingPattern(node.name)) {
43130                 if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true) && !ts.getJSDocTypeTag(node)) {
43131                     declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
43132                 }
43133                 else if (ts.isBlockOrCatchScoped(node)) {
43134                     bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
43135                 }
43136                 else if (ts.isParameterDeclaration(node)) {
43137                     // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
43138                     // because its parent chain has already been set up, since parents are set before descending into children.
43139                     //
43140                     // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
43141                     // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
43142                     // For example:
43143                     //      function foo([a,a]) {} // Duplicate Identifier error
43144                     //      function bar(a,a) {}   // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
43145                     //                             // which correctly set excluded symbols
43146                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
43147                 }
43148                 else {
43149                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
43150                 }
43151             }
43152         }
43153         function bindParameter(node) {
43154             if (node.kind === 326 /* JSDocParameterTag */ && container.kind !== 313 /* JSDocSignature */) {
43155                 return;
43156             }
43157             if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) {
43158                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
43159                 // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
43160                 checkStrictModeEvalOrArguments(node, node.name);
43161             }
43162             if (ts.isBindingPattern(node.name)) {
43163                 bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
43164             }
43165             else {
43166                 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
43167             }
43168             // If this is a property-parameter, then also declare the property symbol into the
43169             // containing class.
43170             if (ts.isParameterPropertyDeclaration(node, node.parent)) {
43171                 var classDeclaration = node.parent.parent;
43172                 declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
43173             }
43174         }
43175         function bindFunctionDeclaration(node) {
43176             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
43177                 if (ts.isAsyncFunction(node)) {
43178                     emitFlags |= 2048 /* HasAsyncFunctions */;
43179                 }
43180             }
43181             checkStrictModeFunctionName(node);
43182             if (inStrictMode) {
43183                 checkStrictModeFunctionDeclaration(node);
43184                 bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
43185             }
43186             else {
43187                 declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
43188             }
43189         }
43190         function bindFunctionExpression(node) {
43191             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
43192                 if (ts.isAsyncFunction(node)) {
43193                     emitFlags |= 2048 /* HasAsyncFunctions */;
43194                 }
43195             }
43196             if (currentFlow) {
43197                 node.flowNode = currentFlow;
43198             }
43199             checkStrictModeFunctionName(node);
43200             var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
43201             return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
43202         }
43203         function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
43204             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */) && ts.isAsyncFunction(node)) {
43205                 emitFlags |= 2048 /* HasAsyncFunctions */;
43206             }
43207             if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) {
43208                 node.flowNode = currentFlow;
43209             }
43210             return ts.hasDynamicName(node)
43211                 ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
43212                 : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
43213         }
43214         function getInferTypeContainer(node) {
43215             var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
43216             return extendsType && extendsType.parent;
43217         }
43218         function bindTypeParameter(node) {
43219             if (ts.isJSDocTemplateTag(node.parent)) {
43220                 var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217
43221                 if (container_1) {
43222                     if (!container_1.locals) {
43223                         container_1.locals = ts.createSymbolTable();
43224                     }
43225                     declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
43226                 }
43227                 else {
43228                     declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
43229                 }
43230             }
43231             else if (node.parent.kind === 185 /* InferType */) {
43232                 var container_2 = getInferTypeContainer(node.parent);
43233                 if (container_2) {
43234                     if (!container_2.locals) {
43235                         container_2.locals = ts.createSymbolTable();
43236                     }
43237                     declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
43238                 }
43239                 else {
43240                     bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
43241                 }
43242             }
43243             else {
43244                 declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
43245             }
43246         }
43247         // reachability checks
43248         function shouldReportErrorOnModuleDeclaration(node) {
43249             var instanceState = getModuleInstanceState(node);
43250             return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && ts.shouldPreserveConstEnums(options));
43251         }
43252         function checkUnreachable(node) {
43253             if (!(currentFlow.flags & 1 /* Unreachable */)) {
43254                 return false;
43255             }
43256             if (currentFlow === unreachableFlow) {
43257                 var reportError = 
43258                 // report error on all statements except empty ones
43259                 (ts.isStatementButNotDeclaration(node) && node.kind !== 231 /* EmptyStatement */) ||
43260                     // report error on class declarations
43261                     node.kind === 252 /* ClassDeclaration */ ||
43262                     // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
43263                     (node.kind === 256 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
43264                 if (reportError) {
43265                     currentFlow = reportedUnreachableFlow;
43266                     if (!options.allowUnreachableCode) {
43267                         // unreachable code is reported if
43268                         // - user has explicitly asked about it AND
43269                         // - statement is in not ambient context (statements in ambient context is already an error
43270                         //   so we should not report extras) AND
43271                         //   - node is not variable statement OR
43272                         //   - node is block scoped variable statement OR
43273                         //   - node is not block scoped variable statement and at least one variable declaration has initializer
43274                         //   Rationale: we don't want to report errors on non-initialized var's since they are hoisted
43275                         //   On the other side we do want to report errors on non-initialized 'lets' because of TDZ
43276                         var isError_1 = ts.unreachableCodeIsError(options) &&
43277                             !(node.flags & 8388608 /* Ambient */) &&
43278                             (!ts.isVariableStatement(node) ||
43279                                 !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
43280                                 node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
43281                         eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
43282                     }
43283                 }
43284             }
43285             return true;
43286         }
43287     }
43288     function eachUnreachableRange(node, cb) {
43289         if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
43290             var statements = node.parent.statements;
43291             var slice_1 = ts.sliceAfter(statements, node);
43292             ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
43293         }
43294         else {
43295             cb(node, node);
43296         }
43297     }
43298     // As opposed to a pure declaration like an `interface`
43299     function isExecutableStatement(s) {
43300         // Don't remove statements that can validly be used before they appear.
43301         return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
43302             // `var x;` may declare a variable used above
43303             !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
43304     }
43305     function isPurelyTypeDeclaration(s) {
43306         switch (s.kind) {
43307             case 253 /* InterfaceDeclaration */:
43308             case 254 /* TypeAliasDeclaration */:
43309                 return true;
43310             case 256 /* ModuleDeclaration */:
43311                 return getModuleInstanceState(s) !== 1 /* Instantiated */;
43312             case 255 /* EnumDeclaration */:
43313                 return ts.hasSyntacticModifier(s, 2048 /* Const */);
43314             default:
43315                 return false;
43316         }
43317     }
43318     function isExportsOrModuleExportsOrAlias(sourceFile, node) {
43319         var i = 0;
43320         var q = [node];
43321         while (q.length && i < 100) {
43322             i++;
43323             node = q.shift();
43324             if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) {
43325                 return true;
43326             }
43327             else if (ts.isIdentifier(node)) {
43328                 var symbol = lookupSymbolForName(sourceFile, node.escapedText);
43329                 if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
43330                     var init = symbol.valueDeclaration.initializer;
43331                     q.push(init);
43332                     if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) {
43333                         q.push(init.left);
43334                         q.push(init.right);
43335                     }
43336                 }
43337             }
43338         }
43339         return false;
43340     }
43341     ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
43342     function lookupSymbolForName(container, name) {
43343         var local = container.locals && container.locals.get(name);
43344         if (local) {
43345             return local.exportSymbol || local;
43346         }
43347         if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
43348             return container.jsGlobalAugmentations.get(name);
43349         }
43350         return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
43351     }
43352 })(ts || (ts = {}));
43353 /** @internal */
43354 var ts;
43355 (function (ts) {
43356     function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments) {
43357         return getSymbolWalker;
43358         function getSymbolWalker(accept) {
43359             if (accept === void 0) { accept = function () { return true; }; }
43360             var visitedTypes = []; // Sparse array from id to type
43361             var visitedSymbols = []; // Sparse array from id to symbol
43362             return {
43363                 walkType: function (type) {
43364                     try {
43365                         visitType(type);
43366                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
43367                     }
43368                     finally {
43369                         ts.clear(visitedTypes);
43370                         ts.clear(visitedSymbols);
43371                     }
43372                 },
43373                 walkSymbol: function (symbol) {
43374                     try {
43375                         visitSymbol(symbol);
43376                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
43377                     }
43378                     finally {
43379                         ts.clear(visitedTypes);
43380                         ts.clear(visitedSymbols);
43381                     }
43382                 },
43383             };
43384             function visitType(type) {
43385                 if (!type) {
43386                     return;
43387                 }
43388                 if (visitedTypes[type.id]) {
43389                     return;
43390                 }
43391                 visitedTypes[type.id] = type;
43392                 // Reuse visitSymbol to visit the type's symbol,
43393                 //  but be sure to bail on recuring into the type if accept declines the symbol.
43394                 var shouldBail = visitSymbol(type.symbol);
43395                 if (shouldBail)
43396                     return;
43397                 // Visit the type's related types, if any
43398                 if (type.flags & 524288 /* Object */) {
43399                     var objectType = type;
43400                     var objectFlags = objectType.objectFlags;
43401                     if (objectFlags & 4 /* Reference */) {
43402                         visitTypeReference(type);
43403                     }
43404                     if (objectFlags & 32 /* Mapped */) {
43405                         visitMappedType(type);
43406                     }
43407                     if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
43408                         visitInterfaceType(type);
43409                     }
43410                     if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
43411                         visitObjectType(objectType);
43412                     }
43413                 }
43414                 if (type.flags & 262144 /* TypeParameter */) {
43415                     visitTypeParameter(type);
43416                 }
43417                 if (type.flags & 3145728 /* UnionOrIntersection */) {
43418                     visitUnionOrIntersectionType(type);
43419                 }
43420                 if (type.flags & 4194304 /* Index */) {
43421                     visitIndexType(type);
43422                 }
43423                 if (type.flags & 8388608 /* IndexedAccess */) {
43424                     visitIndexedAccessType(type);
43425                 }
43426             }
43427             function visitTypeReference(type) {
43428                 visitType(type.target);
43429                 ts.forEach(getTypeArguments(type), visitType);
43430             }
43431             function visitTypeParameter(type) {
43432                 visitType(getConstraintOfTypeParameter(type));
43433             }
43434             function visitUnionOrIntersectionType(type) {
43435                 ts.forEach(type.types, visitType);
43436             }
43437             function visitIndexType(type) {
43438                 visitType(type.type);
43439             }
43440             function visitIndexedAccessType(type) {
43441                 visitType(type.objectType);
43442                 visitType(type.indexType);
43443                 visitType(type.constraint);
43444             }
43445             function visitMappedType(type) {
43446                 visitType(type.typeParameter);
43447                 visitType(type.constraintType);
43448                 visitType(type.templateType);
43449                 visitType(type.modifiersType);
43450             }
43451             function visitSignature(signature) {
43452                 var typePredicate = getTypePredicateOfSignature(signature);
43453                 if (typePredicate) {
43454                     visitType(typePredicate.type);
43455                 }
43456                 ts.forEach(signature.typeParameters, visitType);
43457                 for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
43458                     var parameter = _a[_i];
43459                     visitSymbol(parameter);
43460                 }
43461                 visitType(getRestTypeOfSignature(signature));
43462                 visitType(getReturnTypeOfSignature(signature));
43463             }
43464             function visitInterfaceType(interfaceT) {
43465                 visitObjectType(interfaceT);
43466                 ts.forEach(interfaceT.typeParameters, visitType);
43467                 ts.forEach(getBaseTypes(interfaceT), visitType);
43468                 visitType(interfaceT.thisType);
43469             }
43470             function visitObjectType(type) {
43471                 var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */);
43472                 visitType(stringIndexType);
43473                 var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */);
43474                 visitType(numberIndexType);
43475                 // The two checks above *should* have already resolved the type (if needed), so this should be cached
43476                 var resolved = resolveStructuredTypeMembers(type);
43477                 for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) {
43478                     var signature = _a[_i];
43479                     visitSignature(signature);
43480                 }
43481                 for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) {
43482                     var signature = _c[_b];
43483                     visitSignature(signature);
43484                 }
43485                 for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) {
43486                     var p = _e[_d];
43487                     visitSymbol(p);
43488                 }
43489             }
43490             function visitSymbol(symbol) {
43491                 if (!symbol) {
43492                     return false;
43493                 }
43494                 var symbolId = ts.getSymbolId(symbol);
43495                 if (visitedSymbols[symbolId]) {
43496                     return false;
43497                 }
43498                 visitedSymbols[symbolId] = symbol;
43499                 if (!accept(symbol)) {
43500                     return true;
43501                 }
43502                 var t = getTypeOfSymbol(symbol);
43503                 visitType(t); // Should handle members on classes and such
43504                 if (symbol.exports) {
43505                     symbol.exports.forEach(visitSymbol);
43506                 }
43507                 ts.forEach(symbol.declarations, function (d) {
43508                     // Type queries are too far resolved when we just visit the symbol's type
43509                     //  (their type resolved directly to the member deeply referenced)
43510                     // So to get the intervening symbols, we need to check if there's a type
43511                     // query node on any of the symbol's declarations and get symbols there
43512                     if (d.type && d.type.kind === 176 /* TypeQuery */) {
43513                         var query = d.type;
43514                         var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
43515                         visitSymbol(entity);
43516                     }
43517                 });
43518                 return false;
43519             }
43520         }
43521     }
43522     ts.createGetSymbolWalker = createGetSymbolWalker;
43523 })(ts || (ts = {}));
43524 /* @internal */
43525 var ts;
43526 (function (ts) {
43527     var ambientModuleSymbolRegex = /^".+"$/;
43528     var anon = "(anonymous)";
43529     var nextSymbolId = 1;
43530     var nextNodeId = 1;
43531     var nextMergeId = 1;
43532     var nextFlowId = 1;
43533     var IterationUse;
43534     (function (IterationUse) {
43535         IterationUse[IterationUse["AllowsSyncIterablesFlag"] = 1] = "AllowsSyncIterablesFlag";
43536         IterationUse[IterationUse["AllowsAsyncIterablesFlag"] = 2] = "AllowsAsyncIterablesFlag";
43537         IterationUse[IterationUse["AllowsStringInputFlag"] = 4] = "AllowsStringInputFlag";
43538         IterationUse[IterationUse["ForOfFlag"] = 8] = "ForOfFlag";
43539         IterationUse[IterationUse["YieldStarFlag"] = 16] = "YieldStarFlag";
43540         IterationUse[IterationUse["SpreadFlag"] = 32] = "SpreadFlag";
43541         IterationUse[IterationUse["DestructuringFlag"] = 64] = "DestructuringFlag";
43542         IterationUse[IterationUse["PossiblyOutOfBounds"] = 128] = "PossiblyOutOfBounds";
43543         // Spread, Destructuring, Array element assignment
43544         IterationUse[IterationUse["Element"] = 1] = "Element";
43545         IterationUse[IterationUse["Spread"] = 33] = "Spread";
43546         IterationUse[IterationUse["Destructuring"] = 65] = "Destructuring";
43547         IterationUse[IterationUse["ForOf"] = 13] = "ForOf";
43548         IterationUse[IterationUse["ForAwaitOf"] = 15] = "ForAwaitOf";
43549         IterationUse[IterationUse["YieldStar"] = 17] = "YieldStar";
43550         IterationUse[IterationUse["AsyncYieldStar"] = 19] = "AsyncYieldStar";
43551         IterationUse[IterationUse["GeneratorReturnType"] = 1] = "GeneratorReturnType";
43552         IterationUse[IterationUse["AsyncGeneratorReturnType"] = 2] = "AsyncGeneratorReturnType";
43553     })(IterationUse || (IterationUse = {}));
43554     var IterationTypeKind;
43555     (function (IterationTypeKind) {
43556         IterationTypeKind[IterationTypeKind["Yield"] = 0] = "Yield";
43557         IterationTypeKind[IterationTypeKind["Return"] = 1] = "Return";
43558         IterationTypeKind[IterationTypeKind["Next"] = 2] = "Next";
43559     })(IterationTypeKind || (IterationTypeKind = {}));
43560     var WideningKind;
43561     (function (WideningKind) {
43562         WideningKind[WideningKind["Normal"] = 0] = "Normal";
43563         WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn";
43564         WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext";
43565         WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield";
43566     })(WideningKind || (WideningKind = {}));
43567     var TypeFacts;
43568     (function (TypeFacts) {
43569         TypeFacts[TypeFacts["None"] = 0] = "None";
43570         TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
43571         TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
43572         TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
43573         TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
43574         TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
43575         TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject";
43576         TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction";
43577         TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
43578         TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString";
43579         TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber";
43580         TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
43581         TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
43582         TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
43583         TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject";
43584         TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
43585         TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
43586         TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined";
43587         TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull";
43588         TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
43589         TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined";
43590         TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull";
43591         TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
43592         TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy";
43593         TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy";
43594         TypeFacts[TypeFacts["All"] = 16777215] = "All";
43595         // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
43596         // The presence of a particular fact means that the given test is true for some (and possibly all) values
43597         // of that kind of type.
43598         TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
43599         TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts";
43600         TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts";
43601         TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts";
43602         TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
43603         TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts";
43604         TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
43605         TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
43606         TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
43607         TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
43608         TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
43609         TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts";
43610         TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
43611         TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts";
43612         TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
43613         TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
43614         TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
43615         TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
43616         TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
43617         TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts";
43618         TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
43619         TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts";
43620         TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
43621         TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
43622         TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
43623         TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
43624         TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
43625         TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts";
43626         TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
43627         TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts";
43628         TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
43629         TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts";
43630         TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
43631         TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts";
43632         TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
43633         TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts";
43634         TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
43635         TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts";
43636         TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts";
43637         TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts";
43638         TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts";
43639         TypeFacts[TypeFacts["AllTypeofNE"] = 556800] = "AllTypeofNE";
43640         TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts";
43641     })(TypeFacts || (TypeFacts = {}));
43642     var typeofEQFacts = new ts.Map(ts.getEntries({
43643         string: 1 /* TypeofEQString */,
43644         number: 2 /* TypeofEQNumber */,
43645         bigint: 4 /* TypeofEQBigInt */,
43646         boolean: 8 /* TypeofEQBoolean */,
43647         symbol: 16 /* TypeofEQSymbol */,
43648         undefined: 65536 /* EQUndefined */,
43649         object: 32 /* TypeofEQObject */,
43650         function: 64 /* TypeofEQFunction */
43651     }));
43652     var typeofNEFacts = new ts.Map(ts.getEntries({
43653         string: 256 /* TypeofNEString */,
43654         number: 512 /* TypeofNENumber */,
43655         bigint: 1024 /* TypeofNEBigInt */,
43656         boolean: 2048 /* TypeofNEBoolean */,
43657         symbol: 4096 /* TypeofNESymbol */,
43658         undefined: 524288 /* NEUndefined */,
43659         object: 8192 /* TypeofNEObject */,
43660         function: 16384 /* TypeofNEFunction */
43661     }));
43662     var TypeSystemPropertyName;
43663     (function (TypeSystemPropertyName) {
43664         TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
43665         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
43666         TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
43667         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
43668         TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
43669         TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
43670         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 6] = "ResolvedTypeArguments";
43671         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseTypes"] = 7] = "ResolvedBaseTypes";
43672     })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
43673     var CheckMode;
43674     (function (CheckMode) {
43675         CheckMode[CheckMode["Normal"] = 0] = "Normal";
43676         CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
43677         CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
43678         CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
43679         CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
43680         CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
43681     })(CheckMode || (CheckMode = {}));
43682     var AccessFlags;
43683     (function (AccessFlags) {
43684         AccessFlags[AccessFlags["None"] = 0] = "None";
43685         AccessFlags[AccessFlags["NoIndexSignatures"] = 1] = "NoIndexSignatures";
43686         AccessFlags[AccessFlags["Writing"] = 2] = "Writing";
43687         AccessFlags[AccessFlags["CacheSymbol"] = 4] = "CacheSymbol";
43688         AccessFlags[AccessFlags["NoTupleBoundsCheck"] = 8] = "NoTupleBoundsCheck";
43689         AccessFlags[AccessFlags["ExpressionPosition"] = 16] = "ExpressionPosition";
43690     })(AccessFlags || (AccessFlags = {}));
43691     var SignatureCheckMode;
43692     (function (SignatureCheckMode) {
43693         SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback";
43694         SignatureCheckMode[SignatureCheckMode["StrictCallback"] = 2] = "StrictCallback";
43695         SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
43696         SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity";
43697         SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback";
43698     })(SignatureCheckMode || (SignatureCheckMode = {}));
43699     var IntersectionState;
43700     (function (IntersectionState) {
43701         IntersectionState[IntersectionState["None"] = 0] = "None";
43702         IntersectionState[IntersectionState["Source"] = 1] = "Source";
43703         IntersectionState[IntersectionState["Target"] = 2] = "Target";
43704         IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck";
43705         IntersectionState[IntersectionState["UnionIntersectionCheck"] = 8] = "UnionIntersectionCheck";
43706         IntersectionState[IntersectionState["InPropertyCheck"] = 16] = "InPropertyCheck";
43707     })(IntersectionState || (IntersectionState = {}));
43708     var MappedTypeModifiers;
43709     (function (MappedTypeModifiers) {
43710         MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
43711         MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
43712         MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
43713         MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
43714     })(MappedTypeModifiers || (MappedTypeModifiers = {}));
43715     var ExpandingFlags;
43716     (function (ExpandingFlags) {
43717         ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
43718         ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
43719         ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
43720         ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
43721     })(ExpandingFlags || (ExpandingFlags = {}));
43722     var MembersOrExportsResolutionKind;
43723     (function (MembersOrExportsResolutionKind) {
43724         MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
43725         MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
43726     })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
43727     var UnusedKind;
43728     (function (UnusedKind) {
43729         UnusedKind[UnusedKind["Local"] = 0] = "Local";
43730         UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
43731     })(UnusedKind || (UnusedKind = {}));
43732     var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
43733     var DeclarationMeaning;
43734     (function (DeclarationMeaning) {
43735         DeclarationMeaning[DeclarationMeaning["GetAccessor"] = 1] = "GetAccessor";
43736         DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor";
43737         DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment";
43738         DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method";
43739         DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor";
43740         DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod";
43741     })(DeclarationMeaning || (DeclarationMeaning = {}));
43742     var DeclarationSpaces;
43743     (function (DeclarationSpaces) {
43744         DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
43745         DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
43746         DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
43747         DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
43748     })(DeclarationSpaces || (DeclarationSpaces = {}));
43749     var MinArgumentCountFlags;
43750     (function (MinArgumentCountFlags) {
43751         MinArgumentCountFlags[MinArgumentCountFlags["None"] = 0] = "None";
43752         MinArgumentCountFlags[MinArgumentCountFlags["StrongArityForUntypedJS"] = 1] = "StrongArityForUntypedJS";
43753         MinArgumentCountFlags[MinArgumentCountFlags["VoidIsNonOptional"] = 2] = "VoidIsNonOptional";
43754     })(MinArgumentCountFlags || (MinArgumentCountFlags = {}));
43755     var IntrinsicTypeKind;
43756     (function (IntrinsicTypeKind) {
43757         IntrinsicTypeKind[IntrinsicTypeKind["Uppercase"] = 0] = "Uppercase";
43758         IntrinsicTypeKind[IntrinsicTypeKind["Lowercase"] = 1] = "Lowercase";
43759         IntrinsicTypeKind[IntrinsicTypeKind["Capitalize"] = 2] = "Capitalize";
43760         IntrinsicTypeKind[IntrinsicTypeKind["Uncapitalize"] = 3] = "Uncapitalize";
43761     })(IntrinsicTypeKind || (IntrinsicTypeKind = {}));
43762     var intrinsicTypeKinds = new ts.Map(ts.getEntries({
43763         Uppercase: 0 /* Uppercase */,
43764         Lowercase: 1 /* Lowercase */,
43765         Capitalize: 2 /* Capitalize */,
43766         Uncapitalize: 3 /* Uncapitalize */
43767     }));
43768     function SymbolLinks() {
43769     }
43770     function NodeLinks() {
43771         this.flags = 0;
43772     }
43773     function getNodeId(node) {
43774         if (!node.id) {
43775             node.id = nextNodeId;
43776             nextNodeId++;
43777         }
43778         return node.id;
43779     }
43780     ts.getNodeId = getNodeId;
43781     function getSymbolId(symbol) {
43782         if (!symbol.id) {
43783             symbol.id = nextSymbolId;
43784             nextSymbolId++;
43785         }
43786         return symbol.id;
43787     }
43788     ts.getSymbolId = getSymbolId;
43789     function isInstantiatedModule(node, preserveConstEnums) {
43790         var moduleState = ts.getModuleInstanceState(node);
43791         return moduleState === 1 /* Instantiated */ ||
43792             (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
43793     }
43794     ts.isInstantiatedModule = isInstantiatedModule;
43795     function createTypeChecker(host, produceDiagnostics) {
43796         var getPackagesSet = ts.memoize(function () {
43797             var set = new ts.Set();
43798             host.getSourceFiles().forEach(function (sf) {
43799                 if (!sf.resolvedModules)
43800                     return;
43801                 ts.forEachEntry(sf.resolvedModules, function (r) {
43802                     if (r && r.packageId)
43803                         set.add(r.packageId.name);
43804                 });
43805             });
43806             return set;
43807         });
43808         // Cancellation that controls whether or not we can cancel in the middle of type checking.
43809         // In general cancelling is *not* safe for the type checker.  We might be in the middle of
43810         // computing something, and we will leave our internals in an inconsistent state.  Callers
43811         // who set the cancellation token should catch if a cancellation exception occurs, and
43812         // should throw away and create a new TypeChecker.
43813         //
43814         // Currently we only support setting the cancellation token when getting diagnostics.  This
43815         // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
43816         // they no longer need the information (for example, if the user started editing again).
43817         var cancellationToken;
43818         var requestedExternalEmitHelpers;
43819         var externalHelpersModule;
43820         var Symbol = ts.objectAllocator.getSymbolConstructor();
43821         var Type = ts.objectAllocator.getTypeConstructor();
43822         var Signature = ts.objectAllocator.getSignatureConstructor();
43823         var typeCount = 0;
43824         var symbolCount = 0;
43825         var enumCount = 0;
43826         var totalInstantiationCount = 0;
43827         var instantiationCount = 0;
43828         var instantiationDepth = 0;
43829         var currentNode;
43830         var typeCatalog = []; // NB: id is index + 1
43831         var emptySymbols = ts.createSymbolTable();
43832         var arrayVariances = [1 /* Covariant */];
43833         var compilerOptions = host.getCompilerOptions();
43834         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
43835         var moduleKind = ts.getEmitModuleKind(compilerOptions);
43836         var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
43837         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
43838         var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
43839         var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply");
43840         var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
43841         var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
43842         var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
43843         var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
43844         var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
43845         var emitResolver = createResolver();
43846         var nodeBuilder = createNodeBuilder();
43847         var globals = ts.createSymbolTable();
43848         var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
43849         undefinedSymbol.declarations = [];
43850         var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
43851         globalThisSymbol.exports = globals;
43852         globalThisSymbol.declarations = [];
43853         globals.set(globalThisSymbol.escapedName, globalThisSymbol);
43854         var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
43855         var requireSymbol = createSymbol(4 /* Property */, "require");
43856         /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
43857         var apparentArgumentCount;
43858         // for public members that accept a Node or one of its subtypes, we must guard against
43859         // synthetic nodes created during transformations by calling `getParseTreeNode`.
43860         // for most of these, we perform the guard only on `checker` to avoid any possible
43861         // extra cost of calling `getParseTreeNode` when calling these functions from inside the
43862         // checker.
43863         var checker = {
43864             getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
43865             getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
43866             getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
43867             getTypeCatalog: function () { return typeCatalog; },
43868             getTypeCount: function () { return typeCount; },
43869             getInstantiationCount: function () { return totalInstantiationCount; },
43870             getRelationCacheSizes: function () { return ({
43871                 assignable: assignableRelation.size,
43872                 identity: identityRelation.size,
43873                 subtype: subtypeRelation.size,
43874                 strictSubtype: strictSubtypeRelation.size,
43875             }); },
43876             isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
43877             isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
43878             isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
43879             getMergedSymbol: getMergedSymbol,
43880             getDiagnostics: getDiagnostics,
43881             getGlobalDiagnostics: getGlobalDiagnostics,
43882             getRecursionIdentity: getRecursionIdentity,
43883             getTypeOfSymbolAtLocation: function (symbol, locationIn) {
43884                 var location = ts.getParseTreeNode(locationIn);
43885                 return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
43886             },
43887             getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
43888                 var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
43889                 if (parameter === undefined)
43890                     return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
43891                 return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
43892             },
43893             getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
43894             getPropertiesOfType: getPropertiesOfType,
43895             getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
43896             getPrivateIdentifierPropertyOfType: function (leftType, name, location) {
43897                 var node = ts.getParseTreeNode(location);
43898                 if (!node) {
43899                     return undefined;
43900                 }
43901                 var propName = ts.escapeLeadingUnderscores(name);
43902                 var lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
43903                 return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : undefined;
43904             },
43905             getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
43906             getIndexInfoOfType: getIndexInfoOfType,
43907             getSignaturesOfType: getSignaturesOfType,
43908             getIndexTypeOfType: getIndexTypeOfType,
43909             getBaseTypes: getBaseTypes,
43910             getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
43911             getWidenedType: getWidenedType,
43912             getTypeFromTypeNode: function (nodeIn) {
43913                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
43914                 return node ? getTypeFromTypeNode(node) : errorType;
43915             },
43916             getParameterType: getTypeAtPosition,
43917             getPromisedTypeOfPromise: getPromisedTypeOfPromise,
43918             getAwaitedType: function (type) { return getAwaitedType(type); },
43919             getReturnTypeOfSignature: getReturnTypeOfSignature,
43920             isNullableType: isNullableType,
43921             getNullableType: getNullableType,
43922             getNonNullableType: getNonNullableType,
43923             getNonOptionalType: removeOptionalTypeMarker,
43924             getTypeArguments: getTypeArguments,
43925             typeToTypeNode: nodeBuilder.typeToTypeNode,
43926             indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
43927             signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
43928             symbolToEntityName: nodeBuilder.symbolToEntityName,
43929             symbolToExpression: nodeBuilder.symbolToExpression,
43930             symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
43931             symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
43932             typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
43933             getSymbolsInScope: function (locationIn, meaning) {
43934                 var location = ts.getParseTreeNode(locationIn);
43935                 return location ? getSymbolsInScope(location, meaning) : [];
43936             },
43937             getSymbolAtLocation: function (nodeIn) {
43938                 var node = ts.getParseTreeNode(nodeIn);
43939                 // set ignoreErrors: true because any lookups invoked by the API shouldn't cause any new errors
43940                 return node ? getSymbolAtLocation(node, /*ignoreErrors*/ true) : undefined;
43941             },
43942             getShorthandAssignmentValueSymbol: function (nodeIn) {
43943                 var node = ts.getParseTreeNode(nodeIn);
43944                 return node ? getShorthandAssignmentValueSymbol(node) : undefined;
43945             },
43946             getExportSpecifierLocalTargetSymbol: function (nodeIn) {
43947                 var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
43948                 return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
43949             },
43950             getExportSymbolOfSymbol: function (symbol) {
43951                 return getMergedSymbol(symbol.exportSymbol || symbol);
43952             },
43953             getTypeAtLocation: function (nodeIn) {
43954                 var node = ts.getParseTreeNode(nodeIn);
43955                 return node ? getTypeOfNode(node) : errorType;
43956             },
43957             getTypeOfAssignmentPattern: function (nodeIn) {
43958                 var node = ts.getParseTreeNode(nodeIn, ts.isAssignmentPattern);
43959                 return node && getTypeOfAssignmentPattern(node) || errorType;
43960             },
43961             getPropertySymbolOfDestructuringAssignment: function (locationIn) {
43962                 var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
43963                 return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
43964             },
43965             signatureToString: function (signature, enclosingDeclaration, flags, kind) {
43966                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
43967             },
43968             typeToString: function (type, enclosingDeclaration, flags) {
43969                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
43970             },
43971             symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
43972                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
43973             },
43974             typePredicateToString: function (predicate, enclosingDeclaration, flags) {
43975                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
43976             },
43977             writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
43978                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
43979             },
43980             writeType: function (type, enclosingDeclaration, flags, writer) {
43981                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
43982             },
43983             writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
43984                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
43985             },
43986             writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
43987                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
43988             },
43989             getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
43990             getRootSymbols: getRootSymbols,
43991             getSymbolOfExpando: getSymbolOfExpando,
43992             getContextualType: function (nodeIn, contextFlags) {
43993                 var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
43994                 if (!node) {
43995                     return undefined;
43996                 }
43997                 var containingCall = ts.findAncestor(node, ts.isCallLikeExpression);
43998                 var containingCallResolvedSignature = containingCall && getNodeLinks(containingCall).resolvedSignature;
43999                 if (contextFlags & 4 /* Completions */ && containingCall) {
44000                     var toMarkSkip = node;
44001                     do {
44002                         getNodeLinks(toMarkSkip).skipDirectInference = true;
44003                         toMarkSkip = toMarkSkip.parent;
44004                     } while (toMarkSkip && toMarkSkip !== containingCall);
44005                     getNodeLinks(containingCall).resolvedSignature = undefined;
44006                 }
44007                 var result = getContextualType(node, contextFlags);
44008                 if (contextFlags & 4 /* Completions */ && containingCall) {
44009                     var toMarkSkip = node;
44010                     do {
44011                         getNodeLinks(toMarkSkip).skipDirectInference = undefined;
44012                         toMarkSkip = toMarkSkip.parent;
44013                     } while (toMarkSkip && toMarkSkip !== containingCall);
44014                     getNodeLinks(containingCall).resolvedSignature = containingCallResolvedSignature;
44015                 }
44016                 return result;
44017             },
44018             getContextualTypeForObjectLiteralElement: function (nodeIn) {
44019                 var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
44020                 return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
44021             },
44022             getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
44023                 var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
44024                 return node && getContextualTypeForArgumentAtIndex(node, argIndex);
44025             },
44026             getContextualTypeForJsxAttribute: function (nodeIn) {
44027                 var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
44028                 return node && getContextualTypeForJsxAttribute(node);
44029             },
44030             isContextSensitive: isContextSensitive,
44031             getFullyQualifiedName: getFullyQualifiedName,
44032             getResolvedSignature: function (node, candidatesOutArray, argumentCount) {
44033                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */);
44034             },
44035             getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, argumentCount) {
44036                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */);
44037             },
44038             getExpandedParameters: getExpandedParameters,
44039             hasEffectiveRestParameter: hasEffectiveRestParameter,
44040             getConstantValue: function (nodeIn) {
44041                 var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
44042                 return node ? getConstantValue(node) : undefined;
44043             },
44044             isValidPropertyAccess: function (nodeIn, propertyName) {
44045                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
44046                 return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
44047             },
44048             isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
44049                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
44050                 return !!node && isValidPropertyAccessForCompletions(node, type, property);
44051             },
44052             getSignatureFromDeclaration: function (declarationIn) {
44053                 var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
44054                 return declaration ? getSignatureFromDeclaration(declaration) : undefined;
44055             },
44056             isImplementationOfOverload: function (nodeIn) {
44057                 var node = ts.getParseTreeNode(nodeIn, ts.isFunctionLike);
44058                 return node ? isImplementationOfOverload(node) : undefined;
44059             },
44060             getImmediateAliasedSymbol: getImmediateAliasedSymbol,
44061             getAliasedSymbol: resolveAlias,
44062             getEmitResolver: getEmitResolver,
44063             getExportsOfModule: getExportsOfModuleAsArray,
44064             getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
44065             getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments),
44066             getAmbientModules: getAmbientModules,
44067             getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
44068             isOptionalParameter: function (nodeIn) {
44069                 var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
44070                 return node ? isOptionalParameter(node) : false;
44071             },
44072             tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
44073             tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
44074             tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
44075                 // we deliberately exclude augmentations
44076                 // since we are only interested in declarations of the module itself
44077                 return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
44078             },
44079             getApparentType: getApparentType,
44080             getUnionType: getUnionType,
44081             isTypeAssignableTo: isTypeAssignableTo,
44082             createAnonymousType: createAnonymousType,
44083             createSignature: createSignature,
44084             createSymbol: createSymbol,
44085             createIndexInfo: createIndexInfo,
44086             getAnyType: function () { return anyType; },
44087             getStringType: function () { return stringType; },
44088             getNumberType: function () { return numberType; },
44089             createPromiseType: createPromiseType,
44090             createArrayType: createArrayType,
44091             getElementTypeOfArrayType: getElementTypeOfArrayType,
44092             getBooleanType: function () { return booleanType; },
44093             getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
44094             getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
44095             getVoidType: function () { return voidType; },
44096             getUndefinedType: function () { return undefinedType; },
44097             getNullType: function () { return nullType; },
44098             getESSymbolType: function () { return esSymbolType; },
44099             getNeverType: function () { return neverType; },
44100             getOptionalType: function () { return optionalType; },
44101             isSymbolAccessible: isSymbolAccessible,
44102             isArrayType: isArrayType,
44103             isTupleType: isTupleType,
44104             isArrayLikeType: isArrayLikeType,
44105             isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
44106             getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
44107             getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty,
44108             getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty,
44109             getSuggestedSymbolForNonexistentJSXAttribute: getSuggestedSymbolForNonexistentJSXAttribute,
44110             getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
44111             getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
44112             getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule,
44113             getSuggestionForNonexistentExport: getSuggestionForNonexistentExport,
44114             getBaseConstraintOfType: getBaseConstraintOfType,
44115             getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
44116             resolveName: function (name, location, meaning, excludeGlobals) {
44117                 return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
44118             },
44119             getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
44120             getJsxFragmentFactory: function (n) {
44121                 var jsxFragmentFactory = getJsxFragmentFactoryEntity(n);
44122                 return jsxFragmentFactory && ts.unescapeLeadingUnderscores(ts.getFirstIdentifier(jsxFragmentFactory).escapedText);
44123             },
44124             getAccessibleSymbolChain: getAccessibleSymbolChain,
44125             getTypePredicateOfSignature: getTypePredicateOfSignature,
44126             resolveExternalModuleName: function (moduleSpecifierIn) {
44127                 var moduleSpecifier = ts.getParseTreeNode(moduleSpecifierIn, ts.isExpression);
44128                 return moduleSpecifier && resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true);
44129             },
44130             resolveExternalModuleSymbol: resolveExternalModuleSymbol,
44131             tryGetThisTypeAt: function (nodeIn, includeGlobalThis) {
44132                 var node = ts.getParseTreeNode(nodeIn);
44133                 return node && tryGetThisTypeAt(node, includeGlobalThis);
44134             },
44135             getTypeArgumentConstraint: function (nodeIn) {
44136                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
44137                 return node && getTypeArgumentConstraint(node);
44138             },
44139             getSuggestionDiagnostics: function (fileIn, ct) {
44140                 var file = ts.getParseTreeNode(fileIn, ts.isSourceFile) || ts.Debug.fail("Could not determine parsed source file.");
44141                 if (ts.skipTypeChecking(file, compilerOptions, host)) {
44142                     return ts.emptyArray;
44143                 }
44144                 var diagnostics;
44145                 try {
44146                     // Record the cancellation token so it can be checked later on during checkSourceElement.
44147                     // Do this in a finally block so we can ensure that it gets reset back to nothing after
44148                     // this call is done.
44149                     cancellationToken = ct;
44150                     // Ensure file is type checked
44151                     checkSourceFile(file);
44152                     ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
44153                     diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.getDiagnostics(file.fileName));
44154                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
44155                         if (!ts.containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
44156                             (diagnostics || (diagnostics = [])).push(__assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
44157                         }
44158                     });
44159                     return diagnostics || ts.emptyArray;
44160                 }
44161                 finally {
44162                     cancellationToken = undefined;
44163                 }
44164             },
44165             runWithCancellationToken: function (token, callback) {
44166                 try {
44167                     cancellationToken = token;
44168                     return callback(checker);
44169                 }
44170                 finally {
44171                     cancellationToken = undefined;
44172                 }
44173             },
44174             getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
44175             isDeclarationVisible: isDeclarationVisible,
44176         };
44177         function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
44178             var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
44179             apparentArgumentCount = argumentCount;
44180             var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
44181             apparentArgumentCount = undefined;
44182             return res;
44183         }
44184         var tupleTypes = new ts.Map();
44185         var unionTypes = new ts.Map();
44186         var intersectionTypes = new ts.Map();
44187         var literalTypes = new ts.Map();
44188         var indexedAccessTypes = new ts.Map();
44189         var templateLiteralTypes = new ts.Map();
44190         var stringMappingTypes = new ts.Map();
44191         var substitutionTypes = new ts.Map();
44192         var evolvingArrayTypes = [];
44193         var undefinedProperties = new ts.Map();
44194         var unknownSymbol = createSymbol(4 /* Property */, "unknown");
44195         var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
44196         var anyType = createIntrinsicType(1 /* Any */, "any");
44197         var autoType = createIntrinsicType(1 /* Any */, "any");
44198         var wildcardType = createIntrinsicType(1 /* Any */, "any");
44199         var errorType = createIntrinsicType(1 /* Any */, "error");
44200         var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */);
44201         var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic");
44202         var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
44203         var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
44204         var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */);
44205         var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined");
44206         var nullType = createIntrinsicType(65536 /* Null */, "null");
44207         var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */);
44208         var stringType = createIntrinsicType(4 /* String */, "string");
44209         var numberType = createIntrinsicType(8 /* Number */, "number");
44210         var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
44211         var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
44212         var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
44213         var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
44214         var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
44215         trueType.regularType = regularTrueType;
44216         trueType.freshType = trueType;
44217         regularTrueType.regularType = regularTrueType;
44218         regularTrueType.freshType = trueType;
44219         falseType.regularType = regularFalseType;
44220         falseType.freshType = falseType;
44221         regularFalseType.regularType = regularFalseType;
44222         regularFalseType.freshType = falseType;
44223         var booleanType = createBooleanType([regularFalseType, regularTrueType]);
44224         // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false`
44225         // (The union is cached, so simply doing the marking here is sufficient)
44226         createBooleanType([regularFalseType, trueType]);
44227         createBooleanType([falseType, regularTrueType]);
44228         createBooleanType([falseType, trueType]);
44229         var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
44230         var voidType = createIntrinsicType(16384 /* Void */, "void");
44231         var neverType = createIntrinsicType(131072 /* Never */, "never");
44232         var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
44233         var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */);
44234         var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
44235         var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never");
44236         var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
44237         var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
44238         var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
44239         var numberOrBigIntType = getUnionType([numberType, bigintType]);
44240         var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]);
44241         var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t; });
44242         var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; });
44243         var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
44244         var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
44245         emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */;
44246         var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
44247         emptyTypeLiteralSymbol.members = ts.createSymbolTable();
44248         var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
44249         var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
44250         emptyGenericType.instantiations = new ts.Map();
44251         var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
44252         // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
44253         // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
44254         anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */;
44255         var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
44256         var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
44257         var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
44258         var markerSuperType = createTypeParameter();
44259         var markerSubType = createTypeParameter();
44260         markerSubType.constraint = markerSuperType;
44261         var markerOtherType = createTypeParameter();
44262         var noTypePredicate = createTypePredicate(1 /* Identifier */, "<<unresolved>>", 0, anyType);
44263         var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
44264         var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
44265         var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
44266         var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
44267         var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
44268         var iterationTypesCache = new ts.Map(); // cache for common IterationTypes instances
44269         var noIterationTypes = {
44270             get yieldType() { return ts.Debug.fail("Not supported"); },
44271             get returnType() { return ts.Debug.fail("Not supported"); },
44272             get nextType() { return ts.Debug.fail("Not supported"); },
44273         };
44274         var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
44275         var anyIterationTypesExceptNext = createIterationTypes(anyType, anyType, unknownType);
44276         var defaultIterationTypes = createIterationTypes(neverType, anyType, undefinedType); // default iteration types for `Iterator`.
44277         var asyncIterationTypesResolver = {
44278             iterableCacheKey: "iterationTypesOfAsyncIterable",
44279             iteratorCacheKey: "iterationTypesOfAsyncIterator",
44280             iteratorSymbolName: "asyncIterator",
44281             getGlobalIteratorType: getGlobalAsyncIteratorType,
44282             getGlobalIterableType: getGlobalAsyncIterableType,
44283             getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
44284             getGlobalGeneratorType: getGlobalAsyncGeneratorType,
44285             resolveIterationType: getAwaitedType,
44286             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_async_iterator_must_have_a_next_method,
44287             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
44288             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,
44289         };
44290         var syncIterationTypesResolver = {
44291             iterableCacheKey: "iterationTypesOfIterable",
44292             iteratorCacheKey: "iterationTypesOfIterator",
44293             iteratorSymbolName: "iterator",
44294             getGlobalIteratorType: getGlobalIteratorType,
44295             getGlobalIterableType: getGlobalIterableType,
44296             getGlobalIterableIteratorType: getGlobalIterableIteratorType,
44297             getGlobalGeneratorType: getGlobalGeneratorType,
44298             resolveIterationType: function (type, _errorNode) { return type; },
44299             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_iterator_must_have_a_next_method,
44300             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
44301             mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property,
44302         };
44303         /** Key is "/path/to/a.ts|/path/to/b.ts". */
44304         var amalgamatedDuplicates;
44305         var reverseMappedCache = new ts.Map();
44306         var inInferTypeForHomomorphicMappedType = false;
44307         var ambientModulesCache;
44308         /**
44309          * List of every ambient module with a "*" wildcard.
44310          * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
44311          * This is only used if there is no exact match.
44312          */
44313         var patternAmbientModules;
44314         var patternAmbientModuleAugmentations;
44315         var globalObjectType;
44316         var globalFunctionType;
44317         var globalCallableFunctionType;
44318         var globalNewableFunctionType;
44319         var globalArrayType;
44320         var globalReadonlyArrayType;
44321         var globalStringType;
44322         var globalNumberType;
44323         var globalBooleanType;
44324         var globalRegExpType;
44325         var globalThisType;
44326         var anyArrayType;
44327         var autoArrayType;
44328         var anyReadonlyArrayType;
44329         var deferredGlobalNonNullableTypeAlias;
44330         // The library files are only loaded when the feature is used.
44331         // This allows users to just specify library files they want to used through --lib
44332         // and they will not get an error from not having unrelated library files
44333         var deferredGlobalESSymbolConstructorSymbol;
44334         var deferredGlobalESSymbolType;
44335         var deferredGlobalTypedPropertyDescriptorType;
44336         var deferredGlobalPromiseType;
44337         var deferredGlobalPromiseLikeType;
44338         var deferredGlobalPromiseConstructorSymbol;
44339         var deferredGlobalPromiseConstructorLikeType;
44340         var deferredGlobalIterableType;
44341         var deferredGlobalIteratorType;
44342         var deferredGlobalIterableIteratorType;
44343         var deferredGlobalGeneratorType;
44344         var deferredGlobalIteratorYieldResultType;
44345         var deferredGlobalIteratorReturnResultType;
44346         var deferredGlobalAsyncIterableType;
44347         var deferredGlobalAsyncIteratorType;
44348         var deferredGlobalAsyncIterableIteratorType;
44349         var deferredGlobalAsyncGeneratorType;
44350         var deferredGlobalTemplateStringsArrayType;
44351         var deferredGlobalImportMetaType;
44352         var deferredGlobalExtractSymbol;
44353         var deferredGlobalOmitSymbol;
44354         var deferredGlobalBigIntType;
44355         var allPotentiallyUnusedIdentifiers = new ts.Map(); // key is file name
44356         var flowLoopStart = 0;
44357         var flowLoopCount = 0;
44358         var sharedFlowCount = 0;
44359         var flowAnalysisDisabled = false;
44360         var flowInvocationCount = 0;
44361         var lastFlowNode;
44362         var lastFlowNodeReachable;
44363         var flowTypeCache;
44364         var emptyStringType = getLiteralType("");
44365         var zeroType = getLiteralType(0);
44366         var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" });
44367         var resolutionTargets = [];
44368         var resolutionResults = [];
44369         var resolutionPropertyNames = [];
44370         var suggestionCount = 0;
44371         var maximumSuggestionCount = 10;
44372         var mergedSymbols = [];
44373         var symbolLinks = [];
44374         var nodeLinks = [];
44375         var flowLoopCaches = [];
44376         var flowLoopNodes = [];
44377         var flowLoopKeys = [];
44378         var flowLoopTypes = [];
44379         var sharedFlowNodes = [];
44380         var sharedFlowTypes = [];
44381         var flowNodeReachable = [];
44382         var flowNodePostSuper = [];
44383         var potentialThisCollisions = [];
44384         var potentialNewTargetCollisions = [];
44385         var potentialWeakMapCollisions = [];
44386         var awaitedTypeStack = [];
44387         var diagnostics = ts.createDiagnosticCollection();
44388         var suggestionDiagnostics = ts.createDiagnosticCollection();
44389         var typeofTypesByName = new ts.Map(ts.getEntries({
44390             string: stringType,
44391             number: numberType,
44392             bigint: bigintType,
44393             boolean: booleanType,
44394             symbol: esSymbolType,
44395             undefined: undefinedType
44396         }));
44397         var typeofType = createTypeofType();
44398         var _jsxNamespace;
44399         var _jsxFactoryEntity;
44400         var outofbandVarianceMarkerHandler;
44401         var subtypeRelation = new ts.Map();
44402         var strictSubtypeRelation = new ts.Map();
44403         var assignableRelation = new ts.Map();
44404         var comparableRelation = new ts.Map();
44405         var identityRelation = new ts.Map();
44406         var enumRelation = new ts.Map();
44407         var builtinGlobals = ts.createSymbolTable();
44408         builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
44409         initializeTypeChecker();
44410         return checker;
44411         function getJsxNamespace(location) {
44412             if (location) {
44413                 var file = ts.getSourceFileOfNode(location);
44414                 if (file) {
44415                     if (ts.isJsxOpeningFragment(location)) {
44416                         if (file.localJsxFragmentNamespace) {
44417                             return file.localJsxFragmentNamespace;
44418                         }
44419                         var jsxFragmentPragma = file.pragmas.get("jsxfrag");
44420                         if (jsxFragmentPragma) {
44421                             var chosenPragma = ts.isArray(jsxFragmentPragma) ? jsxFragmentPragma[0] : jsxFragmentPragma;
44422                             file.localJsxFragmentFactory = ts.parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
44423                             ts.visitNode(file.localJsxFragmentFactory, markAsSynthetic);
44424                             if (file.localJsxFragmentFactory) {
44425                                 return file.localJsxFragmentNamespace = ts.getFirstIdentifier(file.localJsxFragmentFactory).escapedText;
44426                             }
44427                         }
44428                         var entity = getJsxFragmentFactoryEntity(location);
44429                         if (entity) {
44430                             file.localJsxFragmentFactory = entity;
44431                             return file.localJsxFragmentNamespace = ts.getFirstIdentifier(entity).escapedText;
44432                         }
44433                     }
44434                     else {
44435                         if (file.localJsxNamespace) {
44436                             return file.localJsxNamespace;
44437                         }
44438                         var jsxPragma = file.pragmas.get("jsx");
44439                         if (jsxPragma) {
44440                             var chosenPragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
44441                             file.localJsxFactory = ts.parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
44442                             ts.visitNode(file.localJsxFactory, markAsSynthetic);
44443                             if (file.localJsxFactory) {
44444                                 return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText;
44445                             }
44446                         }
44447                     }
44448                 }
44449             }
44450             if (!_jsxNamespace) {
44451                 _jsxNamespace = "React";
44452                 if (compilerOptions.jsxFactory) {
44453                     _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
44454                     ts.visitNode(_jsxFactoryEntity, markAsSynthetic);
44455                     if (_jsxFactoryEntity) {
44456                         _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText;
44457                     }
44458                 }
44459                 else if (compilerOptions.reactNamespace) {
44460                     _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
44461                 }
44462             }
44463             if (!_jsxFactoryEntity) {
44464                 _jsxFactoryEntity = ts.factory.createQualifiedName(ts.factory.createIdentifier(ts.unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
44465             }
44466             return _jsxNamespace;
44467             function markAsSynthetic(node) {
44468                 ts.setTextRangePosEnd(node, -1, -1);
44469                 return ts.visitEachChild(node, markAsSynthetic, ts.nullTransformationContext);
44470             }
44471         }
44472         function getEmitResolver(sourceFile, cancellationToken) {
44473             // Ensure we have all the type information in place for this file so that all the
44474             // emitter questions of this resolver will return the right information.
44475             getDiagnostics(sourceFile, cancellationToken);
44476             return emitResolver;
44477         }
44478         function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
44479             var diagnostic = location
44480                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
44481                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
44482             var existing = diagnostics.lookup(diagnostic);
44483             if (existing) {
44484                 return existing;
44485             }
44486             else {
44487                 diagnostics.add(diagnostic);
44488                 return diagnostic;
44489             }
44490         }
44491         function errorSkippedOn(key, location, message, arg0, arg1, arg2, arg3) {
44492             var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
44493             diagnostic.skippedOn = key;
44494             return diagnostic;
44495         }
44496         function error(location, message, arg0, arg1, arg2, arg3) {
44497             var diagnostic = location
44498                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
44499                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
44500             diagnostics.add(diagnostic);
44501             return diagnostic;
44502         }
44503         function addErrorOrSuggestion(isError, diagnostic) {
44504             if (isError) {
44505                 diagnostics.add(diagnostic);
44506             }
44507             else {
44508                 suggestionDiagnostics.add(__assign(__assign({}, diagnostic), { category: ts.DiagnosticCategory.Suggestion }));
44509             }
44510         }
44511         function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
44512             // Pseudo-synthesized input node
44513             if (location.pos < 0 || location.end < 0) {
44514                 if (!isError) {
44515                     return; // Drop suggestions (we have no span to suggest on)
44516                 }
44517                 // Issue errors globally
44518                 var file = ts.getSourceFileOfNode(location);
44519                 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
44520                 return;
44521             }
44522             addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line no-in-operator
44523         }
44524         function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) {
44525             var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
44526             if (maybeMissingAwait) {
44527                 var related = ts.createDiagnosticForNode(location, ts.Diagnostics.Did_you_forget_to_use_await);
44528                 ts.addRelatedInfo(diagnostic, related);
44529             }
44530             return diagnostic;
44531         }
44532         function addDeprecatedSuggestionWorker(declarations, diagnostic) {
44533             var deprecatedTag = Array.isArray(declarations) ? ts.forEach(declarations, ts.getJSDocDeprecatedTag) : ts.getJSDocDeprecatedTag(declarations);
44534             if (deprecatedTag) {
44535                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(deprecatedTag, ts.Diagnostics.The_declaration_was_marked_as_deprecated_here));
44536             }
44537             // We call `addRelatedInfo()` before adding the diagnostic to prevent duplicates.
44538             suggestionDiagnostics.add(diagnostic);
44539             return diagnostic;
44540         }
44541         function addDeprecatedSuggestion(location, declarations, deprecatedEntity) {
44542             var diagnostic = ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, deprecatedEntity);
44543             return addDeprecatedSuggestionWorker(declarations, diagnostic);
44544         }
44545         function addDeprecatedSuggestionWithSignature(location, declaration, deprecatedEntity, signatureString) {
44546             var diagnostic = deprecatedEntity
44547                 ? ts.createDiagnosticForNode(location, ts.Diagnostics.The_signature_0_of_1_is_deprecated, signatureString, deprecatedEntity)
44548                 : ts.createDiagnosticForNode(location, ts.Diagnostics._0_is_deprecated, signatureString);
44549             return addDeprecatedSuggestionWorker(declaration, diagnostic);
44550         }
44551         function createSymbol(flags, name, checkFlags) {
44552             symbolCount++;
44553             var symbol = (new Symbol(flags | 33554432 /* Transient */, name));
44554             symbol.checkFlags = checkFlags || 0;
44555             return symbol;
44556         }
44557         function getExcludedSymbolFlags(flags) {
44558             var result = 0;
44559             if (flags & 2 /* BlockScopedVariable */)
44560                 result |= 111551 /* BlockScopedVariableExcludes */;
44561             if (flags & 1 /* FunctionScopedVariable */)
44562                 result |= 111550 /* FunctionScopedVariableExcludes */;
44563             if (flags & 4 /* Property */)
44564                 result |= 0 /* PropertyExcludes */;
44565             if (flags & 8 /* EnumMember */)
44566                 result |= 900095 /* EnumMemberExcludes */;
44567             if (flags & 16 /* Function */)
44568                 result |= 110991 /* FunctionExcludes */;
44569             if (flags & 32 /* Class */)
44570                 result |= 899503 /* ClassExcludes */;
44571             if (flags & 64 /* Interface */)
44572                 result |= 788872 /* InterfaceExcludes */;
44573             if (flags & 256 /* RegularEnum */)
44574                 result |= 899327 /* RegularEnumExcludes */;
44575             if (flags & 128 /* ConstEnum */)
44576                 result |= 899967 /* ConstEnumExcludes */;
44577             if (flags & 512 /* ValueModule */)
44578                 result |= 110735 /* ValueModuleExcludes */;
44579             if (flags & 8192 /* Method */)
44580                 result |= 103359 /* MethodExcludes */;
44581             if (flags & 32768 /* GetAccessor */)
44582                 result |= 46015 /* GetAccessorExcludes */;
44583             if (flags & 65536 /* SetAccessor */)
44584                 result |= 78783 /* SetAccessorExcludes */;
44585             if (flags & 262144 /* TypeParameter */)
44586                 result |= 526824 /* TypeParameterExcludes */;
44587             if (flags & 524288 /* TypeAlias */)
44588                 result |= 788968 /* TypeAliasExcludes */;
44589             if (flags & 2097152 /* Alias */)
44590                 result |= 2097152 /* AliasExcludes */;
44591             return result;
44592         }
44593         function recordMergedSymbol(target, source) {
44594             if (!source.mergeId) {
44595                 source.mergeId = nextMergeId;
44596                 nextMergeId++;
44597             }
44598             mergedSymbols[source.mergeId] = target;
44599         }
44600         function cloneSymbol(symbol) {
44601             var result = createSymbol(symbol.flags, symbol.escapedName);
44602             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
44603             result.parent = symbol.parent;
44604             if (symbol.valueDeclaration)
44605                 result.valueDeclaration = symbol.valueDeclaration;
44606             if (symbol.constEnumOnlyModule)
44607                 result.constEnumOnlyModule = true;
44608             if (symbol.members)
44609                 result.members = new ts.Map(symbol.members);
44610             if (symbol.exports)
44611                 result.exports = new ts.Map(symbol.exports);
44612             recordMergedSymbol(result, symbol);
44613             return result;
44614         }
44615         /**
44616          * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
44617          * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
44618          */
44619         function mergeSymbol(target, source, unidirectional) {
44620             if (unidirectional === void 0) { unidirectional = false; }
44621             if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
44622                 (source.flags | target.flags) & 67108864 /* Assignment */) {
44623                 if (source === target) {
44624                     // This can happen when an export assigned namespace exports something also erroneously exported at the top level
44625                     // See `declarationFileNoCrashOnExtraExportModifier` for an example
44626                     return target;
44627                 }
44628                 if (!(target.flags & 33554432 /* Transient */)) {
44629                     var resolvedTarget = resolveSymbol(target);
44630                     if (resolvedTarget === unknownSymbol) {
44631                         return source;
44632                     }
44633                     target = cloneSymbol(resolvedTarget);
44634                 }
44635                 // Javascript static-property-assignment declarations always merge, even though they are also values
44636                 if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
44637                     // reset flag when merging instantiated module into value module that has only const enums
44638                     target.constEnumOnlyModule = false;
44639                 }
44640                 target.flags |= source.flags;
44641                 if (source.valueDeclaration) {
44642                     ts.setValueDeclaration(target, source.valueDeclaration);
44643                 }
44644                 ts.addRange(target.declarations, source.declarations);
44645                 if (source.members) {
44646                     if (!target.members)
44647                         target.members = ts.createSymbolTable();
44648                     mergeSymbolTable(target.members, source.members, unidirectional);
44649                 }
44650                 if (source.exports) {
44651                     if (!target.exports)
44652                         target.exports = ts.createSymbolTable();
44653                     mergeSymbolTable(target.exports, source.exports, unidirectional);
44654                 }
44655                 if (!unidirectional) {
44656                     recordMergedSymbol(target, source);
44657                 }
44658             }
44659             else if (target.flags & 1024 /* NamespaceModule */) {
44660                 // Do not report an error when merging `var globalThis` with the built-in `globalThis`,
44661                 // as we will already report a "Declaration name conflicts..." error, and this error
44662                 // won't make much sense.
44663                 if (target !== globalThisSymbol) {
44664                     error(ts.getNameOfDeclaration(source.declarations[0]), ts.Diagnostics.Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity, symbolToString(target));
44665                 }
44666             }
44667             else { // error
44668                 var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
44669                 var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
44670                 var message = isEitherEnum
44671                     ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
44672                     : isEitherBlockScoped_1
44673                         ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
44674                         : ts.Diagnostics.Duplicate_identifier_0;
44675                 var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
44676                 var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
44677                 var symbolName_1 = symbolToString(source);
44678                 // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
44679                 if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
44680                     var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
44681                     var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
44682                     var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () {
44683                         return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: new ts.Map() });
44684                     });
44685                     var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () {
44686                         return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] });
44687                     });
44688                     addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source);
44689                     addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target);
44690                 }
44691                 else {
44692                     addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target);
44693                     addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source);
44694                 }
44695             }
44696             return target;
44697             function addDuplicateLocations(locs, symbol) {
44698                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
44699                     var decl = _a[_i];
44700                     ts.pushIfUnique(locs, decl);
44701                 }
44702             }
44703         }
44704         function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
44705             ts.forEach(target.declarations, function (node) {
44706                 addDuplicateDeclarationError(node, message, symbolName, source.declarations);
44707             });
44708         }
44709         function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) {
44710             var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
44711             var err = lookupOrIssueError(errorNode, message, symbolName);
44712             var _loop_7 = function (relatedNode) {
44713                 var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode;
44714                 if (adjustedNode === errorNode)
44715                     return "continue";
44716                 err.relatedInformation = err.relatedInformation || [];
44717                 var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName);
44718                 var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here);
44719                 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 */; }))
44720                     return "continue";
44721                 ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage);
44722             };
44723             for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) {
44724                 var relatedNode = _a[_i];
44725                 _loop_7(relatedNode);
44726             }
44727         }
44728         function combineSymbolTables(first, second) {
44729             if (!(first === null || first === void 0 ? void 0 : first.size))
44730                 return second;
44731             if (!(second === null || second === void 0 ? void 0 : second.size))
44732                 return first;
44733             var combined = ts.createSymbolTable();
44734             mergeSymbolTable(combined, first);
44735             mergeSymbolTable(combined, second);
44736             return combined;
44737         }
44738         function mergeSymbolTable(target, source, unidirectional) {
44739             if (unidirectional === void 0) { unidirectional = false; }
44740             source.forEach(function (sourceSymbol, id) {
44741                 var targetSymbol = target.get(id);
44742                 target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol);
44743             });
44744         }
44745         function mergeModuleAugmentation(moduleName) {
44746             var _a, _b;
44747             var moduleAugmentation = moduleName.parent;
44748             if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) {
44749                 // this is a combined symbol for multiple augmentations within the same file.
44750                 // its symbol already has accumulated information for all declarations
44751                 // so we need to add it just once - do the work only for first declaration
44752                 ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
44753                 return;
44754             }
44755             if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
44756                 mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
44757             }
44758             else {
44759                 // find a module that about to be augmented
44760                 // do not validate names of augmentations that are defined in ambient context
44761                 var moduleNotFoundError = !(moduleName.parent.parent.flags & 8388608 /* Ambient */)
44762                     ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
44763                     : undefined;
44764                 var mainModule_1 = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
44765                 if (!mainModule_1) {
44766                     return;
44767                 }
44768                 // obtain item referenced by 'export='
44769                 mainModule_1 = resolveExternalModuleSymbol(mainModule_1);
44770                 if (mainModule_1.flags & 1920 /* Namespace */) {
44771                     // If we're merging an augmentation to a pattern ambient module, we want to
44772                     // perform the merge unidirectionally from the augmentation ('a.foo') to
44773                     // the pattern ('*.foo'), so that 'getMergedSymbol()' on a.foo gives you
44774                     // all the exports both from the pattern and from the augmentation, but
44775                     // 'getMergedSymbol()' on *.foo only gives you exports from *.foo.
44776                     if (ts.some(patternAmbientModules, function (module) { return mainModule_1 === module.symbol; })) {
44777                         var merged = mergeSymbol(moduleAugmentation.symbol, mainModule_1, /*unidirectional*/ true);
44778                         if (!patternAmbientModuleAugmentations) {
44779                             patternAmbientModuleAugmentations = new ts.Map();
44780                         }
44781                         // moduleName will be a StringLiteral since this is not `declare global`.
44782                         patternAmbientModuleAugmentations.set(moduleName.text, merged);
44783                     }
44784                     else {
44785                         if (((_a = mainModule_1.exports) === null || _a === void 0 ? void 0 : _a.get("__export" /* ExportStar */)) && ((_b = moduleAugmentation.symbol.exports) === null || _b === void 0 ? void 0 : _b.size)) {
44786                             // We may need to merge the module augmentation's exports into the target symbols of the resolved exports
44787                             var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */);
44788                             for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) {
44789                                 var _d = _c[_i], key = _d[0], value = _d[1];
44790                                 if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) {
44791                                     mergeSymbol(resolvedExports.get(key), value);
44792                                 }
44793                             }
44794                         }
44795                         mergeSymbol(mainModule_1, moduleAugmentation.symbol);
44796                     }
44797                 }
44798                 else {
44799                     // moduleName will be a StringLiteral since this is not `declare global`.
44800                     error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
44801                 }
44802             }
44803         }
44804         function addToSymbolTable(target, source, message) {
44805             source.forEach(function (sourceSymbol, id) {
44806                 var targetSymbol = target.get(id);
44807                 if (targetSymbol) {
44808                     // Error on redeclarations
44809                     ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
44810                 }
44811                 else {
44812                     target.set(id, sourceSymbol);
44813                 }
44814             });
44815             function addDeclarationDiagnostic(id, message) {
44816                 return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
44817             }
44818         }
44819         function getSymbolLinks(symbol) {
44820             if (symbol.flags & 33554432 /* Transient */)
44821                 return symbol;
44822             var id = getSymbolId(symbol);
44823             return symbolLinks[id] || (symbolLinks[id] = new SymbolLinks());
44824         }
44825         function getNodeLinks(node) {
44826             var nodeId = getNodeId(node);
44827             return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
44828         }
44829         function isGlobalSourceFile(node) {
44830             return node.kind === 297 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
44831         }
44832         function getSymbol(symbols, name, meaning) {
44833             if (meaning) {
44834                 var symbol = getMergedSymbol(symbols.get(name));
44835                 if (symbol) {
44836                     ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
44837                     if (symbol.flags & meaning) {
44838                         return symbol;
44839                     }
44840                     if (symbol.flags & 2097152 /* Alias */) {
44841                         var target = resolveAlias(symbol);
44842                         // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
44843                         if (target === unknownSymbol || target.flags & meaning) {
44844                             return symbol;
44845                         }
44846                     }
44847                 }
44848             }
44849             // return undefined if we can't find a symbol.
44850         }
44851         /**
44852          * Get symbols that represent parameter-property-declaration as parameter and as property declaration
44853          * @param parameter a parameterDeclaration node
44854          * @param parameterName a name of the parameter to get the symbols for.
44855          * @return a tuple of two symbols
44856          */
44857         function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
44858             var constructorDeclaration = parameter.parent;
44859             var classDeclaration = parameter.parent.parent;
44860             var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
44861             var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
44862             if (parameterSymbol && propertySymbol) {
44863                 return [parameterSymbol, propertySymbol];
44864             }
44865             return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
44866         }
44867         function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
44868             var declarationFile = ts.getSourceFileOfNode(declaration);
44869             var useFile = ts.getSourceFileOfNode(usage);
44870             var declContainer = ts.getEnclosingBlockScopeContainer(declaration);
44871             if (declarationFile !== useFile) {
44872                 if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
44873                     (!ts.outFile(compilerOptions)) ||
44874                     isInTypeQuery(usage) ||
44875                     declaration.flags & 8388608 /* Ambient */) {
44876                     // nodes are in different files and order cannot be determined
44877                     return true;
44878                 }
44879                 // declaration is after usage
44880                 // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
44881                 if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
44882                     return true;
44883                 }
44884                 var sourceFiles = host.getSourceFiles();
44885                 return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
44886             }
44887             if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) {
44888                 // declaration is before usage
44889                 if (declaration.kind === 198 /* BindingElement */) {
44890                     // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
44891                     var errorBindingElement = ts.getAncestor(usage, 198 /* BindingElement */);
44892                     if (errorBindingElement) {
44893                         return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
44894                             declaration.pos < errorBindingElement.pos;
44895                     }
44896                     // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
44897                     return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 249 /* VariableDeclaration */), usage);
44898                 }
44899                 else if (declaration.kind === 249 /* VariableDeclaration */) {
44900                     // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
44901                     return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
44902                 }
44903                 else if (ts.isClassDeclaration(declaration)) {
44904                     // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
44905                     return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
44906                 }
44907                 else if (ts.isPropertyDeclaration(declaration)) {
44908                     // still might be illegal if a self-referencing property initializer (eg private x = this.x)
44909                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false);
44910                 }
44911                 else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) {
44912                     // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property
44913                     return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
44914                         && ts.getContainingClass(declaration) === ts.getContainingClass(usage)
44915                         && isUsedInFunctionOrInstanceProperty(usage, declaration));
44916                 }
44917                 return true;
44918             }
44919             // declaration is after usage, but it can still be legal if usage is deferred:
44920             // 1. inside an export specifier
44921             // 2. inside a function
44922             // 3. inside an instance property initializer, a reference to a non-instance property
44923             //    (except when target: "esnext" and useDefineForClassFields: true and the reference is to a parameter property)
44924             // 4. inside a static property initializer, a reference to a static method in the same class
44925             // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
44926             // or if usage is in a type context:
44927             // 1. inside a type query (typeof in type position)
44928             // 2. inside a jsdoc comment
44929             if (usage.parent.kind === 270 /* ExportSpecifier */ || (usage.parent.kind === 266 /* ExportAssignment */ && usage.parent.isExportEquals)) {
44930                 // export specifiers do not use the variable, they only make it available for use
44931                 return true;
44932             }
44933             // When resolving symbols for exports, the `usage` location passed in can be the export site directly
44934             if (usage.kind === 266 /* ExportAssignment */ && usage.isExportEquals) {
44935                 return true;
44936             }
44937             if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) {
44938                 return true;
44939             }
44940             if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
44941                 if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
44942                     && ts.getContainingClass(declaration)
44943                     && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) {
44944                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true);
44945                 }
44946                 else {
44947                     return true;
44948                 }
44949             }
44950             return false;
44951             function usageInTypeDeclaration() {
44952                 return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); });
44953             }
44954             function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
44955                 switch (declaration.parent.parent.kind) {
44956                     case 232 /* VariableStatement */:
44957                     case 237 /* ForStatement */:
44958                     case 239 /* ForOfStatement */:
44959                         // variable statement/for/for-of statement case,
44960                         // use site should not be inside variable declaration (initializer of declaration or binding element)
44961                         if (isSameScopeDescendentOf(usage, declaration, declContainer)) {
44962                             return true;
44963                         }
44964                         break;
44965                 }
44966                 // ForIn/ForOf case - use site should not be used in expression part
44967                 var grandparent = declaration.parent.parent;
44968                 return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer);
44969             }
44970             function isUsedInFunctionOrInstanceProperty(usage, declaration) {
44971                 return !!ts.findAncestor(usage, function (current) {
44972                     if (current === declContainer) {
44973                         return "quit";
44974                     }
44975                     if (ts.isFunctionLike(current)) {
44976                         return true;
44977                     }
44978                     var initializerOfProperty = current.parent &&
44979                         current.parent.kind === 163 /* PropertyDeclaration */ &&
44980                         current.parent.initializer === current;
44981                     if (initializerOfProperty) {
44982                         if (ts.hasSyntacticModifier(current.parent, 32 /* Static */)) {
44983                             if (declaration.kind === 165 /* MethodDeclaration */) {
44984                                 return true;
44985                             }
44986                         }
44987                         else {
44988                             var isDeclarationInstanceProperty = declaration.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(declaration, 32 /* Static */);
44989                             if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
44990                                 return true;
44991                             }
44992                         }
44993                     }
44994                     return false;
44995                 });
44996             }
44997             /** stopAtAnyPropertyDeclaration is used for detecting ES-standard class field use-before-def errors */
44998             function isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, stopAtAnyPropertyDeclaration) {
44999                 // always legal if usage is after declaration
45000                 if (usage.end > declaration.end) {
45001                     return false;
45002                 }
45003                 // still might be legal if usage is deferred (e.g. x: any = () => this.x)
45004                 // otherwise illegal if immediately referenced within the declaration (e.g. x: any = this.x)
45005                 var ancestorChangingReferenceScope = ts.findAncestor(usage, function (node) {
45006                     if (node === declaration) {
45007                         return "quit";
45008                     }
45009                     switch (node.kind) {
45010                         case 209 /* ArrowFunction */:
45011                             return true;
45012                         case 163 /* PropertyDeclaration */:
45013                             // even when stopping at any property declaration, they need to come from the same class
45014                             return stopAtAnyPropertyDeclaration &&
45015                                 (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent
45016                                     || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent)
45017                                 ? "quit" : true;
45018                         case 230 /* Block */:
45019                             switch (node.parent.kind) {
45020                                 case 167 /* GetAccessor */:
45021                                 case 165 /* MethodDeclaration */:
45022                                 case 168 /* SetAccessor */:
45023                                     return true;
45024                                 default:
45025                                     return false;
45026                             }
45027                         default:
45028                             return false;
45029                     }
45030                 });
45031                 return ancestorChangingReferenceScope === undefined;
45032             }
45033         }
45034         function useOuterVariableScopeInParameter(result, location, lastLocation) {
45035             var target = ts.getEmitScriptTarget(compilerOptions);
45036             var functionLocation = location;
45037             if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) {
45038                 // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body
45039                 // - static field in a class expression
45040                 // - optional chaining pre-es2020
45041                 // - nullish coalesce pre-es2020
45042                 // - spread assignment in binding pattern pre-es2017
45043                 if (target >= 2 /* ES2015 */) {
45044                     var links = getNodeLinks(functionLocation);
45045                     if (links.declarationRequiresScopeChange === undefined) {
45046                         links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false;
45047                     }
45048                     return !links.declarationRequiresScopeChange;
45049                 }
45050             }
45051             return false;
45052             function requiresScopeChange(node) {
45053                 return requiresScopeChangeWorker(node.name)
45054                     || !!node.initializer && requiresScopeChangeWorker(node.initializer);
45055             }
45056             function requiresScopeChangeWorker(node) {
45057                 switch (node.kind) {
45058                     case 209 /* ArrowFunction */:
45059                     case 208 /* FunctionExpression */:
45060                     case 251 /* FunctionDeclaration */:
45061                     case 166 /* Constructor */:
45062                         // do not descend into these
45063                         return false;
45064                     case 165 /* MethodDeclaration */:
45065                     case 167 /* GetAccessor */:
45066                     case 168 /* SetAccessor */:
45067                     case 288 /* PropertyAssignment */:
45068                         return requiresScopeChangeWorker(node.name);
45069                     case 163 /* PropertyDeclaration */:
45070                         // static properties in classes introduce temporary variables
45071                         if (ts.hasStaticModifier(node)) {
45072                             return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields;
45073                         }
45074                         return requiresScopeChangeWorker(node.name);
45075                     default:
45076                         // null coalesce and optional chain pre-es2020 produce temporary variables
45077                         if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) {
45078                             return target < 7 /* ES2020 */;
45079                         }
45080                         if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) {
45081                             return target < 4 /* ES2017 */;
45082                         }
45083                         if (ts.isTypeNode(node))
45084                             return false;
45085                         return ts.forEachChild(node, requiresScopeChangeWorker) || false;
45086                 }
45087             }
45088         }
45089         /**
45090          * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
45091          * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
45092          * the given name can be found.
45093          *
45094          * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
45095          */
45096         function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) {
45097             if (excludeGlobals === void 0) { excludeGlobals = false; }
45098             return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage);
45099         }
45100         function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) {
45101             var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
45102             var result;
45103             var lastLocation;
45104             var lastSelfReferenceLocation;
45105             var propertyWithInvalidInitializer;
45106             var associatedDeclarationForContainingInitializerOrBindingName;
45107             var withinDeferredContext = false;
45108             var errorLocation = location;
45109             var grandparent;
45110             var isInExternalModule = false;
45111             loop: while (location) {
45112                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
45113                 if (location.locals && !isGlobalSourceFile(location)) {
45114                     if (result = lookup(location.locals, name, meaning)) {
45115                         var useResult = true;
45116                         if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
45117                             // symbol lookup restrictions for function-like declarations
45118                             // - Type parameters of a function are in scope in the entire function declaration, including the parameter
45119                             //   list and return type. However, local types are only in scope in the function body.
45120                             // - parameters are only in the scope of function body
45121                             // This restriction does not apply to JSDoc comment types because they are parented
45122                             // at a higher level than type parameters would normally be
45123                             if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 311 /* JSDocComment */) {
45124                                 useResult = result.flags & 262144 /* TypeParameter */
45125                                     // type parameters are visible in parameter list, return type and type parameter list
45126                                     ? lastLocation === location.type ||
45127                                         lastLocation.kind === 160 /* Parameter */ ||
45128                                         lastLocation.kind === 159 /* TypeParameter */
45129                                     // local types not visible outside the function body
45130                                     : false;
45131                             }
45132                             if (meaning & result.flags & 3 /* Variable */) {
45133                                 // expression inside parameter will lookup as normal variable scope when targeting es2015+
45134                                 if (useOuterVariableScopeInParameter(result, location, lastLocation)) {
45135                                     useResult = false;
45136                                 }
45137                                 else if (result.flags & 1 /* FunctionScopedVariable */) {
45138                                     // parameters are visible only inside function body, parameter list and return type
45139                                     // technically for parameter list case here we might mix parameters and variables declared in function,
45140                                     // however it is detected separately when checking initializers of parameters
45141                                     // to make sure that they reference no variables declared after them.
45142                                     useResult =
45143                                         lastLocation.kind === 160 /* Parameter */ ||
45144                                             (lastLocation === location.type &&
45145                                                 !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
45146                                 }
45147                             }
45148                         }
45149                         else if (location.kind === 184 /* ConditionalType */) {
45150                             // A type parameter declared using 'infer T' in a conditional type is visible only in
45151                             // the true branch of the conditional type.
45152                             useResult = lastLocation === location.trueType;
45153                         }
45154                         if (useResult) {
45155                             break loop;
45156                         }
45157                         else {
45158                             result = undefined;
45159                         }
45160                     }
45161                 }
45162                 withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
45163                 switch (location.kind) {
45164                     case 297 /* SourceFile */:
45165                         if (!ts.isExternalOrCommonJsModule(location))
45166                             break;
45167                         isInExternalModule = true;
45168                     // falls through
45169                     case 256 /* ModuleDeclaration */:
45170                         var moduleExports = getSymbolOfNode(location).exports || emptySymbols;
45171                         if (location.kind === 297 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) {
45172                             // It's an external module. First see if the module has an export default and if the local
45173                             // name of that export default matches.
45174                             if (result = moduleExports.get("default" /* Default */)) {
45175                                 var localSymbol = ts.getLocalSymbolForExportDefault(result);
45176                                 if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
45177                                     break loop;
45178                                 }
45179                                 result = undefined;
45180                             }
45181                             // Because of module/namespace merging, a module's exports are in scope,
45182                             // yet we never want to treat an export specifier as putting a member in scope.
45183                             // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
45184                             // Two things to note about this:
45185                             //     1. We have to check this without calling getSymbol. The problem with calling getSymbol
45186                             //        on an export specifier is that it might find the export specifier itself, and try to
45187                             //        resolve it as an alias. This will cause the checker to consider the export specifier
45188                             //        a circular alias reference when it might not be.
45189                             //     2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
45190                             //        an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
45191                             //        which is not the desired behavior.
45192                             var moduleExport = moduleExports.get(name);
45193                             if (moduleExport &&
45194                                 moduleExport.flags === 2097152 /* Alias */ &&
45195                                 (ts.getDeclarationOfKind(moduleExport, 270 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 269 /* NamespaceExport */))) {
45196                                 break;
45197                             }
45198                         }
45199                         // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
45200                         if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
45201                             if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) {
45202                                 result = undefined;
45203                             }
45204                             else {
45205                                 break loop;
45206                             }
45207                         }
45208                         break;
45209                     case 255 /* EnumDeclaration */:
45210                         if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
45211                             break loop;
45212                         }
45213                         break;
45214                     case 163 /* PropertyDeclaration */:
45215                         // TypeScript 1.0 spec (April 2014): 8.4.1
45216                         // Initializer expressions for instance member variables are evaluated in the scope
45217                         // of the class constructor body but are not permitted to reference parameters or
45218                         // local variables of the constructor. This effectively means that entities from outer scopes
45219                         // by the same name as a constructor parameter or local variable are inaccessible
45220                         // in initializer expressions for instance member variables.
45221                         if (!ts.hasSyntacticModifier(location, 32 /* Static */)) {
45222                             var ctor = findConstructorDeclaration(location.parent);
45223                             if (ctor && ctor.locals) {
45224                                 if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) {
45225                                     // Remember the property node, it will be used later to report appropriate error
45226                                     propertyWithInvalidInitializer = location;
45227                                 }
45228                             }
45229                         }
45230                         break;
45231                     case 252 /* ClassDeclaration */:
45232                     case 221 /* ClassExpression */:
45233                     case 253 /* InterfaceDeclaration */:
45234                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
45235                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
45236                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
45237                         if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 788968 /* Type */)) {
45238                             if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
45239                                 // ignore type parameters not declared in this container
45240                                 result = undefined;
45241                                 break;
45242                             }
45243                             if (lastLocation && ts.hasSyntacticModifier(lastLocation, 32 /* Static */)) {
45244                                 // TypeScript 1.0 spec (April 2014): 3.4.1
45245                                 // The scope of a type parameter extends over the entire declaration with which the type
45246                                 // parameter list is associated, with the exception of static member declarations in classes.
45247                                 error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
45248                                 return undefined;
45249                             }
45250                             break loop;
45251                         }
45252                         if (location.kind === 221 /* ClassExpression */ && meaning & 32 /* Class */) {
45253                             var className = location.name;
45254                             if (className && name === className.escapedText) {
45255                                 result = location.symbol;
45256                                 break loop;
45257                             }
45258                         }
45259                         break;
45260                     case 223 /* ExpressionWithTypeArguments */:
45261                         // The type parameters of a class are not in scope in the base class expression.
45262                         if (lastLocation === location.expression && location.parent.token === 93 /* ExtendsKeyword */) {
45263                             var container = location.parent.parent;
45264                             if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 788968 /* Type */))) {
45265                                 if (nameNotFoundMessage) {
45266                                     error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
45267                                 }
45268                                 return undefined;
45269                             }
45270                         }
45271                         break;
45272                     // It is not legal to reference a class's own type parameters from a computed property name that
45273                     // belongs to the class. For example:
45274                     //
45275                     //   function foo<T>() { return '' }
45276                     //   class C<T> { // <-- Class's own type parameter T
45277                     //       [foo<T>()]() { } // <-- Reference to T from class's own computed property
45278                     //   }
45279                     //
45280                     case 158 /* ComputedPropertyName */:
45281                         grandparent = location.parent.parent;
45282                         if (ts.isClassLike(grandparent) || grandparent.kind === 253 /* InterfaceDeclaration */) {
45283                             // A reference to this grandparent's type parameters would be an error
45284                             if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) {
45285                                 error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
45286                                 return undefined;
45287                             }
45288                         }
45289                         break;
45290                     case 209 /* ArrowFunction */:
45291                         // when targeting ES6 or higher there is no 'arguments' in an arrow function
45292                         // for lower compile targets the resolved symbol is used to emit an error
45293                         if (compilerOptions.target >= 2 /* ES2015 */) {
45294                             break;
45295                         }
45296                     // falls through
45297                     case 165 /* MethodDeclaration */:
45298                     case 166 /* Constructor */:
45299                     case 167 /* GetAccessor */:
45300                     case 168 /* SetAccessor */:
45301                     case 251 /* FunctionDeclaration */:
45302                         if (meaning & 3 /* Variable */ && name === "arguments") {
45303                             result = argumentsSymbol;
45304                             break loop;
45305                         }
45306                         break;
45307                     case 208 /* FunctionExpression */:
45308                         if (meaning & 3 /* Variable */ && name === "arguments") {
45309                             result = argumentsSymbol;
45310                             break loop;
45311                         }
45312                         if (meaning & 16 /* Function */) {
45313                             var functionName = location.name;
45314                             if (functionName && name === functionName.escapedText) {
45315                                 result = location.symbol;
45316                                 break loop;
45317                             }
45318                         }
45319                         break;
45320                     case 161 /* Decorator */:
45321                         // Decorators are resolved at the class declaration. Resolving at the parameter
45322                         // or member would result in looking up locals in the method.
45323                         //
45324                         //   function y() {}
45325                         //   class C {
45326                         //       method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
45327                         //   }
45328                         //
45329                         if (location.parent && location.parent.kind === 160 /* Parameter */) {
45330                             location = location.parent;
45331                         }
45332                         //
45333                         //   function y() {}
45334                         //   class C {
45335                         //       @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
45336                         //   }
45337                         //
45338                         // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
45339                         //
45340                         //   type T = number;
45341                         //   declare function y(x: T): any;
45342                         //   @param(1 as T) // <-- T should resolve to the type alias outside of class C
45343                         //   class C<T> {}
45344                         if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 252 /* ClassDeclaration */)) {
45345                             location = location.parent;
45346                         }
45347                         break;
45348                     case 331 /* JSDocTypedefTag */:
45349                     case 324 /* JSDocCallbackTag */:
45350                     case 325 /* JSDocEnumTag */:
45351                         // js type aliases do not resolve names from their host, so skip past it
45352                         var root = ts.getJSDocRoot(location);
45353                         if (root) {
45354                             location = root.parent;
45355                         }
45356                         break;
45357                     case 160 /* Parameter */:
45358                         if (lastLocation && (lastLocation === location.initializer ||
45359                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
45360                             if (!associatedDeclarationForContainingInitializerOrBindingName) {
45361                                 associatedDeclarationForContainingInitializerOrBindingName = location;
45362                             }
45363                         }
45364                         break;
45365                     case 198 /* BindingElement */:
45366                         if (lastLocation && (lastLocation === location.initializer ||
45367                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
45368                             if (ts.isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) {
45369                                 associatedDeclarationForContainingInitializerOrBindingName = location;
45370                             }
45371                         }
45372                         break;
45373                     case 185 /* InferType */:
45374                         if (meaning & 262144 /* TypeParameter */) {
45375                             var parameterName = location.typeParameter.name;
45376                             if (parameterName && name === parameterName.escapedText) {
45377                                 result = location.typeParameter.symbol;
45378                                 break loop;
45379                             }
45380                         }
45381                         break;
45382                 }
45383                 if (isSelfReferenceLocation(location)) {
45384                     lastSelfReferenceLocation = location;
45385                 }
45386                 lastLocation = location;
45387                 location = location.parent;
45388             }
45389             // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
45390             // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
45391             // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
45392             if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
45393                 result.isReferenced |= meaning;
45394             }
45395             if (!result) {
45396                 if (lastLocation) {
45397                     ts.Debug.assert(lastLocation.kind === 297 /* SourceFile */);
45398                     if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
45399                         return lastLocation.symbol;
45400                     }
45401                 }
45402                 if (!excludeGlobals) {
45403                     result = lookup(globals, name, meaning);
45404                 }
45405             }
45406             if (!result) {
45407                 if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
45408                     if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
45409                         return requireSymbol;
45410                     }
45411                 }
45412             }
45413             if (!result) {
45414                 if (nameNotFoundMessage) {
45415                     if (!errorLocation ||
45416                         !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
45417                             !checkAndReportErrorForExtendingInterface(errorLocation) &&
45418                             !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
45419                             !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) &&
45420                             !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
45421                             !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
45422                             !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
45423                         var suggestion = void 0;
45424                         if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
45425                             suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
45426                             var isGlobalScopeAugmentationDeclaration = suggestion && suggestion.valueDeclaration && ts.isAmbientModule(suggestion.valueDeclaration) && ts.isGlobalScopeAugmentation(suggestion.valueDeclaration);
45427                             if (isGlobalScopeAugmentationDeclaration) {
45428                                 suggestion = undefined;
45429                             }
45430                             if (suggestion) {
45431                                 var suggestionName = symbolToString(suggestion);
45432                                 var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
45433                                 if (suggestion.valueDeclaration) {
45434                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
45435                                 }
45436                             }
45437                         }
45438                         if (!suggestion) {
45439                             if (nameArg) {
45440                                 var lib = getSuggestedLibForNonExistentName(nameArg);
45441                                 if (lib) {
45442                                     error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), lib);
45443                                 }
45444                                 else {
45445                                     error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
45446                                 }
45447                             }
45448                         }
45449                         suggestionCount++;
45450                     }
45451                 }
45452                 return undefined;
45453             }
45454             // Perform extra checks only if error reporting was requested
45455             if (nameNotFoundMessage) {
45456                 if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
45457                     // We have a match, but the reference occurred within a property initializer and the identifier also binds
45458                     // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed
45459                     // with ESNext+useDefineForClassFields because the scope semantics are different.
45460                     var propertyName = propertyWithInvalidInitializer.name;
45461                     error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
45462                     return undefined;
45463                 }
45464                 // Only check for block-scoped variable if we have an error location and are looking for the
45465                 // name with variable meaning
45466                 //      For example,
45467                 //          declare module foo {
45468                 //              interface bar {}
45469                 //          }
45470                 //      const foo/*1*/: foo/*2*/.bar;
45471                 // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
45472                 // block-scoped variable and namespace module. However, only when we
45473                 // try to resolve name in /*1*/ which is used in variable position,
45474                 // we want to check for block-scoped
45475                 if (errorLocation &&
45476                     (meaning & 2 /* BlockScopedVariable */ ||
45477                         ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */))) {
45478                     var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
45479                     if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
45480                         checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
45481                     }
45482                 }
45483                 // If we're in an external module, we can't reference value symbols created from UMD export declarations
45484                 if (result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(originalLocation.flags & 4194304 /* JSDoc */)) {
45485                     var merged = getMergedSymbol(result);
45486                     if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) {
45487                         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));
45488                     }
45489                 }
45490                 // 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
45491                 if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
45492                     var candidate = getMergedSymbol(getLateBoundSymbol(result));
45493                     var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
45494                     // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself
45495                     if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) {
45496                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
45497                     }
45498                     // And it cannot refer to any declarations which come after it
45499                     else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) {
45500                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation));
45501                     }
45502                 }
45503                 if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) {
45504                     checkSymbolUsageInExpressionContext(result, name, errorLocation);
45505                 }
45506             }
45507             return result;
45508         }
45509         function checkSymbolUsageInExpressionContext(symbol, name, useSite) {
45510             if (!ts.isValidTypeOnlyAliasUseSite(useSite)) {
45511                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol);
45512                 if (typeOnlyDeclaration) {
45513                     var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
45514                     var message = isExport
45515                         ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type
45516                         : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
45517                     var relatedMessage = isExport
45518                         ? ts.Diagnostics._0_was_exported_here
45519                         : ts.Diagnostics._0_was_imported_here;
45520                     var unescapedName = ts.unescapeLeadingUnderscores(name);
45521                     ts.addRelatedInfo(error(useSite, message, unescapedName), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, unescapedName));
45522                 }
45523             }
45524         }
45525         function getIsDeferredContext(location, lastLocation) {
45526             if (location.kind !== 209 /* ArrowFunction */ && location.kind !== 208 /* FunctionExpression */) {
45527                 // initializers in instance property declaration of class like entities are executed in constructor and thus deferred
45528                 return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) ||
45529                     (location.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred
45530             }
45531             if (lastLocation && lastLocation === location.name) {
45532                 return false;
45533             }
45534             // generator functions and async functions are not inlined in control flow when immediately invoked
45535             if (location.asteriskToken || ts.hasSyntacticModifier(location, 256 /* Async */)) {
45536                 return true;
45537             }
45538             return !ts.getImmediatelyInvokedFunctionExpression(location);
45539         }
45540         function isSelfReferenceLocation(node) {
45541             switch (node.kind) {
45542                 case 251 /* FunctionDeclaration */:
45543                 case 252 /* ClassDeclaration */:
45544                 case 253 /* InterfaceDeclaration */:
45545                 case 255 /* EnumDeclaration */:
45546                 case 254 /* TypeAliasDeclaration */:
45547                 case 256 /* ModuleDeclaration */: // For `namespace N { N; }`
45548                     return true;
45549                 default:
45550                     return false;
45551             }
45552         }
45553         function diagnosticName(nameArg) {
45554             return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
45555         }
45556         function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
45557             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
45558                 var decl = _a[_i];
45559                 if (decl.kind === 159 /* TypeParameter */) {
45560                     var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
45561                     if (parent === container) {
45562                         return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
45563                     }
45564                 }
45565             }
45566             return false;
45567         }
45568         function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
45569             if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
45570                 return false;
45571             }
45572             var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
45573             var location = container;
45574             while (location) {
45575                 if (ts.isClassLike(location.parent)) {
45576                     var classSymbol = getSymbolOfNode(location.parent);
45577                     if (!classSymbol) {
45578                         break;
45579                     }
45580                     // Check to see if a static member exists.
45581                     var constructorType = getTypeOfSymbol(classSymbol);
45582                     if (getPropertyOfType(constructorType, name)) {
45583                         error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
45584                         return true;
45585                     }
45586                     // No static member is present.
45587                     // Check if we're in an instance method and look for a relevant instance member.
45588                     if (location === container && !ts.hasSyntacticModifier(location, 32 /* Static */)) {
45589                         var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
45590                         if (getPropertyOfType(instanceType, name)) {
45591                             error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
45592                             return true;
45593                         }
45594                     }
45595                 }
45596                 location = location.parent;
45597             }
45598             return false;
45599         }
45600         function checkAndReportErrorForExtendingInterface(errorLocation) {
45601             var expression = getEntityNameForExtendingInterface(errorLocation);
45602             if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
45603                 error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
45604                 return true;
45605             }
45606             return false;
45607         }
45608         /**
45609          * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
45610          * but returns undefined if that expression is not an EntityNameExpression.
45611          */
45612         function getEntityNameForExtendingInterface(node) {
45613             switch (node.kind) {
45614                 case 78 /* Identifier */:
45615                 case 201 /* PropertyAccessExpression */:
45616                     return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
45617                 case 223 /* ExpressionWithTypeArguments */:
45618                     if (ts.isEntityNameExpression(node.expression)) {
45619                         return node.expression;
45620                     }
45621                 // falls through
45622                 default:
45623                     return undefined;
45624             }
45625         }
45626         function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
45627             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
45628             if (meaning === namespaceMeaning) {
45629                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
45630                 var parent = errorLocation.parent;
45631                 if (symbol) {
45632                     if (ts.isQualifiedName(parent)) {
45633                         ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
45634                         var propName = parent.right.escapedText;
45635                         var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
45636                         if (propType) {
45637                             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));
45638                             return true;
45639                         }
45640                     }
45641                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
45642                     return true;
45643                 }
45644             }
45645             return false;
45646         }
45647         function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
45648             if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
45649                 var symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
45650                 if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
45651                     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));
45652                     return true;
45653                 }
45654             }
45655             return false;
45656         }
45657         function isPrimitiveTypeName(name) {
45658             return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
45659         }
45660         function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
45661             if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 270 /* ExportSpecifier */) {
45662                 error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
45663                 return true;
45664             }
45665             return false;
45666         }
45667         function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
45668             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */)) {
45669                 if (isPrimitiveTypeName(name)) {
45670                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
45671                     return true;
45672                 }
45673                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
45674                 if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
45675                     var rawName = ts.unescapeLeadingUnderscores(name);
45676                     if (isES2015OrLaterConstructorName(name)) {
45677                         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);
45678                     }
45679                     else if (maybeMappedType(errorLocation, symbol)) {
45680                         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");
45681                     }
45682                     else {
45683                         error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, rawName);
45684                     }
45685                     return true;
45686                 }
45687             }
45688             return false;
45689         }
45690         function maybeMappedType(node, symbol) {
45691             var container = ts.findAncestor(node.parent, function (n) {
45692                 return ts.isComputedPropertyName(n) || ts.isPropertySignature(n) ? false : ts.isTypeLiteralNode(n) || "quit";
45693             });
45694             if (container && container.members.length === 1) {
45695                 var type = getDeclaredTypeOfSymbol(symbol);
45696                 return !!(type.flags & 1048576 /* Union */) && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true);
45697             }
45698             return false;
45699         }
45700         function isES2015OrLaterConstructorName(n) {
45701             switch (n) {
45702                 case "Promise":
45703                 case "Symbol":
45704                 case "Map":
45705                 case "WeakMap":
45706                 case "Set":
45707                 case "WeakSet":
45708                     return true;
45709             }
45710             return false;
45711         }
45712         function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
45713             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */ & ~788968 /* Type */)) {
45714                 var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
45715                 if (symbol) {
45716                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
45717                     return true;
45718                 }
45719             }
45720             else if (meaning & (788968 /* Type */ & ~1024 /* NamespaceModule */ & ~111551 /* Value */)) {
45721                 var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~788968 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
45722                 if (symbol) {
45723                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
45724                     return true;
45725                 }
45726             }
45727             return false;
45728         }
45729         function checkResolvedBlockScopedVariable(result, errorLocation) {
45730             ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
45731             if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
45732                 // constructor functions aren't block scoped
45733                 return;
45734             }
45735             // Block-scoped variables cannot be used before their definition
45736             var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 255 /* EnumDeclaration */); });
45737             if (declaration === undefined)
45738                 return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
45739             if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
45740                 var diagnosticMessage = void 0;
45741                 var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
45742                 if (result.flags & 2 /* BlockScopedVariable */) {
45743                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
45744                 }
45745                 else if (result.flags & 32 /* Class */) {
45746                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
45747                 }
45748                 else if (result.flags & 256 /* RegularEnum */) {
45749                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
45750                 }
45751                 else {
45752                     ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
45753                     if (ts.shouldPreserveConstEnums(compilerOptions)) {
45754                         diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
45755                     }
45756                 }
45757                 if (diagnosticMessage) {
45758                     ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
45759                 }
45760             }
45761         }
45762         /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
45763          * If at any point current node is equal to 'parent' node - return true.
45764          * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
45765          */
45766         function isSameScopeDescendentOf(initial, parent, stopAt) {
45767             return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
45768         }
45769         function getAnyImportSyntax(node) {
45770             switch (node.kind) {
45771                 case 260 /* ImportEqualsDeclaration */:
45772                     return node;
45773                 case 262 /* ImportClause */:
45774                     return node.parent;
45775                 case 263 /* NamespaceImport */:
45776                     return node.parent.parent;
45777                 case 265 /* ImportSpecifier */:
45778                     return node.parent.parent.parent;
45779                 default:
45780                     return undefined;
45781             }
45782         }
45783         function getDeclarationOfAliasSymbol(symbol) {
45784             return ts.find(symbol.declarations, isAliasSymbolDeclaration);
45785         }
45786         /**
45787          * An alias symbol is created by one of the following declarations:
45788          * import <symbol> = ...
45789          * import <symbol> from ...
45790          * import * as <symbol> from ...
45791          * import { x as <symbol> } from ...
45792          * export { x as <symbol> } from ...
45793          * export * as ns <symbol> from ...
45794          * export = <EntityNameExpression>
45795          * export default <EntityNameExpression>
45796          * module.exports = <EntityNameExpression>
45797          * {<Identifier>}
45798          * {name: <EntityNameExpression>}
45799          */
45800         function isAliasSymbolDeclaration(node) {
45801             return node.kind === 260 /* ImportEqualsDeclaration */
45802                 || node.kind === 259 /* NamespaceExportDeclaration */
45803                 || node.kind === 262 /* ImportClause */ && !!node.name
45804                 || node.kind === 263 /* NamespaceImport */
45805                 || node.kind === 269 /* NamespaceExport */
45806                 || node.kind === 265 /* ImportSpecifier */
45807                 || node.kind === 270 /* ExportSpecifier */
45808                 || node.kind === 266 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node)
45809                 || ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node)
45810                 || ts.isAccessExpression(node)
45811                     && ts.isBinaryExpression(node.parent)
45812                     && node.parent.left === node
45813                     && node.parent.operatorToken.kind === 62 /* EqualsToken */
45814                     && isAliasableOrJsExpression(node.parent.right)
45815                 || node.kind === 289 /* ShorthandPropertyAssignment */
45816                 || node.kind === 288 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer)
45817                 || ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true);
45818         }
45819         function isAliasableOrJsExpression(e) {
45820             return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e);
45821         }
45822         function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
45823             var commonJSPropertyAccess = getCommonJSPropertyAccess(node);
45824             if (commonJSPropertyAccess) {
45825                 var name = ts.getLeftmostAccessExpression(commonJSPropertyAccess.expression).arguments[0];
45826                 return ts.isIdentifier(commonJSPropertyAccess.name)
45827                     ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText))
45828                     : undefined;
45829             }
45830             if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 272 /* ExternalModuleReference */) {
45831                 var immediate = resolveExternalModuleName(node, ts.getExternalModuleRequireArgument(node) || ts.getExternalModuleImportEqualsDeclarationExpression(node));
45832                 var resolved_4 = resolveExternalModuleSymbol(immediate);
45833                 markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false);
45834                 return resolved_4;
45835             }
45836             var resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
45837             checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
45838             return resolved;
45839         }
45840         function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
45841             if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false) && !node.isTypeOnly) {
45842                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node));
45843                 var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
45844                 var message = isExport
45845                     ? ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type
45846                     : ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
45847                 var relatedMessage = isExport
45848                     ? ts.Diagnostics._0_was_exported_here
45849                     : ts.Diagnostics._0_was_imported_here;
45850                 // Non-null assertion is safe because the optionality comes from ImportClause,
45851                 // but if an ImportClause was the typeOnlyDeclaration, it had to have a `name`.
45852                 var name = ts.unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText);
45853                 ts.addRelatedInfo(error(node.moduleReference, message), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
45854             }
45855         }
45856         function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
45857             var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
45858             var exportSymbol = exportValue ? getPropertyOfType(getTypeOfSymbol(exportValue), name) : moduleSymbol.exports.get(name);
45859             var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
45860             markSymbolOfAliasDeclarationIfTypeOnly(sourceNode, exportSymbol, resolved, /*overwriteEmpty*/ false);
45861             return resolved;
45862         }
45863         function isSyntacticDefault(node) {
45864             return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasSyntacticModifier(node, 512 /* Default */) || ts.isExportSpecifier(node));
45865         }
45866         function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) {
45867             if (!allowSyntheticDefaultImports) {
45868                 return false;
45869             }
45870             // Declaration files (and ambient modules)
45871             if (!file || file.isDeclarationFile) {
45872                 // Definitely cannot have a synthetic default if they have a syntactic default member specified
45873                 var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*sourceNode*/ undefined, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
45874                 if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) {
45875                     return false;
45876                 }
45877                 // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member
45878                 // So we check a bit more,
45879                 if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias)) {
45880                     // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code),
45881                     // it definitely is a module and does not have a synthetic default
45882                     return false;
45883                 }
45884                 // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set
45885                 // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member
45886                 // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm
45887                 return true;
45888             }
45889             // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement
45890             if (!ts.isSourceFileJS(file)) {
45891                 return hasExportAssignmentSymbol(moduleSymbol);
45892             }
45893             // 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
45894             return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias);
45895         }
45896         function getTargetOfImportClause(node, dontResolveAlias) {
45897             var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
45898             if (moduleSymbol) {
45899                 var exportDefaultSymbol = void 0;
45900                 if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
45901                     exportDefaultSymbol = moduleSymbol;
45902                 }
45903                 else {
45904                     exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias);
45905                 }
45906                 var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
45907                 var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
45908                 if (!exportDefaultSymbol && !hasSyntheticDefault) {
45909                     if (hasExportAssignmentSymbol(moduleSymbol)) {
45910                         var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop";
45911                         var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */);
45912                         var exportAssignment = exportEqualsSymbol.valueDeclaration;
45913                         var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
45914                         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));
45915                     }
45916                     else {
45917                         reportNonDefaultExport(moduleSymbol, node);
45918                     }
45919                 }
45920                 else if (hasSyntheticDefault) {
45921                     // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present
45922                     var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
45923                     markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false);
45924                     return resolved;
45925                 }
45926                 markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ undefined, /*overwriteTypeOnly*/ false);
45927                 return exportDefaultSymbol;
45928             }
45929         }
45930         function reportNonDefaultExport(moduleSymbol, node) {
45931             var _a, _b;
45932             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) {
45933                 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));
45934             }
45935             else {
45936                 var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
45937                 var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */);
45938                 if (exportStar) {
45939                     var defaultExport = ts.find(exportStar.declarations, function (decl) {
45940                         var _a, _b;
45941                         return !!(ts.isExportDeclaration(decl) && decl.moduleSpecifier &&
45942                             ((_b = (_a = resolveExternalModuleName(decl, decl.moduleSpecifier)) === null || _a === void 0 ? void 0 : _a.exports) === null || _b === void 0 ? void 0 : _b.has("default" /* Default */)));
45943                     });
45944                     if (defaultExport) {
45945                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default));
45946                     }
45947                 }
45948             }
45949         }
45950         function getTargetOfNamespaceImport(node, dontResolveAlias) {
45951             var moduleSpecifier = node.parent.parent.moduleSpecifier;
45952             var immediate = resolveExternalModuleName(node, moduleSpecifier);
45953             var resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
45954             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
45955             return resolved;
45956         }
45957         function getTargetOfNamespaceExport(node, dontResolveAlias) {
45958             var moduleSpecifier = node.parent.moduleSpecifier;
45959             var immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
45960             var resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
45961             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
45962             return resolved;
45963         }
45964         // This function creates a synthetic symbol that combines the value side of one symbol with the
45965         // type/namespace side of another symbol. Consider this example:
45966         //
45967         //   declare module graphics {
45968         //       interface Point {
45969         //           x: number;
45970         //           y: number;
45971         //       }
45972         //   }
45973         //   declare var graphics: {
45974         //       Point: new (x: number, y: number) => graphics.Point;
45975         //   }
45976         //   declare module "graphics" {
45977         //       export = graphics;
45978         //   }
45979         //
45980         // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point'
45981         // property with the type/namespace side interface 'Point'.
45982         function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
45983             if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
45984                 return unknownSymbol;
45985             }
45986             if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) {
45987                 return valueSymbol;
45988             }
45989             var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
45990             result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues);
45991             result.parent = valueSymbol.parent || typeSymbol.parent;
45992             if (valueSymbol.valueDeclaration)
45993                 result.valueDeclaration = valueSymbol.valueDeclaration;
45994             if (typeSymbol.members)
45995                 result.members = new ts.Map(typeSymbol.members);
45996             if (valueSymbol.exports)
45997                 result.exports = new ts.Map(valueSymbol.exports);
45998             return result;
45999         }
46000         function getExportOfModule(symbol, name, specifier, dontResolveAlias) {
46001             if (symbol.flags & 1536 /* Module */) {
46002                 var exportSymbol = getExportsOfSymbol(symbol).get(name.escapedText);
46003                 var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
46004                 markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false);
46005                 return resolved;
46006             }
46007         }
46008         function getPropertyOfVariable(symbol, name) {
46009             if (symbol.flags & 3 /* Variable */) {
46010                 var typeAnnotation = symbol.valueDeclaration.type;
46011                 if (typeAnnotation) {
46012                     return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
46013                 }
46014             }
46015         }
46016         function getExternalModuleMember(node, specifier, dontResolveAlias) {
46017             var _a;
46018             if (dontResolveAlias === void 0) { dontResolveAlias = false; }
46019             var moduleSpecifier = ts.getExternalModuleRequireArgument(node) || node.moduleSpecifier;
46020             var moduleSymbol = resolveExternalModuleName(node, moduleSpecifier); // TODO: GH#18217
46021             var name = !ts.isPropertyAccessExpression(specifier) && specifier.propertyName || specifier.name;
46022             if (!ts.isIdentifier(name)) {
46023                 return undefined;
46024             }
46025             var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop);
46026             var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError);
46027             if (targetSymbol) {
46028                 if (name.escapedText) {
46029                     if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
46030                         return moduleSymbol;
46031                     }
46032                     var symbolFromVariable = void 0;
46033                     // First check if module was specified with "export=". If so, get the member from the resolved type
46034                     if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
46035                         symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText, /*skipObjectFunctionPropertyAugment*/ true);
46036                     }
46037                     else {
46038                         symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
46039                     }
46040                     // if symbolFromVariable is export - get its final target
46041                     symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
46042                     var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias);
46043                     if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) {
46044                         var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
46045                         if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) {
46046                             symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
46047                         }
46048                     }
46049                     var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ?
46050                         combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
46051                         symbolFromModule || symbolFromVariable;
46052                     if (!symbol) {
46053                         var moduleName = getFullyQualifiedName(moduleSymbol, node);
46054                         var declarationName = ts.declarationNameToString(name);
46055                         var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol);
46056                         if (suggestion !== undefined) {
46057                             var suggestionName = symbolToString(suggestion);
46058                             var diagnostic = error(name, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
46059                             if (suggestion.valueDeclaration) {
46060                                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
46061                             }
46062                         }
46063                         else {
46064                             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) {
46065                                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName);
46066                             }
46067                             else {
46068                                 reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName);
46069                             }
46070                         }
46071                     }
46072                     return symbol;
46073                 }
46074             }
46075         }
46076         function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) {
46077             var _a;
46078             var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText);
46079             var exports = moduleSymbol.exports;
46080             if (localSymbol) {
46081                 var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */);
46082                 if (exportedEqualsSymbol) {
46083                     getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) :
46084                         error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
46085                 }
46086                 else {
46087                     var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined;
46088                     var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) :
46089                         error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
46090                     ts.addRelatedInfo.apply(void 0, __spreadArray([diagnostic], ts.map(localSymbol.declarations, function (decl, index) {
46091                         return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName);
46092                     })));
46093                 }
46094             }
46095             else {
46096                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
46097             }
46098         }
46099         function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) {
46100             if (moduleKind >= ts.ModuleKind.ES2015) {
46101                 var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import :
46102                     ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
46103                 error(name, message, declarationName);
46104             }
46105             else {
46106                 if (ts.isInJSFile(node)) {
46107                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import :
46108                         ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
46109                     error(name, message, declarationName);
46110                 }
46111                 else {
46112                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import :
46113                         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;
46114                     error(name, message, declarationName, declarationName, moduleName);
46115                 }
46116             }
46117         }
46118         function getTargetOfImportSpecifier(node, dontResolveAlias) {
46119             var root = ts.isBindingElement(node) ? ts.getRootDeclaration(node) : node.parent.parent.parent;
46120             var commonJSPropertyAccess = getCommonJSPropertyAccess(root);
46121             var resolved = getExternalModuleMember(root, commonJSPropertyAccess || node, dontResolveAlias);
46122             var name = node.propertyName || node.name;
46123             if (commonJSPropertyAccess && resolved && ts.isIdentifier(name)) {
46124                 return resolveSymbol(getPropertyOfType(getTypeOfSymbol(resolved), name.escapedText), dontResolveAlias);
46125             }
46126             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
46127             return resolved;
46128         }
46129         function getCommonJSPropertyAccess(node) {
46130             if (ts.isVariableDeclaration(node) && node.initializer && ts.isPropertyAccessExpression(node.initializer)) {
46131                 return node.initializer;
46132             }
46133         }
46134         function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
46135             var resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
46136             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
46137             return resolved;
46138         }
46139         function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
46140             var resolved = node.parent.parent.moduleSpecifier ?
46141                 getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
46142                 resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias);
46143             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
46144             return resolved;
46145         }
46146         function getTargetOfExportAssignment(node, dontResolveAlias) {
46147             var expression = ts.isExportAssignment(node) ? node.expression : node.right;
46148             var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
46149             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
46150             return resolved;
46151         }
46152         function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
46153             if (ts.isClassExpression(expression)) {
46154                 return checkExpressionCached(expression).symbol;
46155             }
46156             if (!ts.isEntityName(expression) && !ts.isEntityNameExpression(expression)) {
46157                 return undefined;
46158             }
46159             var aliasLike = resolveEntityName(expression, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
46160             if (aliasLike) {
46161                 return aliasLike;
46162             }
46163             checkExpressionCached(expression);
46164             return getNodeLinks(expression).resolvedSymbol;
46165         }
46166         function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) {
46167             var expression = node.initializer;
46168             return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve);
46169         }
46170         function getTargetOfAccessExpression(node, dontRecursivelyResolve) {
46171             if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */)) {
46172                 return undefined;
46173             }
46174             return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
46175         }
46176         function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
46177             if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; }
46178             switch (node.kind) {
46179                 case 260 /* ImportEqualsDeclaration */:
46180                 case 249 /* VariableDeclaration */:
46181                     return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
46182                 case 262 /* ImportClause */:
46183                     return getTargetOfImportClause(node, dontRecursivelyResolve);
46184                 case 263 /* NamespaceImport */:
46185                     return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
46186                 case 269 /* NamespaceExport */:
46187                     return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
46188                 case 265 /* ImportSpecifier */:
46189                 case 198 /* BindingElement */:
46190                     return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
46191                 case 270 /* ExportSpecifier */:
46192                     return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
46193                 case 266 /* ExportAssignment */:
46194                 case 216 /* BinaryExpression */:
46195                     return getTargetOfExportAssignment(node, dontRecursivelyResolve);
46196                 case 259 /* NamespaceExportDeclaration */:
46197                     return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
46198                 case 289 /* ShorthandPropertyAssignment */:
46199                     return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve);
46200                 case 288 /* PropertyAssignment */:
46201                     return getTargetOfPropertyAssignment(node, dontRecursivelyResolve);
46202                 case 202 /* ElementAccessExpression */:
46203                 case 201 /* PropertyAccessExpression */:
46204                     return getTargetOfAccessExpression(node, dontRecursivelyResolve);
46205                 default:
46206                     return ts.Debug.fail();
46207             }
46208         }
46209         /**
46210          * Indicates that a symbol is an alias that does not merge with a local declaration.
46211          * OR Is a JSContainer which may merge an alias with a local declaration
46212          */
46213         function isNonLocalAlias(symbol, excludes) {
46214             if (excludes === void 0) { excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */; }
46215             if (!symbol)
46216                 return false;
46217             return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
46218         }
46219         function resolveSymbol(symbol, dontResolveAlias) {
46220             return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
46221         }
46222         function resolveAlias(symbol) {
46223             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
46224             var links = getSymbolLinks(symbol);
46225             if (!links.target) {
46226                 links.target = resolvingSymbol;
46227                 var node = getDeclarationOfAliasSymbol(symbol);
46228                 if (!node)
46229                     return ts.Debug.fail();
46230                 var target = getTargetOfAliasDeclaration(node);
46231                 if (links.target === resolvingSymbol) {
46232                     links.target = target || unknownSymbol;
46233                 }
46234                 else {
46235                     error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
46236                 }
46237             }
46238             else if (links.target === resolvingSymbol) {
46239                 links.target = unknownSymbol;
46240             }
46241             return links.target;
46242         }
46243         function tryResolveAlias(symbol) {
46244             var links = getSymbolLinks(symbol);
46245             if (links.target !== resolvingSymbol) {
46246                 return resolveAlias(symbol);
46247             }
46248             return undefined;
46249         }
46250         /**
46251          * Marks a symbol as type-only if its declaration is syntactically type-only.
46252          * If it is not itself marked type-only, but resolves to a type-only alias
46253          * somewhere in its resolution chain, save a reference to the type-only alias declaration
46254          * so the alias _not_ marked type-only can be identified as _transitively_ type-only.
46255          *
46256          * This function is called on each alias declaration that could be type-only or resolve to
46257          * another type-only alias during `resolveAlias`, so that later, when an alias is used in a
46258          * JS-emitting expression, we can quickly determine if that symbol is effectively type-only
46259          * and issue an error if so.
46260          *
46261          * @param aliasDeclaration The alias declaration not marked as type-only
46262          * has already been marked as not resolving to a type-only alias. Used when recursively resolving qualified
46263          * names of import aliases, e.g. `import C = a.b.C`. If namespace `a` is not found to be type-only, the
46264          * import declaration will initially be marked as not resolving to a type-only symbol. But, namespace `b`
46265          * must still be checked for a type-only marker, overwriting the previous negative result if found.
46266          * @param immediateTarget The symbol to which the alias declaration immediately resolves
46267          * @param finalTarget The symbol to which the alias declaration ultimately resolves
46268          * @param overwriteEmpty Checks `resolvesToSymbol` for type-only declarations even if `aliasDeclaration`
46269          */
46270         function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty) {
46271             if (!aliasDeclaration || ts.isPropertyAccessExpression(aliasDeclaration))
46272                 return false;
46273             // If the declaration itself is type-only, mark it and return.
46274             // No need to check what it resolves to.
46275             var sourceSymbol = getSymbolOfNode(aliasDeclaration);
46276             if (ts.isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
46277                 var links_1 = getSymbolLinks(sourceSymbol);
46278                 links_1.typeOnlyDeclaration = aliasDeclaration;
46279                 return true;
46280             }
46281             var links = getSymbolLinks(sourceSymbol);
46282             return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty)
46283                 || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
46284         }
46285         function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
46286             var _a, _b, _c;
46287             if (target && (aliasDeclarationLinks.typeOnlyDeclaration === undefined || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
46288                 var exportSymbol = (_b = (_a = target.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* ExportEquals */)) !== null && _b !== void 0 ? _b : target;
46289                 var typeOnly = exportSymbol.declarations && ts.find(exportSymbol.declarations, ts.isTypeOnlyImportOrExportDeclaration);
46290                 aliasDeclarationLinks.typeOnlyDeclaration = (_c = typeOnly !== null && typeOnly !== void 0 ? typeOnly : getSymbolLinks(exportSymbol).typeOnlyDeclaration) !== null && _c !== void 0 ? _c : false;
46291             }
46292             return !!aliasDeclarationLinks.typeOnlyDeclaration;
46293         }
46294         /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */
46295         function getTypeOnlyAliasDeclaration(symbol) {
46296             if (!(symbol.flags & 2097152 /* Alias */)) {
46297                 return undefined;
46298             }
46299             var links = getSymbolLinks(symbol);
46300             return links.typeOnlyDeclaration || undefined;
46301         }
46302         function markExportAsReferenced(node) {
46303             var symbol = getSymbolOfNode(node);
46304             var target = resolveAlias(symbol);
46305             if (target) {
46306                 var markAlias = target === unknownSymbol ||
46307                     ((target.flags & 111551 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol));
46308                 if (markAlias) {
46309                     markAliasSymbolAsReferenced(symbol);
46310                 }
46311             }
46312         }
46313         // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until
46314         // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of
46315         // the alias as an expression (which recursively takes us back here if the target references another alias).
46316         function markAliasSymbolAsReferenced(symbol) {
46317             var links = getSymbolLinks(symbol);
46318             if (!links.referenced) {
46319                 links.referenced = true;
46320                 var node = getDeclarationOfAliasSymbol(symbol);
46321                 if (!node)
46322                     return ts.Debug.fail();
46323                 // We defer checking of the reference of an `import =` until the import itself is referenced,
46324                 // This way a chain of imports can be elided if ultimately the final input is only used in a type
46325                 // position.
46326                 if (ts.isInternalModuleImportEqualsDeclaration(node)) {
46327                     var target = resolveSymbol(symbol);
46328                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
46329                         // import foo = <symbol>
46330                         checkExpressionCached(node.moduleReference);
46331                     }
46332                 }
46333             }
46334         }
46335         // Aliases that resolve to const enums are not marked as referenced because they are not emitted,
46336         // but their usage in value positions must be tracked to determine if the import can be type-only.
46337         function markConstEnumAliasAsReferenced(symbol) {
46338             var links = getSymbolLinks(symbol);
46339             if (!links.constEnumReferenced) {
46340                 links.constEnumReferenced = true;
46341             }
46342         }
46343         // This function is only for imports with entity names
46344         function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
46345             // There are three things we might try to look for. In the following examples,
46346             // the search term is enclosed in |...|:
46347             //
46348             //     import a = |b|; // Namespace
46349             //     import a = |b.c|; // Value, type, namespace
46350             //     import a = |b.c|.d; // Namespace
46351             if (entityName.kind === 78 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
46352                 entityName = entityName.parent;
46353             }
46354             // Check for case 1 and 3 in the above example
46355             if (entityName.kind === 78 /* Identifier */ || entityName.parent.kind === 157 /* QualifiedName */) {
46356                 return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
46357             }
46358             else {
46359                 // Case 2 in above example
46360                 // entityName.kind could be a QualifiedName or a Missing identifier
46361                 ts.Debug.assert(entityName.parent.kind === 260 /* ImportEqualsDeclaration */);
46362                 return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
46363             }
46364         }
46365         function getFullyQualifiedName(symbol, containingLocation) {
46366             return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */);
46367         }
46368         /**
46369          * Resolves a qualified name and any involved aliases.
46370          */
46371         function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
46372             if (ts.nodeIsMissing(name)) {
46373                 return undefined;
46374             }
46375             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0);
46376             var symbol;
46377             if (name.kind === 78 /* Identifier */) {
46378                 var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name));
46379                 var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined;
46380                 symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true));
46381                 if (!symbol) {
46382                     return getMergedSymbol(symbolFromJSPrototype);
46383                 }
46384             }
46385             else if (name.kind === 157 /* QualifiedName */ || name.kind === 201 /* PropertyAccessExpression */) {
46386                 var left = name.kind === 157 /* QualifiedName */ ? name.left : name.expression;
46387                 var right = name.kind === 157 /* QualifiedName */ ? name.right : name.name;
46388                 var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
46389                 if (!namespace || ts.nodeIsMissing(right)) {
46390                     return undefined;
46391                 }
46392                 else if (namespace === unknownSymbol) {
46393                     return namespace;
46394                 }
46395                 if (ts.isInJSFile(name)) {
46396                     if (namespace.valueDeclaration &&
46397                         ts.isVariableDeclaration(namespace.valueDeclaration) &&
46398                         namespace.valueDeclaration.initializer &&
46399                         isCommonJsRequire(namespace.valueDeclaration.initializer)) {
46400                         var moduleName = namespace.valueDeclaration.initializer.arguments[0];
46401                         var moduleSym = resolveExternalModuleName(moduleName, moduleName);
46402                         if (moduleSym) {
46403                             var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
46404                             if (resolvedModuleSymbol) {
46405                                 namespace = resolvedModuleSymbol;
46406                             }
46407                         }
46408                     }
46409                 }
46410                 symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning));
46411                 if (!symbol) {
46412                     if (!ignoreErrors) {
46413                         var namespaceName = getFullyQualifiedName(namespace);
46414                         var declarationName = ts.declarationNameToString(right);
46415                         var suggestion = getSuggestedSymbolForNonexistentModule(right, namespace);
46416                         suggestion ?
46417                             error(right, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestion)) :
46418                             error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName);
46419                     }
46420                     return undefined;
46421                 }
46422             }
46423             else {
46424                 throw ts.Debug.assertNever(name, "Unknown entity name kind.");
46425             }
46426             ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
46427             if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 266 /* ExportAssignment */)) {
46428                 markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true);
46429             }
46430             return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
46431         }
46432         /**
46433          * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
46434          * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
46435          * name resolution won't work either.
46436          * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
46437          */
46438         function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
46439             if (isJSDocTypeReference(name.parent)) {
46440                 var secondaryLocation = getAssignmentDeclarationLocation(name.parent);
46441                 if (secondaryLocation) {
46442                     return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
46443                 }
46444             }
46445         }
46446         function getAssignmentDeclarationLocation(node) {
46447             var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 4194304 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
46448             if (typeAlias) {
46449                 return;
46450             }
46451             var host = ts.getJSDocHost(node);
46452             if (host &&
46453                 ts.isExpressionStatement(host) &&
46454                 ts.isBinaryExpression(host.expression) &&
46455                 ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
46456                 // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
46457                 var symbol = getSymbolOfNode(host.expression.left);
46458                 if (symbol) {
46459                     return getDeclarationOfJSPrototypeContainer(symbol);
46460                 }
46461             }
46462             if (host && (ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
46463                 ts.isBinaryExpression(host.parent.parent) &&
46464                 ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
46465                 // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
46466                 var symbol = getSymbolOfNode(host.parent.parent.left);
46467                 if (symbol) {
46468                     return getDeclarationOfJSPrototypeContainer(symbol);
46469                 }
46470             }
46471             var sig = ts.getEffectiveJSDocHost(node);
46472             if (sig && ts.isFunctionLike(sig)) {
46473                 var symbol = getSymbolOfNode(sig);
46474                 return symbol && symbol.valueDeclaration;
46475             }
46476         }
46477         function getDeclarationOfJSPrototypeContainer(symbol) {
46478             var decl = symbol.parent.valueDeclaration;
46479             if (!decl) {
46480                 return undefined;
46481             }
46482             var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) :
46483                 ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) :
46484                     undefined;
46485             return initializer || decl;
46486         }
46487         /**
46488          * Get the real symbol of a declaration with an expando initializer.
46489          *
46490          * Normally, declarations have an associated symbol, but when a declaration has an expando
46491          * initializer, the expando's symbol is the one that has all the members merged into it.
46492          */
46493         function getExpandoSymbol(symbol) {
46494             var decl = symbol.valueDeclaration;
46495             if (!decl || !ts.isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false)) {
46496                 return undefined;
46497             }
46498             var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl);
46499             if (init) {
46500                 var initSymbol = getSymbolOfNode(init);
46501                 if (initSymbol) {
46502                     return mergeJSSymbols(initSymbol, symbol);
46503                 }
46504             }
46505         }
46506         function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
46507             var isClassic = ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.Classic;
46508             var errorMessage = isClassic ?
46509                 ts.Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option
46510                 : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations;
46511             return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : errorMessage);
46512         }
46513         function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
46514             if (isForAugmentation === void 0) { isForAugmentation = false; }
46515             return ts.isStringLiteralLike(moduleReferenceExpression)
46516                 ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation)
46517                 : undefined;
46518         }
46519         function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) {
46520             if (isForAugmentation === void 0) { isForAugmentation = false; }
46521             if (ts.startsWith(moduleReference, "@types/")) {
46522                 var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
46523                 var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/");
46524                 error(errorNode, diag, withoutAtTypePrefix, moduleReference);
46525             }
46526             var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true);
46527             if (ambientModule) {
46528                 return ambientModule;
46529             }
46530             var currentSourceFile = ts.getSourceFileOfNode(location);
46531             var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217
46532             var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule);
46533             var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
46534             if (sourceFile) {
46535                 if (sourceFile.symbol) {
46536                     if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
46537                         errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
46538                     }
46539                     // merged symbol is module declaration symbol combined with all augmentations
46540                     return getMergedSymbol(sourceFile.symbol);
46541                 }
46542                 if (moduleNotFoundError) {
46543                     // report errors only if it was requested
46544                     error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
46545                 }
46546                 return undefined;
46547             }
46548             if (patternAmbientModules) {
46549                 var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference);
46550                 if (pattern) {
46551                     // If the module reference matched a pattern ambient module ('*.foo') but there's also a
46552                     // module augmentation by the specific name requested ('a.foo'), we store the merged symbol
46553                     // by the augmentation name ('a.foo'), because asking for *.foo should not give you exports
46554                     // from a.foo.
46555                     var augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
46556                     if (augmentation) {
46557                         return getMergedSymbol(augmentation);
46558                     }
46559                     return getMergedSymbol(pattern.symbol);
46560                 }
46561             }
46562             // May be an untyped module. If so, ignore resolutionDiagnostic.
46563             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) {
46564                 if (isForAugmentation) {
46565                     var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
46566                     error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
46567                 }
46568                 else {
46569                     errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference);
46570                 }
46571                 // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
46572                 return undefined;
46573             }
46574             if (moduleNotFoundError) {
46575                 // See if this was possibly a projectReference redirect
46576                 if (resolvedModule) {
46577                     var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
46578                     if (redirect) {
46579                         error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
46580                         return undefined;
46581                     }
46582                 }
46583                 if (resolutionDiagnostic) {
46584                     error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
46585                 }
46586                 else {
46587                     var tsExtension = ts.tryExtractTSExtension(moduleReference);
46588                     if (tsExtension) {
46589                         var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
46590                         var importSourceWithoutExtension = ts.removeExtension(moduleReference, tsExtension);
46591                         var replacedImportSource = importSourceWithoutExtension;
46592                         /**
46593                          * Direct users to import source with .js extension if outputting an ES module.
46594                          * @see https://github.com/microsoft/TypeScript/issues/42151
46595                          */
46596                         var moduleKind_1 = ts.getEmitModuleKind(compilerOptions);
46597                         if (moduleKind_1 >= ts.ModuleKind.ES2015) {
46598                             replacedImportSource += ".js";
46599                         }
46600                         error(errorNode, diag, tsExtension, replacedImportSource);
46601                     }
46602                     else if (!compilerOptions.resolveJsonModule &&
46603                         ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
46604                         ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
46605                         ts.hasJsonModuleEmitEnabled(compilerOptions)) {
46606                         error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
46607                     }
46608                     else {
46609                         error(errorNode, moduleNotFoundError, moduleReference);
46610                     }
46611                 }
46612             }
46613             return undefined;
46614         }
46615         function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
46616             var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
46617             var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
46618                 ? typesPackageExists(packageId.name)
46619                     ? ts.chainDiagnosticMessages(
46620                     /*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))
46621                     : ts.chainDiagnosticMessages(
46622                     /*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))
46623                 : undefined;
46624             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));
46625         }
46626         function typesPackageExists(packageName) {
46627             return getPackagesSet().has(ts.getTypesPackageName(packageName));
46628         }
46629         function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
46630             if (moduleSymbol === null || moduleSymbol === void 0 ? void 0 : moduleSymbol.exports) {
46631                 var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
46632                 var exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
46633                 return getMergedSymbol(exported) || moduleSymbol;
46634             }
46635             return undefined;
46636         }
46637         function getCommonJsExportEquals(exported, moduleSymbol) {
46638             if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
46639                 return exported;
46640             }
46641             var links = getSymbolLinks(exported);
46642             if (links.cjsExportMerged) {
46643                 return links.cjsExportMerged;
46644             }
46645             var merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported);
46646             merged.flags = merged.flags | 512 /* ValueModule */;
46647             if (merged.exports === undefined) {
46648                 merged.exports = ts.createSymbolTable();
46649             }
46650             moduleSymbol.exports.forEach(function (s, name) {
46651                 if (name === "export=" /* ExportEquals */)
46652                     return;
46653                 merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
46654             });
46655             getSymbolLinks(merged).cjsExportMerged = merged;
46656             return links.cjsExportMerged = merged;
46657         }
46658         // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
46659         // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
46660         // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
46661         function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
46662             var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
46663             if (!dontResolveAlias && symbol) {
46664                 if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 297 /* SourceFile */)) {
46665                     var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
46666                         ? "allowSyntheticDefaultImports"
46667                         : "esModuleInterop";
46668                     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);
46669                     return symbol;
46670                 }
46671                 if (compilerOptions.esModuleInterop) {
46672                     var referenceParent = referencingLocation.parent;
46673                     if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) ||
46674                         ts.isImportCall(referenceParent)) {
46675                         var type = getTypeOfSymbol(symbol);
46676                         var sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
46677                         if (!sigs || !sigs.length) {
46678                             sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
46679                         }
46680                         if (sigs && sigs.length) {
46681                             var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol);
46682                             // Create a new symbol which has the module's type less the call and construct signatures
46683                             var result = createSymbol(symbol.flags, symbol.escapedName);
46684                             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
46685                             result.parent = symbol.parent;
46686                             result.target = symbol;
46687                             result.originatingImport = referenceParent;
46688                             if (symbol.valueDeclaration)
46689                                 result.valueDeclaration = symbol.valueDeclaration;
46690                             if (symbol.constEnumOnlyModule)
46691                                 result.constEnumOnlyModule = true;
46692                             if (symbol.members)
46693                                 result.members = new ts.Map(symbol.members);
46694                             if (symbol.exports)
46695                                 result.exports = new ts.Map(symbol.exports);
46696                             var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above
46697                             result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo);
46698                             return result;
46699                         }
46700                     }
46701                 }
46702             }
46703             return symbol;
46704         }
46705         function hasExportAssignmentSymbol(moduleSymbol) {
46706             return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined;
46707         }
46708         function getExportsOfModuleAsArray(moduleSymbol) {
46709             return symbolsToArray(getExportsOfModule(moduleSymbol));
46710         }
46711         function getExportsAndPropertiesOfModule(moduleSymbol) {
46712             var exports = getExportsOfModuleAsArray(moduleSymbol);
46713             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
46714             if (exportEquals !== moduleSymbol) {
46715                 ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals)));
46716             }
46717             return exports;
46718         }
46719         function tryGetMemberInModuleExports(memberName, moduleSymbol) {
46720             var symbolTable = getExportsOfModule(moduleSymbol);
46721             if (symbolTable) {
46722                 return symbolTable.get(memberName);
46723             }
46724         }
46725         function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
46726             var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
46727             if (symbol) {
46728                 return symbol;
46729             }
46730             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
46731             if (exportEquals === moduleSymbol) {
46732                 return undefined;
46733             }
46734             var type = getTypeOfSymbol(exportEquals);
46735             return type.flags & 131068 /* Primitive */ ||
46736                 ts.getObjectFlags(type) & 1 /* Class */ ||
46737                 isArrayOrTupleLikeType(type)
46738                 ? undefined
46739                 : getPropertyOfType(type, memberName);
46740         }
46741         function getExportsOfSymbol(symbol) {
46742             return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) :
46743                 symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) :
46744                     symbol.exports || emptySymbols;
46745         }
46746         function getExportsOfModule(moduleSymbol) {
46747             var links = getSymbolLinks(moduleSymbol);
46748             return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol));
46749         }
46750         /**
46751          * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
46752          * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
46753          */
46754         function extendExportSymbols(target, source, lookupTable, exportNode) {
46755             if (!source)
46756                 return;
46757             source.forEach(function (sourceSymbol, id) {
46758                 if (id === "default" /* Default */)
46759                     return;
46760                 var targetSymbol = target.get(id);
46761                 if (!targetSymbol) {
46762                     target.set(id, sourceSymbol);
46763                     if (lookupTable && exportNode) {
46764                         lookupTable.set(id, {
46765                             specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
46766                         });
46767                     }
46768                 }
46769                 else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
46770                     var collisionTracker = lookupTable.get(id);
46771                     if (!collisionTracker.exportsWithDuplicate) {
46772                         collisionTracker.exportsWithDuplicate = [exportNode];
46773                     }
46774                     else {
46775                         collisionTracker.exportsWithDuplicate.push(exportNode);
46776                     }
46777                 }
46778             });
46779         }
46780         function getExportsOfModuleWorker(moduleSymbol) {
46781             var visitedSymbols = [];
46782             // A module defined by an 'export=' consists of one export that needs to be resolved
46783             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
46784             return visit(moduleSymbol) || emptySymbols;
46785             // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
46786             // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
46787             function visit(symbol) {
46788                 if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) {
46789                     return;
46790                 }
46791                 var symbols = new ts.Map(symbol.exports);
46792                 // All export * declarations are collected in an __export symbol by the binder
46793                 var exportStars = symbol.exports.get("__export" /* ExportStar */);
46794                 if (exportStars) {
46795                     var nestedSymbols = ts.createSymbolTable();
46796                     var lookupTable_1 = new ts.Map();
46797                     for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
46798                         var node = _a[_i];
46799                         var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
46800                         var exportedSymbols = visit(resolvedModule);
46801                         extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
46802                     }
46803                     lookupTable_1.forEach(function (_a, id) {
46804                         var exportsWithDuplicate = _a.exportsWithDuplicate;
46805                         // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
46806                         if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
46807                             return;
46808                         }
46809                         for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
46810                             var node = exportsWithDuplicate_1[_i];
46811                             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)));
46812                         }
46813                     });
46814                     extendExportSymbols(symbols, nestedSymbols);
46815                 }
46816                 return symbols;
46817             }
46818         }
46819         function getMergedSymbol(symbol) {
46820             var merged;
46821             return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
46822         }
46823         function getSymbolOfNode(node) {
46824             return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
46825         }
46826         function getParentOfSymbol(symbol) {
46827             return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
46828         }
46829         function getAlternativeContainingModules(symbol, enclosingDeclaration) {
46830             var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
46831             var id = getNodeId(containingFile);
46832             var links = getSymbolLinks(symbol);
46833             var results;
46834             if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
46835                 return results;
46836             }
46837             if (containingFile && containingFile.imports) {
46838                 // Try to make an import using an import already in the enclosing file, if possible
46839                 for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
46840                     var importRef = _a[_i];
46841                     if (ts.nodeIsSynthesized(importRef))
46842                         continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
46843                     var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
46844                     if (!resolvedModule)
46845                         continue;
46846                     var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
46847                     if (!ref)
46848                         continue;
46849                     results = ts.append(results, resolvedModule);
46850                 }
46851                 if (ts.length(results)) {
46852                     (links.extendedContainersByFile || (links.extendedContainersByFile = new ts.Map())).set(id, results);
46853                     return results;
46854                 }
46855             }
46856             if (links.extendedContainers) {
46857                 return links.extendedContainers;
46858             }
46859             // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
46860             var otherFiles = host.getSourceFiles();
46861             for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
46862                 var file = otherFiles_1[_b];
46863                 if (!ts.isExternalModule(file))
46864                     continue;
46865                 var sym = getSymbolOfNode(file);
46866                 var ref = getAliasForSymbolInContainer(sym, symbol);
46867                 if (!ref)
46868                     continue;
46869                 results = ts.append(results, sym);
46870             }
46871             return links.extendedContainers = results || ts.emptyArray;
46872         }
46873         /**
46874          * Attempts to find the symbol corresponding to the container a symbol is in - usually this
46875          * is just its' `.parent`, but for locals, this value is `undefined`
46876          */
46877         function getContainersOfSymbol(symbol, enclosingDeclaration, meaning) {
46878             var container = getParentOfSymbol(symbol);
46879             // Type parameters end up in the `members` lists but are not externally visible
46880             if (container && !(symbol.flags & 262144 /* TypeParameter */)) {
46881                 var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
46882                 var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
46883                 var objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container, meaning);
46884                 if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
46885                     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
46886                 }
46887                 var res = ts.append(ts.append(additionalContainers, container), objectLiteralContainer);
46888                 return ts.concatenate(res, reexportContainers);
46889             }
46890             var candidates = ts.mapDefined(symbol.declarations, function (d) {
46891                 if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
46892                     return getSymbolOfNode(d.parent);
46893                 }
46894                 if (ts.isClassExpression(d) && ts.isBinaryExpression(d.parent) && d.parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isAccessExpression(d.parent.left) && ts.isEntityNameExpression(d.parent.left.expression)) {
46895                     if (ts.isModuleExportsAccessExpression(d.parent.left) || ts.isExportsIdentifier(d.parent.left.expression)) {
46896                         return getSymbolOfNode(ts.getSourceFileOfNode(d));
46897                     }
46898                     checkExpressionCached(d.parent.left.expression);
46899                     return getNodeLinks(d.parent.left.expression).resolvedSymbol;
46900                 }
46901             });
46902             if (!ts.length(candidates)) {
46903                 return undefined;
46904             }
46905             return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; });
46906             function fileSymbolIfFileSymbolExportEqualsContainer(d) {
46907                 return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container);
46908             }
46909         }
46910         function getVariableDeclarationOfObjectLiteral(symbol, meaning) {
46911             // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct
46912             // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however,
46913             // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal.
46914             var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations);
46915             if (meaning & 111551 /* Value */ && firstDecl && firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent)) {
46916                 if (ts.isObjectLiteralExpression(firstDecl) && firstDecl === firstDecl.parent.initializer || ts.isTypeLiteralNode(firstDecl) && firstDecl === firstDecl.parent.type) {
46917                     return getSymbolOfNode(firstDecl.parent);
46918                 }
46919             }
46920         }
46921         function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) {
46922             var fileSymbol = getExternalModuleContainer(d);
46923             var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
46924             return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined;
46925         }
46926         function getAliasForSymbolInContainer(container, symbol) {
46927             if (container === getParentOfSymbol(symbol)) {
46928                 // fast path, `symbol` is either already the alias or isn't aliased
46929                 return symbol;
46930             }
46931             // Check if container is a thing with an `export=` which points directly at `symbol`, and if so, return
46932             // the container itself as the alias for the symbol
46933             var exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */);
46934             if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
46935                 return container;
46936             }
46937             var exports = getExportsOfSymbol(container);
46938             var quick = exports.get(symbol.escapedName);
46939             if (quick && getSymbolIfSameReference(quick, symbol)) {
46940                 return quick;
46941             }
46942             return ts.forEachEntry(exports, function (exported) {
46943                 if (getSymbolIfSameReference(exported, symbol)) {
46944                     return exported;
46945                 }
46946             });
46947         }
46948         /**
46949          * Checks if two symbols, through aliasing and/or merging, refer to the same thing
46950          */
46951         function getSymbolIfSameReference(s1, s2) {
46952             if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
46953                 return s1;
46954             }
46955         }
46956         function getExportSymbolOfValueSymbolIfExported(symbol) {
46957             return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
46958         }
46959         function symbolIsValue(symbol) {
46960             return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 111551 /* Value */ && !getTypeOnlyAliasDeclaration(symbol));
46961         }
46962         function findConstructorDeclaration(node) {
46963             var members = node.members;
46964             for (var _i = 0, members_3 = members; _i < members_3.length; _i++) {
46965                 var member = members_3[_i];
46966                 if (member.kind === 166 /* Constructor */ && ts.nodeIsPresent(member.body)) {
46967                     return member;
46968                 }
46969             }
46970         }
46971         function createType(flags) {
46972             var result = new Type(checker, flags);
46973             typeCount++;
46974             result.id = typeCount;
46975             typeCatalog.push(result);
46976             return result;
46977         }
46978         function createOriginType(flags) {
46979             return new Type(checker, flags);
46980         }
46981         function createIntrinsicType(kind, intrinsicName, objectFlags) {
46982             if (objectFlags === void 0) { objectFlags = 0; }
46983             var type = createType(kind);
46984             type.intrinsicName = intrinsicName;
46985             type.objectFlags = objectFlags;
46986             return type;
46987         }
46988         function createBooleanType(trueFalseTypes) {
46989             var type = getUnionType(trueFalseTypes);
46990             type.flags |= 16 /* Boolean */;
46991             type.intrinsicName = "boolean";
46992             return type;
46993         }
46994         function createObjectType(objectFlags, symbol) {
46995             var type = createType(524288 /* Object */);
46996             type.objectFlags = objectFlags;
46997             type.symbol = symbol;
46998             type.members = undefined;
46999             type.properties = undefined;
47000             type.callSignatures = undefined;
47001             type.constructSignatures = undefined;
47002             type.stringIndexInfo = undefined;
47003             type.numberIndexInfo = undefined;
47004             return type;
47005         }
47006         function createTypeofType() {
47007             return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType));
47008         }
47009         function createTypeParameter(symbol) {
47010             var type = createType(262144 /* TypeParameter */);
47011             if (symbol)
47012                 type.symbol = symbol;
47013             return type;
47014         }
47015         // A reserved member name starts with two underscores, but the third character cannot be an underscore,
47016         // @, or #. A third underscore indicates an escaped form of an identifier that started
47017         // with at least two underscores. The @ character indicates that the name is denoted by a well known ES
47018         // Symbol instance and the # character indicates that the name is a PrivateIdentifier.
47019         function isReservedMemberName(name) {
47020             return name.charCodeAt(0) === 95 /* _ */ &&
47021                 name.charCodeAt(1) === 95 /* _ */ &&
47022                 name.charCodeAt(2) !== 95 /* _ */ &&
47023                 name.charCodeAt(2) !== 64 /* at */ &&
47024                 name.charCodeAt(2) !== 35 /* hash */;
47025         }
47026         function getNamedMembers(members) {
47027             var result;
47028             members.forEach(function (symbol, id) {
47029                 if (!isReservedMemberName(id) && symbolIsValue(symbol)) {
47030                     (result || (result = [])).push(symbol);
47031                 }
47032             });
47033             return result || ts.emptyArray;
47034         }
47035         function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
47036             var resolved = type;
47037             resolved.members = members;
47038             resolved.properties = ts.emptyArray;
47039             resolved.callSignatures = callSignatures;
47040             resolved.constructSignatures = constructSignatures;
47041             resolved.stringIndexInfo = stringIndexInfo;
47042             resolved.numberIndexInfo = numberIndexInfo;
47043             // This can loop back to getPropertyOfType() which would crash if `callSignatures` & `constructSignatures` are not initialized.
47044             if (members !== emptySymbols)
47045                 resolved.properties = getNamedMembers(members);
47046             return resolved;
47047         }
47048         function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
47049             return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
47050         }
47051         function getResolvedTypeWithoutAbstractConstructSignatures(type) {
47052             if (type.constructSignatures.length === 0)
47053                 return type;
47054             if (type.objectTypeWithoutAbstractConstructSignatures)
47055                 return type.objectTypeWithoutAbstractConstructSignatures;
47056             var constructSignatures = ts.filter(type.constructSignatures, function (signature) { return !(signature.flags & 4 /* Abstract */); });
47057             if (type.constructSignatures === constructSignatures)
47058                 return type;
47059             var typeCopy = createAnonymousType(type.symbol, type.members, type.callSignatures, ts.some(constructSignatures) ? constructSignatures : ts.emptyArray, type.stringIndexInfo, type.numberIndexInfo);
47060             type.objectTypeWithoutAbstractConstructSignatures = typeCopy;
47061             typeCopy.objectTypeWithoutAbstractConstructSignatures = typeCopy;
47062             return typeCopy;
47063         }
47064         function forEachSymbolTableInScope(enclosingDeclaration, callback) {
47065             var result;
47066             var _loop_8 = function (location) {
47067                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
47068                 if (location.locals && !isGlobalSourceFile(location)) {
47069                     if (result = callback(location.locals)) {
47070                         return { value: result };
47071                     }
47072                 }
47073                 switch (location.kind) {
47074                     case 297 /* SourceFile */:
47075                         if (!ts.isExternalOrCommonJsModule(location)) {
47076                             break;
47077                         }
47078                     // falls through
47079                     case 256 /* ModuleDeclaration */:
47080                         var sym = getSymbolOfNode(location);
47081                         // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten
47082                         // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred
47083                         // to one another anyway)
47084                         if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) {
47085                             return { value: result };
47086                         }
47087                         break;
47088                     case 252 /* ClassDeclaration */:
47089                     case 221 /* ClassExpression */:
47090                     case 253 /* InterfaceDeclaration */:
47091                         // Type parameters are bound into `members` lists so they can merge across declarations
47092                         // This is troublesome, since in all other respects, they behave like locals :cries:
47093                         // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol
47094                         // lookup logic in terms of `resolveName` would be nice
47095                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
47096                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
47097                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
47098                         var table_1;
47099                         // TODO: Should this filtered table be cached in some way?
47100                         (getSymbolOfNode(location).members || emptySymbols).forEach(function (memberSymbol, key) {
47101                             if (memberSymbol.flags & (788968 /* Type */ & ~67108864 /* Assignment */)) {
47102                                 (table_1 || (table_1 = ts.createSymbolTable())).set(key, memberSymbol);
47103                             }
47104                         });
47105                         if (table_1 && (result = callback(table_1))) {
47106                             return { value: result };
47107                         }
47108                         break;
47109                 }
47110             };
47111             for (var location = enclosingDeclaration; location; location = location.parent) {
47112                 var state_2 = _loop_8(location);
47113                 if (typeof state_2 === "object")
47114                     return state_2.value;
47115             }
47116             return callback(globals);
47117         }
47118         function getQualifiedLeftMeaning(rightMeaning) {
47119             // If we are looking in value space, the parent meaning is value, other wise it is namespace
47120             return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */;
47121         }
47122         function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
47123             if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = new ts.Map(); }
47124             if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
47125                 return undefined;
47126             }
47127             var id = getSymbolId(symbol);
47128             var visitedSymbolTables = visitedSymbolTablesMap.get(id);
47129             if (!visitedSymbolTables) {
47130                 visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
47131             }
47132             return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
47133             /**
47134              * @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)
47135              */
47136             function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) {
47137                 if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
47138                     return undefined;
47139                 }
47140                 var result = trySymbolTable(symbols, ignoreQualification);
47141                 visitedSymbolTables.pop();
47142                 return result;
47143             }
47144             function canQualifySymbol(symbolFromSymbolTable, meaning) {
47145                 // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
47146                 return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
47147                     // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
47148                     !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
47149             }
47150             function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
47151                 return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) &&
47152                     // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
47153                     // and if symbolFromSymbolTable or alias resolution matches the symbol,
47154                     // check the symbol can be qualified, it is only then this symbol is accessible
47155                     !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) &&
47156                     (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning));
47157             }
47158             function trySymbolTable(symbols, ignoreQualification) {
47159                 // If symbol is directly available by its name in the symbol table
47160                 if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) {
47161                     return [symbol];
47162                 }
47163                 // Check if symbol is any of the aliases in scope
47164                 var result = ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
47165                     if (symbolFromSymbolTable.flags & 2097152 /* Alias */
47166                         && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
47167                         && symbolFromSymbolTable.escapedName !== "default" /* Default */
47168                         && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
47169                         // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
47170                         && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))
47171                         // While exports are generally considered to be in scope, export-specifier declared symbols are _not_
47172                         // See similar comment in `resolveName` for details
47173                         && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */))) {
47174                         var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
47175                         var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification);
47176                         if (candidate) {
47177                             return candidate;
47178                         }
47179                     }
47180                     if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
47181                         if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) {
47182                             return [symbol];
47183                         }
47184                     }
47185                 });
47186                 // 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
47187                 return result || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : undefined);
47188             }
47189             function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) {
47190                 if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
47191                     return [symbolFromSymbolTable];
47192                 }
47193                 // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
47194                 // but only if the symbolFromSymbolTable can be qualified
47195                 var candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
47196                 var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true);
47197                 if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
47198                     return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
47199                 }
47200             }
47201         }
47202         function needsQualification(symbol, enclosingDeclaration, meaning) {
47203             var qualify = false;
47204             forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) {
47205                 // If symbol of this name is not available in the symbol table we are ok
47206                 var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
47207                 if (!symbolFromSymbolTable) {
47208                     // Continue to the next symbol table
47209                     return false;
47210                 }
47211                 // If the symbol with this name is present it should refer to the symbol
47212                 if (symbolFromSymbolTable === symbol) {
47213                     // No need to qualify
47214                     return true;
47215                 }
47216                 // Qualify if the symbol from symbol table has same meaning as expected
47217                 symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
47218                 if (symbolFromSymbolTable.flags & meaning) {
47219                     qualify = true;
47220                     return true;
47221                 }
47222                 // Continue to the next symbol table
47223                 return false;
47224             });
47225             return qualify;
47226         }
47227         function isPropertyOrMethodDeclarationSymbol(symbol) {
47228             if (symbol.declarations && symbol.declarations.length) {
47229                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
47230                     var declaration = _a[_i];
47231                     switch (declaration.kind) {
47232                         case 163 /* PropertyDeclaration */:
47233                         case 165 /* MethodDeclaration */:
47234                         case 167 /* GetAccessor */:
47235                         case 168 /* SetAccessor */:
47236                             continue;
47237                         default:
47238                             return false;
47239                     }
47240                 }
47241                 return true;
47242             }
47243             return false;
47244         }
47245         function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
47246             var access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, 788968 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false, /*allowModules*/ true);
47247             return access.accessibility === 0 /* Accessible */;
47248         }
47249         function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
47250             var access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, 111551 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false, /*allowModules*/ true);
47251             return access.accessibility === 0 /* Accessible */;
47252         }
47253         function isSymbolAccessibleByFlags(typeSymbol, enclosingDeclaration, flags) {
47254             var access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, flags, /*shouldComputeAliasesToMakeVisible*/ false, /*allowModules*/ false);
47255             return access.accessibility === 0 /* Accessible */;
47256         }
47257         function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
47258             if (!ts.length(symbols))
47259                 return;
47260             var hadAccessibleChain;
47261             var earlyModuleBail = false;
47262             for (var _i = 0, _a = symbols; _i < _a.length; _i++) {
47263                 var symbol = _a[_i];
47264                 // Symbol is accessible if it by itself is accessible
47265                 var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false);
47266                 if (accessibleSymbolChain) {
47267                     hadAccessibleChain = symbol;
47268                     var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
47269                     if (hasAccessibleDeclarations) {
47270                         return hasAccessibleDeclarations;
47271                     }
47272                 }
47273                 else if (allowModules) {
47274                     if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
47275                         if (shouldComputeAliasesToMakeVisible) {
47276                             earlyModuleBail = true;
47277                             // Generally speaking, we want to use the aliases that already exist to refer to a module, if present
47278                             // In order to do so, we need to find those aliases in order to retain them in declaration emit; so
47279                             // if we are in declaration emit, we cannot use the fast path for module visibility until we've exhausted
47280                             // all other visibility options (in order to capture the possible aliases used to reference the module)
47281                             continue;
47282                         }
47283                         // Any meaning of a module symbol is always accessible via an `import` type
47284                         return {
47285                             accessibility: 0 /* Accessible */
47286                         };
47287                     }
47288                 }
47289                 // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
47290                 // It could be a qualified symbol and hence verify the path
47291                 // e.g.:
47292                 // module m {
47293                 //     export class c {
47294                 //     }
47295                 // }
47296                 // const x: typeof m.c
47297                 // In the above example when we start with checking if typeof m.c symbol is accessible,
47298                 // we are going to see if c can be accessed in scope directly.
47299                 // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
47300                 // It is accessible if the parent m is accessible because then m.c can be accessed through qualification
47301                 var containers = getContainersOfSymbol(symbol, enclosingDeclaration, meaning);
47302                 var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible, allowModules);
47303                 if (parentResult) {
47304                     return parentResult;
47305                 }
47306             }
47307             if (earlyModuleBail) {
47308                 return {
47309                     accessibility: 0 /* Accessible */
47310                 };
47311             }
47312             if (hadAccessibleChain) {
47313                 return {
47314                     accessibility: 1 /* NotAccessible */,
47315                     errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
47316                     errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined,
47317                 };
47318             }
47319         }
47320         /**
47321          * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested
47322          *
47323          * @param symbol a Symbol to check if accessible
47324          * @param enclosingDeclaration a Node containing reference to the symbol
47325          * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible
47326          * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
47327          */
47328         function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
47329             return isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, /*allowModules*/ true);
47330         }
47331         function isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
47332             if (symbol && enclosingDeclaration) {
47333                 var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible, allowModules);
47334                 if (result) {
47335                     return result;
47336                 }
47337                 // This could be a symbol that is not exported in the external module
47338                 // or it could be a symbol from different external module that is not aliased and hence cannot be named
47339                 var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer);
47340                 if (symbolExternalModule) {
47341                     var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
47342                     if (symbolExternalModule !== enclosingExternalModule) {
47343                         // name from different external module that is not visible
47344                         return {
47345                             accessibility: 2 /* CannotBeNamed */,
47346                             errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
47347                             errorModuleName: symbolToString(symbolExternalModule),
47348                             errorNode: ts.isInJSFile(enclosingDeclaration) ? enclosingDeclaration : undefined,
47349                         };
47350                     }
47351                 }
47352                 // Just a local name that is not accessible
47353                 return {
47354                     accessibility: 1 /* NotAccessible */,
47355                     errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
47356                 };
47357             }
47358             return { accessibility: 0 /* Accessible */ };
47359         }
47360         function getExternalModuleContainer(declaration) {
47361             var node = ts.findAncestor(declaration, hasExternalModuleSymbol);
47362             return node && getSymbolOfNode(node);
47363         }
47364         function hasExternalModuleSymbol(declaration) {
47365             return ts.isAmbientModule(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
47366         }
47367         function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
47368             return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
47369         }
47370         function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
47371             var aliasesToMakeVisible;
47372             if (!ts.every(ts.filter(symbol.declarations, function (d) { return d.kind !== 78 /* Identifier */; }), getIsDeclarationVisible)) {
47373                 return undefined;
47374             }
47375             return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible };
47376             function getIsDeclarationVisible(declaration) {
47377                 var _a, _b;
47378                 if (!isDeclarationVisible(declaration)) {
47379                     // Mark the unexported alias as visible if its parent is visible
47380                     // because these kind of aliases can be used to name types in declaration file
47381                     var anyImportSyntax = getAnyImportSyntax(declaration);
47382                     if (anyImportSyntax &&
47383                         !ts.hasSyntacticModifier(anyImportSyntax, 1 /* Export */) && // import clause without export
47384                         isDeclarationVisible(anyImportSyntax.parent)) {
47385                         return addVisibleAlias(declaration, anyImportSyntax);
47386                     }
47387                     else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) &&
47388                         !ts.hasSyntacticModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement
47389                         isDeclarationVisible(declaration.parent.parent.parent)) {
47390                         return addVisibleAlias(declaration, declaration.parent.parent);
47391                     }
47392                     else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
47393                         && !ts.hasSyntacticModifier(declaration, 1 /* Export */)
47394                         && isDeclarationVisible(declaration.parent)) {
47395                         return addVisibleAlias(declaration, declaration);
47396                     }
47397                     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
47398                         && ts.isVariableDeclaration(declaration.parent.parent)
47399                         && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent)
47400                         && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* Export */)
47401                         && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file)
47402                         && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) {
47403                         return addVisibleAlias(declaration, declaration.parent.parent.parent.parent);
47404                     }
47405                     // Declaration is not visible
47406                     return false;
47407                 }
47408                 return true;
47409             }
47410             function addVisibleAlias(declaration, aliasingStatement) {
47411                 // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types,
47412                 // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time
47413                 // since we will do the emitting later in trackSymbol.
47414                 if (shouldComputeAliasToMakeVisible) {
47415                     getNodeLinks(declaration).isVisible = true;
47416                     aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement);
47417                 }
47418                 return true;
47419             }
47420         }
47421         function isEntityNameVisible(entityName, enclosingDeclaration) {
47422             // get symbol of the first identifier of the entityName
47423             var meaning;
47424             if (entityName.parent.kind === 176 /* TypeQuery */ ||
47425                 ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) ||
47426                 entityName.parent.kind === 158 /* ComputedPropertyName */) {
47427                 // Typeof value
47428                 meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
47429             }
47430             else if (entityName.kind === 157 /* QualifiedName */ || entityName.kind === 201 /* PropertyAccessExpression */ ||
47431                 entityName.parent.kind === 260 /* ImportEqualsDeclaration */) {
47432                 // Left identifier from type reference or TypeAlias
47433                 // Entity name of the import declaration
47434                 meaning = 1920 /* Namespace */;
47435             }
47436             else {
47437                 // Type Reference or TypeAlias entity = Identifier
47438                 meaning = 788968 /* Type */;
47439             }
47440             var firstIdentifier = ts.getFirstIdentifier(entityName);
47441             var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
47442             if (symbol && symbol.flags & 262144 /* TypeParameter */ && meaning & 788968 /* Type */) {
47443                 return { accessibility: 0 /* Accessible */ };
47444             }
47445             // Verify if the symbol is accessible
47446             return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || {
47447                 accessibility: 1 /* NotAccessible */,
47448                 errorSymbolName: ts.getTextOfNode(firstIdentifier),
47449                 errorNode: firstIdentifier
47450             };
47451         }
47452         function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
47453             if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
47454             var nodeFlags = 70221824 /* IgnoreErrors */;
47455             if (flags & 2 /* UseOnlyExternalAliasing */) {
47456                 nodeFlags |= 128 /* UseOnlyExternalAliasing */;
47457             }
47458             if (flags & 1 /* WriteTypeParametersOrArguments */) {
47459                 nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
47460             }
47461             if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
47462                 nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
47463             }
47464             if (flags & 16 /* DoNotIncludeSymbolChain */) {
47465                 nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
47466             }
47467             var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
47468             return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
47469             function symbolToStringWorker(writer) {
47470                 var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217
47471                 // add neverAsciiEscape for GH#39027
47472                 var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 297 /* SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true });
47473                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
47474                 printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer);
47475                 return writer;
47476             }
47477         }
47478         function signatureToString(signature, enclosingDeclaration, flags, kind, writer) {
47479             if (flags === void 0) { flags = 0 /* None */; }
47480             return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker);
47481             function signatureToStringWorker(writer) {
47482                 var sigOutput;
47483                 if (flags & 262144 /* WriteArrowStyleSignature */) {
47484                     sigOutput = kind === 1 /* Construct */ ? 175 /* ConstructorType */ : 174 /* FunctionType */;
47485                 }
47486                 else {
47487                     sigOutput = kind === 1 /* Construct */ ? 170 /* ConstructSignature */ : 169 /* CallSignature */;
47488                 }
47489                 var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
47490                 var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
47491                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
47492                 printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonDeferringWriter(writer)); // TODO: GH#18217
47493                 return writer;
47494             }
47495         }
47496         function typeToString(type, enclosingDeclaration, flags, writer) {
47497             if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
47498             if (writer === void 0) { writer = ts.createTextWriter(""); }
47499             var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
47500             var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
47501             if (typeNode === undefined)
47502                 return ts.Debug.fail("should always get typenode");
47503             var options = { removeComments: true };
47504             var printer = ts.createPrinter(options);
47505             var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
47506             printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer);
47507             var result = writer.getText();
47508             var maxLength = noTruncation ? ts.noTruncationMaximumTruncationLength * 2 : ts.defaultMaximumTruncationLength * 2;
47509             if (maxLength && result && result.length >= maxLength) {
47510                 return result.substr(0, maxLength - "...".length) + "...";
47511             }
47512             return result;
47513         }
47514         function getTypeNamesForErrorDisplay(left, right) {
47515             var leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left);
47516             var rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right);
47517             if (leftStr === rightStr) {
47518                 leftStr = getTypeNameForErrorDisplay(left);
47519                 rightStr = getTypeNameForErrorDisplay(right);
47520             }
47521             return [leftStr, rightStr];
47522         }
47523         function getTypeNameForErrorDisplay(type) {
47524             return typeToString(type, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
47525         }
47526         function symbolValueDeclarationIsContextSensitive(symbol) {
47527             return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration);
47528         }
47529         function toNodeBuilderFlags(flags) {
47530             if (flags === void 0) { flags = 0 /* None */; }
47531             return flags & 814775659 /* NodeBuilderFlagsMask */;
47532         }
47533         function isClassInstanceSide(type) {
47534             return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(ts.getObjectFlags(type) & 1073741824 /* IsClassInstanceClone */));
47535         }
47536         function createNodeBuilder() {
47537             return {
47538                 typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) {
47539                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); });
47540                 },
47541                 indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) {
47542                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context, /*typeNode*/ undefined); });
47543                 },
47544                 signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) {
47545                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); });
47546                 },
47547                 symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
47548                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); });
47549                 },
47550                 symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
47551                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); });
47552                 },
47553                 symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) {
47554                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); });
47555                 },
47556                 symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) {
47557                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); });
47558                 },
47559                 typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) {
47560                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); });
47561                 },
47562                 symbolTableToDeclarationStatements: function (symbolTable, enclosingDeclaration, flags, tracker, bundled) {
47563                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolTableToDeclarationStatements(symbolTable, context, bundled); });
47564                 },
47565             };
47566             function withContext(enclosingDeclaration, flags, tracker, cb) {
47567                 var _a, _b;
47568                 ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0);
47569                 var context = {
47570                     enclosingDeclaration: enclosingDeclaration,
47571                     flags: flags || 0 /* None */,
47572                     // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
47573                     tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
47574                             getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
47575                             getSourceFiles: function () { return host.getSourceFiles(); },
47576                             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
47577                             getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache),
47578                             useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames),
47579                             redirectTargetsMap: host.redirectTargetsMap,
47580                             getProjectReferenceRedirect: function (fileName) { return host.getProjectReferenceRedirect(fileName); },
47581                             isSourceOfProjectReferenceRedirect: function (fileName) { return host.isSourceOfProjectReferenceRedirect(fileName); },
47582                             fileExists: function (fileName) { return host.fileExists(fileName); },
47583                             getFileIncludeReasons: function () { return host.getFileIncludeReasons(); },
47584                         } : undefined },
47585                     encounteredError: false,
47586                     visitedTypes: undefined,
47587                     symbolDepth: undefined,
47588                     inferTypeParameters: undefined,
47589                     approximateLength: 0
47590                 };
47591                 var resultingNode = cb(context);
47592                 if (context.truncating && context.flags & 1 /* NoTruncation */) {
47593                     (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportTruncationError) === null || _b === void 0 ? void 0 : _b.call(_a);
47594                 }
47595                 return context.encounteredError ? undefined : resultingNode;
47596             }
47597             function checkTruncationLength(context) {
47598                 if (context.truncating)
47599                     return context.truncating;
47600                 return context.truncating = context.approximateLength > ((context.flags & 1 /* NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength);
47601             }
47602             function typeToTypeNodeHelper(type, context) {
47603                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
47604                     cancellationToken.throwIfCancellationRequested();
47605                 }
47606                 var inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
47607                 context.flags &= ~8388608 /* InTypeAlias */;
47608                 if (!type) {
47609                     if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
47610                         context.encounteredError = true;
47611                         return undefined; // TODO: GH#18217
47612                     }
47613                     context.approximateLength += 3;
47614                     return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
47615                 }
47616                 if (!(context.flags & 536870912 /* NoTypeReduction */)) {
47617                     type = getReducedType(type);
47618                 }
47619                 if (type.flags & 1 /* Any */) {
47620                     context.approximateLength += 3;
47621                     return ts.factory.createKeywordTypeNode(type === intrinsicMarkerType ? 136 /* IntrinsicKeyword */ : 128 /* AnyKeyword */);
47622                 }
47623                 if (type.flags & 2 /* Unknown */) {
47624                     return ts.factory.createKeywordTypeNode(152 /* UnknownKeyword */);
47625                 }
47626                 if (type.flags & 4 /* String */) {
47627                     context.approximateLength += 6;
47628                     return ts.factory.createKeywordTypeNode(147 /* StringKeyword */);
47629                 }
47630                 if (type.flags & 8 /* Number */) {
47631                     context.approximateLength += 6;
47632                     return ts.factory.createKeywordTypeNode(144 /* NumberKeyword */);
47633                 }
47634                 if (type.flags & 64 /* BigInt */) {
47635                     context.approximateLength += 6;
47636                     return ts.factory.createKeywordTypeNode(155 /* BigIntKeyword */);
47637                 }
47638                 if (type.flags & 16 /* Boolean */) {
47639                     context.approximateLength += 7;
47640                     return ts.factory.createKeywordTypeNode(131 /* BooleanKeyword */);
47641                 }
47642                 if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) {
47643                     var parentSymbol = getParentOfSymbol(type.symbol);
47644                     var parentName = symbolToTypeNode(parentSymbol, context, 788968 /* Type */);
47645                     if (getDeclaredTypeOfSymbol(parentSymbol) === type) {
47646                         return parentName;
47647                     }
47648                     var memberName = ts.symbolName(type.symbol);
47649                     if (ts.isIdentifierText(memberName, 0 /* ES3 */)) {
47650                         return appendReferenceToType(parentName, ts.factory.createTypeReferenceNode(memberName, /*typeArguments*/ undefined));
47651                     }
47652                     if (ts.isImportTypeNode(parentName)) {
47653                         parentName.isTypeOf = true; // mutably update, node is freshly manufactured anyhow
47654                         return ts.factory.createIndexedAccessTypeNode(parentName, ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(memberName)));
47655                     }
47656                     else if (ts.isTypeReferenceNode(parentName)) {
47657                         return ts.factory.createIndexedAccessTypeNode(ts.factory.createTypeQueryNode(parentName.typeName), ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(memberName)));
47658                     }
47659                     else {
47660                         return ts.Debug.fail("Unhandled type node kind returned from `symbolToTypeNode`.");
47661                     }
47662                 }
47663                 if (type.flags & 1056 /* EnumLike */) {
47664                     return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
47665                 }
47666                 if (type.flags & 128 /* StringLiteral */) {
47667                     context.approximateLength += (type.value.length + 2);
47668                     return ts.factory.createLiteralTypeNode(ts.setEmitFlags(ts.factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */));
47669                 }
47670                 if (type.flags & 256 /* NumberLiteral */) {
47671                     var value = type.value;
47672                     context.approximateLength += ("" + value).length;
47673                     return ts.factory.createLiteralTypeNode(value < 0 ? ts.factory.createPrefixUnaryExpression(40 /* MinusToken */, ts.factory.createNumericLiteral(-value)) : ts.factory.createNumericLiteral(value));
47674                 }
47675                 if (type.flags & 2048 /* BigIntLiteral */) {
47676                     context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1;
47677                     return ts.factory.createLiteralTypeNode((ts.factory.createBigIntLiteral(type.value)));
47678                 }
47679                 if (type.flags & 512 /* BooleanLiteral */) {
47680                     context.approximateLength += type.intrinsicName.length;
47681                     return ts.factory.createLiteralTypeNode(type.intrinsicName === "true" ? ts.factory.createTrue() : ts.factory.createFalse());
47682                 }
47683                 if (type.flags & 8192 /* UniqueESSymbol */) {
47684                     if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
47685                         if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
47686                             context.approximateLength += 6;
47687                             return symbolToTypeNode(type.symbol, context, 111551 /* Value */);
47688                         }
47689                         if (context.tracker.reportInaccessibleUniqueSymbolError) {
47690                             context.tracker.reportInaccessibleUniqueSymbolError();
47691                         }
47692                     }
47693                     context.approximateLength += 13;
47694                     return ts.factory.createTypeOperatorNode(151 /* UniqueKeyword */, ts.factory.createKeywordTypeNode(148 /* SymbolKeyword */));
47695                 }
47696                 if (type.flags & 16384 /* Void */) {
47697                     context.approximateLength += 4;
47698                     return ts.factory.createKeywordTypeNode(113 /* VoidKeyword */);
47699                 }
47700                 if (type.flags & 32768 /* Undefined */) {
47701                     context.approximateLength += 9;
47702                     return ts.factory.createKeywordTypeNode(150 /* UndefinedKeyword */);
47703                 }
47704                 if (type.flags & 65536 /* Null */) {
47705                     context.approximateLength += 4;
47706                     return ts.factory.createLiteralTypeNode(ts.factory.createNull());
47707                 }
47708                 if (type.flags & 131072 /* Never */) {
47709                     context.approximateLength += 5;
47710                     return ts.factory.createKeywordTypeNode(141 /* NeverKeyword */);
47711                 }
47712                 if (type.flags & 4096 /* ESSymbol */) {
47713                     context.approximateLength += 6;
47714                     return ts.factory.createKeywordTypeNode(148 /* SymbolKeyword */);
47715                 }
47716                 if (type.flags & 67108864 /* NonPrimitive */) {
47717                     context.approximateLength += 6;
47718                     return ts.factory.createKeywordTypeNode(145 /* ObjectKeyword */);
47719                 }
47720                 if (isThisTypeParameter(type)) {
47721                     if (context.flags & 4194304 /* InObjectTypeLiteral */) {
47722                         if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
47723                             context.encounteredError = true;
47724                         }
47725                         if (context.tracker.reportInaccessibleThisError) {
47726                             context.tracker.reportInaccessibleThisError();
47727                         }
47728                     }
47729                     context.approximateLength += 4;
47730                     return ts.factory.createThisTypeNode();
47731                 }
47732                 if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
47733                     var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
47734                     if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
47735                         return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""), typeArgumentNodes);
47736                     return symbolToTypeNode(type.aliasSymbol, context, 788968 /* Type */, typeArgumentNodes);
47737                 }
47738                 var objectFlags = ts.getObjectFlags(type);
47739                 if (objectFlags & 4 /* Reference */) {
47740                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
47741                     return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type);
47742                 }
47743                 if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
47744                     if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
47745                         context.approximateLength += (ts.symbolName(type.symbol).length + 6);
47746                         return ts.factory.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
47747                     }
47748                     if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
47749                         type.flags & 262144 /* TypeParameter */ &&
47750                         !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
47751                         var name = typeParameterToName(type, context);
47752                         context.approximateLength += ts.idText(name).length;
47753                         return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(ts.idText(name)), /*typeArguments*/ undefined);
47754                     }
47755                     // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
47756                     return type.symbol
47757                         ? symbolToTypeNode(type.symbol, context, 788968 /* Type */)
47758                         : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("?"), /*typeArguments*/ undefined);
47759                 }
47760                 if (type.flags & 1048576 /* Union */ && type.origin) {
47761                     type = type.origin;
47762                 }
47763                 if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
47764                     var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
47765                     if (ts.length(types) === 1) {
47766                         return typeToTypeNodeHelper(types[0], context);
47767                     }
47768                     var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true);
47769                     if (typeNodes && typeNodes.length > 0) {
47770                         return type.flags & 1048576 /* Union */ ? ts.factory.createUnionTypeNode(typeNodes) : ts.factory.createIntersectionTypeNode(typeNodes);
47771                     }
47772                     else {
47773                         if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
47774                             context.encounteredError = true;
47775                         }
47776                         return undefined; // TODO: GH#18217
47777                     }
47778                 }
47779                 if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
47780                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
47781                     // The type is an object literal type.
47782                     return createAnonymousTypeNode(type);
47783                 }
47784                 if (type.flags & 4194304 /* Index */) {
47785                     var indexedType = type.type;
47786                     context.approximateLength += 6;
47787                     var indexTypeNode = typeToTypeNodeHelper(indexedType, context);
47788                     return ts.factory.createTypeOperatorNode(138 /* KeyOfKeyword */, indexTypeNode);
47789                 }
47790                 if (type.flags & 134217728 /* TemplateLiteral */) {
47791                     var texts_1 = type.texts;
47792                     var types_1 = type.types;
47793                     var templateHead = ts.factory.createTemplateHead(texts_1[0]);
47794                     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])); }));
47795                     context.approximateLength += 2;
47796                     return ts.factory.createTemplateLiteralType(templateHead, templateSpans);
47797                 }
47798                 if (type.flags & 268435456 /* StringMapping */) {
47799                     var typeNode = typeToTypeNodeHelper(type.type, context);
47800                     return symbolToTypeNode(type.symbol, context, 788968 /* Type */, [typeNode]);
47801                 }
47802                 if (type.flags & 8388608 /* IndexedAccess */) {
47803                     var objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
47804                     var indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
47805                     context.approximateLength += 2;
47806                     return ts.factory.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
47807                 }
47808                 if (type.flags & 16777216 /* Conditional */) {
47809                     var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
47810                     var saveInferTypeParameters = context.inferTypeParameters;
47811                     context.inferTypeParameters = type.root.inferTypeParameters;
47812                     var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
47813                     context.inferTypeParameters = saveInferTypeParameters;
47814                     var trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type));
47815                     var falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type));
47816                     context.approximateLength += 15;
47817                     return ts.factory.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
47818                 }
47819                 if (type.flags & 33554432 /* Substitution */) {
47820                     return typeToTypeNodeHelper(type.baseType, context);
47821                 }
47822                 return ts.Debug.fail("Should be unreachable.");
47823                 function typeToTypeNodeOrCircularityElision(type) {
47824                     var _a, _b, _c;
47825                     if (type.flags & 1048576 /* Union */) {
47826                         if ((_a = context.visitedTypes) === null || _a === void 0 ? void 0 : _a.has(getTypeId(type))) {
47827                             if (!(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
47828                                 context.encounteredError = true;
47829                                 (_c = (_b = context.tracker) === null || _b === void 0 ? void 0 : _b.reportCyclicStructureError) === null || _c === void 0 ? void 0 : _c.call(_b);
47830                             }
47831                             return createElidedInformationPlaceholder(context);
47832                         }
47833                         return visitAndTransformType(type, function (type) { return typeToTypeNodeHelper(type, context); });
47834                     }
47835                     return typeToTypeNodeHelper(type, context);
47836                 }
47837                 function createMappedTypeNodeFromType(type) {
47838                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
47839                     var readonlyToken = type.declaration.readonlyToken ? ts.factory.createToken(type.declaration.readonlyToken.kind) : undefined;
47840                     var questionToken = type.declaration.questionToken ? ts.factory.createToken(type.declaration.questionToken.kind) : undefined;
47841                     var appropriateConstraintTypeNode;
47842                     if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
47843                         // We have a { [P in keyof T]: X }
47844                         // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
47845                         appropriateConstraintTypeNode = ts.factory.createTypeOperatorNode(138 /* KeyOfKeyword */, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
47846                     }
47847                     else {
47848                         appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
47849                     }
47850                     var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
47851                     var nameTypeNode = type.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type), context) : undefined;
47852                     var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
47853                     var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode);
47854                     context.approximateLength += 10;
47855                     return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
47856                 }
47857                 function createAnonymousTypeNode(type) {
47858                     var _a;
47859                     var typeId = type.id;
47860                     var symbol = type.symbol;
47861                     if (symbol) {
47862                         var isInstanceType = isClassInstanceSide(type) ? 788968 /* Type */ : 111551 /* Value */;
47863                         if (isJSConstructor(symbol.valueDeclaration)) {
47864                             // Instance and static types share the same symbol; only add 'typeof' for the static side.
47865                             return symbolToTypeNode(symbol, context, isInstanceType);
47866                         }
47867                         // Always use 'typeof T' for type of class, enum, and module objects
47868                         else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 221 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) ||
47869                             symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
47870                             shouldWriteTypeOfFunctionSymbol()) {
47871                             return symbolToTypeNode(symbol, context, isInstanceType);
47872                         }
47873                         else if ((_a = context.visitedTypes) === null || _a === void 0 ? void 0 : _a.has(typeId)) {
47874                             // If type is an anonymous type literal in a type alias declaration, use type alias name
47875                             var typeAlias = getTypeAliasForTypeLiteral(type);
47876                             if (typeAlias) {
47877                                 // The specified symbol flags need to be reinterpreted as type flags
47878                                 return symbolToTypeNode(typeAlias, context, 788968 /* Type */);
47879                             }
47880                             else {
47881                                 return createElidedInformationPlaceholder(context);
47882                             }
47883                         }
47884                         else {
47885                             return visitAndTransformType(type, createTypeNodeFromObjectType);
47886                         }
47887                     }
47888                     else {
47889                         // Anonymous types without a symbol are never circular.
47890                         return createTypeNodeFromObjectType(type);
47891                     }
47892                     function shouldWriteTypeOfFunctionSymbol() {
47893                         var _a;
47894                         var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
47895                             ts.some(symbol.declarations, function (declaration) { return ts.hasSyntacticModifier(declaration, 32 /* Static */); });
47896                         var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
47897                             (symbol.parent || // is exported function symbol
47898                                 ts.forEach(symbol.declarations, function (declaration) {
47899                                     return declaration.parent.kind === 297 /* SourceFile */ || declaration.parent.kind === 257 /* ModuleBlock */;
47900                                 }));
47901                         if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
47902                             // typeof is allowed only for static/non local functions
47903                             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
47904                                 (!(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
47905                         }
47906                     }
47907                 }
47908                 function visitAndTransformType(type, transform) {
47909                     var typeId = type.id;
47910                     var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
47911                     var id = ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? "N" + getNodeId(type.node) :
47912                         type.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type.symbol) :
47913                             undefined;
47914                     // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
47915                     // of types allows us to catch circular references to instantiations of the same anonymous type
47916                     if (!context.visitedTypes) {
47917                         context.visitedTypes = new ts.Set();
47918                     }
47919                     if (id && !context.symbolDepth) {
47920                         context.symbolDepth = new ts.Map();
47921                     }
47922                     var depth;
47923                     if (id) {
47924                         depth = context.symbolDepth.get(id) || 0;
47925                         if (depth > 10) {
47926                             return createElidedInformationPlaceholder(context);
47927                         }
47928                         context.symbolDepth.set(id, depth + 1);
47929                     }
47930                     context.visitedTypes.add(typeId);
47931                     var result = transform(type);
47932                     context.visitedTypes.delete(typeId);
47933                     if (id) {
47934                         context.symbolDepth.set(id, depth);
47935                     }
47936                     return result;
47937                 }
47938                 function createTypeNodeFromObjectType(type) {
47939                     if (isGenericMappedType(type) || type.containsError) {
47940                         return createMappedTypeNodeFromType(type);
47941                     }
47942                     var resolved = resolveStructuredTypeMembers(type);
47943                     if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
47944                         if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
47945                             context.approximateLength += 2;
47946                             return ts.setEmitFlags(ts.factory.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */);
47947                         }
47948                         if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
47949                             var signature = resolved.callSignatures[0];
47950                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 174 /* FunctionType */, context);
47951                             return signatureNode;
47952                         }
47953                         if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
47954                             var signature = resolved.constructSignatures[0];
47955                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 175 /* ConstructorType */, context);
47956                             return signatureNode;
47957                         }
47958                     }
47959                     var abstractSignatures = ts.filter(resolved.constructSignatures, function (signature) { return !!(signature.flags & 4 /* Abstract */); });
47960                     if (ts.some(abstractSignatures)) {
47961                         var types = ts.map(abstractSignatures, getOrCreateTypeFromSignature);
47962                         // count the number of type elements excluding abstract constructors
47963                         var typeElementCount = resolved.callSignatures.length +
47964                             (resolved.constructSignatures.length - abstractSignatures.length) +
47965                             (resolved.stringIndexInfo ? 1 : 0) +
47966                             (resolved.numberIndexInfo ? 1 : 0) +
47967                             // exclude `prototype` when writing a class expression as a type literal, as per
47968                             // the logic in `createTypeNodesFromResolvedType`.
47969                             (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ ?
47970                                 ts.countWhere(resolved.properties, function (p) { return !(p.flags & 4194304 /* Prototype */); }) :
47971                                 ts.length(resolved.properties));
47972                         // don't include an empty object literal if there were no other static-side
47973                         // properties to write, i.e. `abstract class C { }` becomes `abstract new () => {}`
47974                         // and not `(abstract new () => {}) & {}`
47975                         if (typeElementCount) {
47976                             // create a copy of the object type without any abstract construct signatures.
47977                             types.push(getResolvedTypeWithoutAbstractConstructSignatures(resolved));
47978                         }
47979                         return typeToTypeNodeHelper(getIntersectionType(types), context);
47980                     }
47981                     var savedFlags = context.flags;
47982                     context.flags |= 4194304 /* InObjectTypeLiteral */;
47983                     var members = createTypeNodesFromResolvedType(resolved);
47984                     context.flags = savedFlags;
47985                     var typeLiteralNode = ts.factory.createTypeLiteralNode(members);
47986                     context.approximateLength += 2;
47987                     ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
47988                     return typeLiteralNode;
47989                 }
47990                 function typeReferenceToTypeNode(type) {
47991                     var typeArguments = getTypeArguments(type);
47992                     if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
47993                         if (context.flags & 2 /* WriteArrayAsGenericType */) {
47994                             var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
47995                             return ts.factory.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
47996                         }
47997                         var elementType = typeToTypeNodeHelper(typeArguments[0], context);
47998                         var arrayType = ts.factory.createArrayTypeNode(elementType);
47999                         return type.target === globalArrayType ? arrayType : ts.factory.createTypeOperatorNode(142 /* ReadonlyKeyword */, arrayType);
48000                     }
48001                     else if (type.target.objectFlags & 8 /* Tuple */) {
48002                         if (typeArguments.length > 0) {
48003                             var arity = getTypeReferenceArity(type);
48004                             var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
48005                             if (tupleConstituentNodes) {
48006                                 if (type.target.labeledElementDeclarations) {
48007                                     for (var i = 0; i < tupleConstituentNodes.length; i++) {
48008                                         var flags = type.target.elementFlags[i];
48009                                         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]) :
48010                                             tupleConstituentNodes[i]);
48011                                     }
48012                                 }
48013                                 else {
48014                                     for (var i = 0; i < Math.min(arity, tupleConstituentNodes.length); i++) {
48015                                         var flags = type.target.elementFlags[i];
48016                                         tupleConstituentNodes[i] =
48017                                             flags & 12 /* Variable */ ? ts.factory.createRestTypeNode(flags & 4 /* Rest */ ? ts.factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]) :
48018                                                 flags & 2 /* Optional */ ? ts.factory.createOptionalTypeNode(tupleConstituentNodes[i]) :
48019                                                     tupleConstituentNodes[i];
48020                                     }
48021                                 }
48022                                 var tupleTypeNode = ts.setEmitFlags(ts.factory.createTupleTypeNode(tupleConstituentNodes), 1 /* SingleLine */);
48023                                 return type.target.readonly ? ts.factory.createTypeOperatorNode(142 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
48024                             }
48025                         }
48026                         if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
48027                             var tupleTypeNode = ts.setEmitFlags(ts.factory.createTupleTypeNode([]), 1 /* SingleLine */);
48028                             return type.target.readonly ? ts.factory.createTypeOperatorNode(142 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
48029                         }
48030                         context.encounteredError = true;
48031                         return undefined; // TODO: GH#18217
48032                     }
48033                     else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ &&
48034                         type.symbol.valueDeclaration &&
48035                         ts.isClassLike(type.symbol.valueDeclaration) &&
48036                         !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
48037                         return createAnonymousTypeNode(type);
48038                     }
48039                     else {
48040                         var outerTypeParameters = type.target.outerTypeParameters;
48041                         var i = 0;
48042                         var resultType = void 0;
48043                         if (outerTypeParameters) {
48044                             var length_2 = outerTypeParameters.length;
48045                             while (i < length_2) {
48046                                 // Find group of type arguments for type parameters with the same declaring container.
48047                                 var start = i;
48048                                 var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
48049                                 do {
48050                                     i++;
48051                                 } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
48052                                 // When type parameters are their own type arguments for the whole group (i.e. we have
48053                                 // the default outer type arguments), we don't show the group.
48054                                 if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
48055                                     var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
48056                                     var flags_3 = context.flags;
48057                                     context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
48058                                     var ref = symbolToTypeNode(parent, context, 788968 /* Type */, typeArgumentSlice);
48059                                     context.flags = flags_3;
48060                                     resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
48061                                 }
48062                             }
48063                         }
48064                         var typeArgumentNodes = void 0;
48065                         if (typeArguments.length > 0) {
48066                             var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
48067                             typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
48068                         }
48069                         var flags = context.flags;
48070                         context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
48071                         var finalRef = symbolToTypeNode(type.symbol, context, 788968 /* Type */, typeArgumentNodes);
48072                         context.flags = flags;
48073                         return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
48074                     }
48075                 }
48076                 function appendReferenceToType(root, ref) {
48077                     if (ts.isImportTypeNode(root)) {
48078                         // first shift type arguments
48079                         var typeArguments = root.typeArguments;
48080                         var qualifier = root.qualifier;
48081                         if (qualifier) {
48082                             if (ts.isIdentifier(qualifier)) {
48083                                 qualifier = ts.factory.updateIdentifier(qualifier, typeArguments);
48084                             }
48085                             else {
48086                                 qualifier = ts.factory.updateQualifiedName(qualifier, qualifier.left, ts.factory.updateIdentifier(qualifier.right, typeArguments));
48087                             }
48088                         }
48089                         typeArguments = ref.typeArguments;
48090                         // then move qualifiers
48091                         var ids = getAccessStack(ref);
48092                         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
48093                             var id = ids_1[_i];
48094                             qualifier = qualifier ? ts.factory.createQualifiedName(qualifier, id) : id;
48095                         }
48096                         return ts.factory.updateImportTypeNode(root, root.argument, qualifier, typeArguments, root.isTypeOf);
48097                     }
48098                     else {
48099                         // first shift type arguments
48100                         var typeArguments = root.typeArguments;
48101                         var typeName = root.typeName;
48102                         if (ts.isIdentifier(typeName)) {
48103                             typeName = ts.factory.updateIdentifier(typeName, typeArguments);
48104                         }
48105                         else {
48106                             typeName = ts.factory.updateQualifiedName(typeName, typeName.left, ts.factory.updateIdentifier(typeName.right, typeArguments));
48107                         }
48108                         typeArguments = ref.typeArguments;
48109                         // then move qualifiers
48110                         var ids = getAccessStack(ref);
48111                         for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
48112                             var id = ids_2[_a];
48113                             typeName = ts.factory.createQualifiedName(typeName, id);
48114                         }
48115                         return ts.factory.updateTypeReferenceNode(root, typeName, typeArguments);
48116                     }
48117                 }
48118                 function getAccessStack(ref) {
48119                     var state = ref.typeName;
48120                     var ids = [];
48121                     while (!ts.isIdentifier(state)) {
48122                         ids.unshift(state.right);
48123                         state = state.left;
48124                     }
48125                     ids.unshift(state);
48126                     return ids;
48127                 }
48128                 function createTypeNodesFromResolvedType(resolvedType) {
48129                     if (checkTruncationLength(context)) {
48130                         return [ts.factory.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined)];
48131                     }
48132                     var typeElements = [];
48133                     for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) {
48134                         var signature = _a[_i];
48135                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 169 /* CallSignature */, context));
48136                     }
48137                     for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
48138                         var signature = _c[_b];
48139                         if (signature.flags & 4 /* Abstract */)
48140                             continue;
48141                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 170 /* ConstructSignature */, context));
48142                     }
48143                     if (resolvedType.stringIndexInfo) {
48144                         var indexSignature = void 0;
48145                         if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
48146                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context, createElidedInformationPlaceholder(context));
48147                         }
48148                         else {
48149                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context, /*typeNode*/ undefined);
48150                         }
48151                         typeElements.push(indexSignature);
48152                     }
48153                     if (resolvedType.numberIndexInfo) {
48154                         typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context, /*typeNode*/ undefined));
48155                     }
48156                     var properties = resolvedType.properties;
48157                     if (!properties) {
48158                         return typeElements;
48159                     }
48160                     var i = 0;
48161                     for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) {
48162                         var propertySymbol = properties_1[_d];
48163                         i++;
48164                         if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
48165                             if (propertySymbol.flags & 4194304 /* Prototype */) {
48166                                 continue;
48167                             }
48168                             if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
48169                                 context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName));
48170                             }
48171                         }
48172                         if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) {
48173                             typeElements.push(ts.factory.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined));
48174                             addPropertyToElementList(properties[properties.length - 1], context, typeElements);
48175                             break;
48176                         }
48177                         addPropertyToElementList(propertySymbol, context, typeElements);
48178                     }
48179                     return typeElements.length ? typeElements : undefined;
48180                 }
48181             }
48182             function createElidedInformationPlaceholder(context) {
48183                 context.approximateLength += 3;
48184                 if (!(context.flags & 1 /* NoTruncation */)) {
48185                     return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("..."), /*typeArguments*/ undefined);
48186                 }
48187                 return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
48188             }
48189             function addPropertyToElementList(propertySymbol, context, typeElements) {
48190                 var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */);
48191                 var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
48192                     anyType : getTypeOfSymbol(propertySymbol);
48193                 var saveEnclosingDeclaration = context.enclosingDeclaration;
48194                 context.enclosingDeclaration = undefined;
48195                 if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */ && isLateBoundName(propertySymbol.escapedName)) {
48196                     var decl = ts.first(propertySymbol.declarations);
48197                     if (hasLateBindableName(decl)) {
48198                         if (ts.isBinaryExpression(decl)) {
48199                             var name = ts.getNameOfDeclaration(decl);
48200                             if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) {
48201                                 trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context);
48202                             }
48203                         }
48204                         else {
48205                             trackComputedName(decl.name.expression, saveEnclosingDeclaration, context);
48206                         }
48207                     }
48208                 }
48209                 context.enclosingDeclaration = saveEnclosingDeclaration;
48210                 var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context);
48211                 context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
48212                 var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined;
48213                 if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
48214                     var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */);
48215                     for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
48216                         var signature = signatures_1[_i];
48217                         var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 164 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken });
48218                         typeElements.push(preserveCommentsOn(methodDeclaration));
48219                     }
48220                 }
48221                 else {
48222                     var savedFlags = context.flags;
48223                     context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
48224                     var propertyTypeNode = void 0;
48225                     if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
48226                         propertyTypeNode = createElidedInformationPlaceholder(context);
48227                     }
48228                     else {
48229                         propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
48230                     }
48231                     context.flags = savedFlags;
48232                     var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined;
48233                     if (modifiers) {
48234                         context.approximateLength += 9;
48235                     }
48236                     var propertySignature = ts.factory.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode);
48237                     typeElements.push(preserveCommentsOn(propertySignature));
48238                 }
48239                 function preserveCommentsOn(node) {
48240                     if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; })) {
48241                         var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; });
48242                         var commentText = d.comment;
48243                         if (commentText) {
48244                             ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]);
48245                         }
48246                     }
48247                     else if (propertySymbol.valueDeclaration) {
48248                         // Copy comments to node for declaration emit
48249                         ts.setCommentRange(node, propertySymbol.valueDeclaration);
48250                     }
48251                     return node;
48252                 }
48253             }
48254             function mapToTypeNodes(types, context, isBareList) {
48255                 if (ts.some(types)) {
48256                     if (checkTruncationLength(context)) {
48257                         if (!isBareList) {
48258                             return [ts.factory.createTypeReferenceNode("...", /*typeArguments*/ undefined)];
48259                         }
48260                         else if (types.length > 2) {
48261                             return [
48262                                 typeToTypeNodeHelper(types[0], context),
48263                                 ts.factory.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined),
48264                                 typeToTypeNodeHelper(types[types.length - 1], context)
48265                             ];
48266                         }
48267                     }
48268                     var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */);
48269                     /** Map from type reference identifier text to [type, index in `result` where the type node is] */
48270                     var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined;
48271                     var result_4 = [];
48272                     var i = 0;
48273                     for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
48274                         var type = types_2[_i];
48275                         i++;
48276                         if (checkTruncationLength(context) && (i + 2 < types.length - 1)) {
48277                             result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined));
48278                             var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context);
48279                             if (typeNode_1) {
48280                                 result_4.push(typeNode_1);
48281                             }
48282                             break;
48283                         }
48284                         context.approximateLength += 2; // Account for whitespace + separator
48285                         var typeNode = typeToTypeNodeHelper(type, context);
48286                         if (typeNode) {
48287                             result_4.push(typeNode);
48288                             if (seenNames && ts.isIdentifierTypeReference(typeNode)) {
48289                                 seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]);
48290                             }
48291                         }
48292                     }
48293                     if (seenNames) {
48294                         // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where
48295                         // occurrences of the same name actually come from different
48296                         // namespaces, go through the single-identifier type reference nodes
48297                         // we just generated, and see if any names were generated more than
48298                         // once while referring to different types. If so, regenerate the
48299                         // type node for each entry by that name with the
48300                         // `UseFullyQualifiedType` flag enabled.
48301                         var saveContextFlags = context.flags;
48302                         context.flags |= 64 /* UseFullyQualifiedType */;
48303                         seenNames.forEach(function (types) {
48304                             if (!ts.arrayIsHomogeneous(types, function (_a, _b) {
48305                                 var a = _a[0];
48306                                 var b = _b[0];
48307                                 return typesAreSameReference(a, b);
48308                             })) {
48309                                 for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
48310                                     var _a = types_3[_i], type = _a[0], resultIndex = _a[1];
48311                                     result_4[resultIndex] = typeToTypeNodeHelper(type, context);
48312                                 }
48313                             }
48314                         });
48315                         context.flags = saveContextFlags;
48316                     }
48317                     return result_4;
48318                 }
48319             }
48320             function typesAreSameReference(a, b) {
48321                 return a === b
48322                     || !!a.symbol && a.symbol === b.symbol
48323                     || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol;
48324             }
48325             function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context, typeNode) {
48326                 var name = ts.getNameFromIndexInfo(indexInfo) || "x";
48327                 var indexerTypeNode = ts.factory.createKeywordTypeNode(kind === 0 /* String */ ? 147 /* StringKeyword */ : 144 /* NumberKeyword */);
48328                 var indexingParameter = ts.factory.createParameterDeclaration(
48329                 /*decorators*/ undefined, 
48330                 /*modifiers*/ undefined, 
48331                 /*dotDotDotToken*/ undefined, name, 
48332                 /*questionToken*/ undefined, indexerTypeNode, 
48333                 /*initializer*/ undefined);
48334                 if (!typeNode) {
48335                     typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
48336                 }
48337                 if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
48338                     context.encounteredError = true;
48339                 }
48340                 context.approximateLength += (name.length + 4);
48341                 return ts.factory.createIndexSignature(
48342                 /*decorators*/ undefined, indexInfo.isReadonly ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode);
48343             }
48344             function signatureToSignatureDeclarationHelper(signature, kind, context, options) {
48345                 var _a, _b, _c, _d;
48346                 var suppressAny = context.flags & 256 /* SuppressAnyReturnType */;
48347                 if (suppressAny)
48348                     context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s
48349                 var typeParameters;
48350                 var typeArguments;
48351                 if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
48352                     typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); });
48353                 }
48354                 else {
48355                     typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); });
48356                 }
48357                 var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0];
48358                 // If the expanded parameter list had a variadic in a non-trailing position, don't expand it
48359                 var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 166 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); });
48360                 if (signature.thisParameter) {
48361                     var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context);
48362                     parameters.unshift(thisParameter);
48363                 }
48364                 var returnTypeNode;
48365                 var typePredicate = getTypePredicateOfSignature(signature);
48366                 if (typePredicate) {
48367                     var assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
48368                         ts.factory.createToken(127 /* AssertsKeyword */) :
48369                         undefined;
48370                     var parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
48371                         ts.setEmitFlags(ts.factory.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) :
48372                         ts.factory.createThisTypeNode();
48373                     var typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
48374                     returnTypeNode = ts.factory.createTypePredicateNode(assertsModifier, parameterName, typeNode);
48375                 }
48376                 else {
48377                     var returnType = getReturnTypeOfSignature(signature);
48378                     if (returnType && !(suppressAny && isTypeAny(returnType))) {
48379                         returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports);
48380                     }
48381                     else if (!suppressAny) {
48382                         returnTypeNode = ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
48383                     }
48384                 }
48385                 var modifiers = options === null || options === void 0 ? void 0 : options.modifiers;
48386                 if ((kind === 175 /* ConstructorType */) && signature.flags & 4 /* Abstract */) {
48387                     var flags = ts.modifiersToFlags(modifiers);
48388                     modifiers = ts.factory.createModifiersFromModifierFlags(flags | 128 /* Abstract */);
48389                 }
48390                 context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum
48391                 var node = kind === 169 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) :
48392                     kind === 170 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) :
48393                         kind === 164 /* 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) :
48394                             kind === 165 /* 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) :
48395                                 kind === 166 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, modifiers, parameters, /*body*/ undefined) :
48396                                     kind === 167 /* 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) :
48397                                         kind === 168 /* 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) :
48398                                             kind === 171 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, modifiers, parameters, returnTypeNode) :
48399                                                 kind === 308 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) :
48400                                                     kind === 174 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) :
48401                                                         kind === 175 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(modifiers, typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) :
48402                                                             kind === 251 /* 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) :
48403                                                                 kind === 208 /* 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([])) :
48404                                                                     kind === 209 /* ArrowFunction */ ? ts.factory.createArrowFunction(modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) :
48405                                                                         ts.Debug.assertNever(kind);
48406                 if (typeArguments) {
48407                     node.typeArguments = ts.factory.createNodeArray(typeArguments);
48408                 }
48409                 return node;
48410             }
48411             function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
48412                 var savedContextFlags = context.flags;
48413                 context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
48414                 var name = typeParameterToName(type, context);
48415                 var defaultParameter = getDefaultFromTypeParameter(type);
48416                 var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
48417                 context.flags = savedContextFlags;
48418                 return ts.factory.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
48419             }
48420             function typeParameterToDeclaration(type, context, constraint) {
48421                 if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); }
48422                 var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
48423                 return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
48424             }
48425             function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) {
48426                 var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 160 /* Parameter */);
48427                 if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) {
48428                     parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 326 /* JSDocParameterTag */);
48429                 }
48430                 var parameterType = getTypeOfSymbol(parameterSymbol);
48431                 if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
48432                     parameterType = getOptionalType(parameterType);
48433                 }
48434                 if ((context.flags & 1073741824 /* NoUndefinedOptionalParameterType */) && parameterDeclaration && !ts.isJSDocParameterTag(parameterDeclaration) && isOptionalUninitializedParameter(parameterDeclaration)) {
48435                     parameterType = getTypeWithFacts(parameterType, 524288 /* NEUndefined */);
48436                 }
48437                 var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports);
48438                 var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.factory.cloneNode) : undefined;
48439                 var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */;
48440                 var dotDotDotToken = isRest ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined;
48441                 var name = parameterDeclaration ? parameterDeclaration.name ?
48442                     parameterDeclaration.name.kind === 78 /* Identifier */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
48443                         parameterDeclaration.name.kind === 157 /* QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
48444                             cloneBindingName(parameterDeclaration.name) :
48445                     ts.symbolName(parameterSymbol) :
48446                     ts.symbolName(parameterSymbol);
48447                 var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */;
48448                 var questionToken = isOptional ? ts.factory.createToken(57 /* QuestionToken */) : undefined;
48449                 var parameterNode = ts.factory.createParameterDeclaration(
48450                 /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, 
48451                 /*initializer*/ undefined);
48452                 context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
48453                 return parameterNode;
48454                 function cloneBindingName(node) {
48455                     return elideInitializerAndSetEmitFlags(node);
48456                     function elideInitializerAndSetEmitFlags(node) {
48457                         if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
48458                             trackComputedName(node.expression, context.enclosingDeclaration, context);
48459                         }
48460                         var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
48461                         if (ts.isBindingElement(visited)) {
48462                             visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, 
48463                             /*initializer*/ undefined);
48464                         }
48465                         if (!ts.nodeIsSynthesized(visited)) {
48466                             visited = ts.factory.cloneNode(visited);
48467                         }
48468                         return ts.setEmitFlags(visited, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
48469                     }
48470                 }
48471             }
48472             function trackComputedName(accessExpression, enclosingDeclaration, context) {
48473                 if (!context.tracker.trackSymbol)
48474                     return;
48475                 // get symbol of the first identifier of the entityName
48476                 var firstIdentifier = ts.getFirstIdentifier(accessExpression);
48477                 var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
48478                 if (name) {
48479                     context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */);
48480                 }
48481             }
48482             function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
48483                 context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217
48484                 return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol);
48485             }
48486             function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) {
48487                 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
48488                 var chain;
48489                 var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
48490                 if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
48491                     chain = ts.Debug.checkDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
48492                     ts.Debug.assert(chain && chain.length > 0);
48493                 }
48494                 else {
48495                     chain = [symbol];
48496                 }
48497                 return chain;
48498                 /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
48499                 function getSymbolChain(symbol, meaning, endOfChain) {
48500                     var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
48501                     var parentSpecifiers;
48502                     if (!accessibleSymbolChain ||
48503                         needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
48504                         // Go up and add our parent.
48505                         var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration, meaning);
48506                         if (ts.length(parents_1)) {
48507                             parentSpecifiers = parents_1.map(function (symbol) {
48508                                 return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
48509                                     ? getSpecifierForModuleSymbol(symbol, context)
48510                                     : undefined;
48511                             });
48512                             var indices = parents_1.map(function (_, i) { return i; });
48513                             indices.sort(sortByBestName);
48514                             var sortedParents = indices.map(function (i) { return parents_1[i]; });
48515                             for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
48516                                 var parent = sortedParents_1[_i];
48517                                 var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
48518                                 if (parentChain) {
48519                                     if (parent.exports && parent.exports.get("export=" /* ExportEquals */) &&
48520                                         getSymbolIfSameReference(parent.exports.get("export=" /* ExportEquals */), symbol)) {
48521                                         // parentChain root _is_ symbol - symbol is a module export=, so it kinda looks like it's own parent
48522                                         // No need to lookup an alias for the symbol in itself
48523                                         accessibleSymbolChain = parentChain;
48524                                         break;
48525                                     }
48526                                     accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
48527                                     break;
48528                                 }
48529                             }
48530                         }
48531                     }
48532                     if (accessibleSymbolChain) {
48533                         return accessibleSymbolChain;
48534                     }
48535                     if (
48536                     // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
48537                     endOfChain ||
48538                         // If a parent symbol is an anonymous type, don't write it.
48539                         !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
48540                         // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
48541                         if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
48542                             return;
48543                         }
48544                         return [symbol];
48545                     }
48546                     function sortByBestName(a, b) {
48547                         var specifierA = parentSpecifiers[a];
48548                         var specifierB = parentSpecifiers[b];
48549                         if (specifierA && specifierB) {
48550                             var isBRelative = ts.pathIsRelative(specifierB);
48551                             if (ts.pathIsRelative(specifierA) === isBRelative) {
48552                                 // Both relative or both non-relative, sort by number of parts
48553                                 return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
48554                             }
48555                             if (isBRelative) {
48556                                 // A is non-relative, B is relative: prefer A
48557                                 return -1;
48558                             }
48559                             // A is relative, B is non-relative: prefer B
48560                             return 1;
48561                         }
48562                         return 0;
48563                     }
48564                 }
48565             }
48566             function typeParametersToTypeParameterDeclarations(symbol, context) {
48567                 var typeParameterNodes;
48568                 var targetSymbol = getTargetSymbol(symbol);
48569                 if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
48570                     typeParameterNodes = ts.factory.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); }));
48571                 }
48572                 return typeParameterNodes;
48573             }
48574             function lookupTypeParameterNodes(chain, index, context) {
48575                 var _a;
48576                 ts.Debug.assert(chain && 0 <= index && index < chain.length);
48577                 var symbol = chain[index];
48578                 var symbolId = getSymbolId(symbol);
48579                 if ((_a = context.typeParameterSymbolList) === null || _a === void 0 ? void 0 : _a.has(symbolId)) {
48580                     return undefined;
48581                 }
48582                 (context.typeParameterSymbolList || (context.typeParameterSymbolList = new ts.Set())).add(symbolId);
48583                 var typeParameterNodes;
48584                 if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) {
48585                     var parentSymbol = symbol;
48586                     var nextSymbol_1 = chain[index + 1];
48587                     if (ts.getCheckFlags(nextSymbol_1) & 1 /* Instantiated */) {
48588                         var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol);
48589                         typeParameterNodes = mapToTypeNodes(ts.map(params, function (t) { return getMappedType(t, nextSymbol_1.mapper); }), context);
48590                     }
48591                     else {
48592                         typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
48593                     }
48594                 }
48595                 return typeParameterNodes;
48596             }
48597             /**
48598              * Given A[B][C][D], finds A[B]
48599              */
48600             function getTopmostIndexedAccessType(top) {
48601                 if (ts.isIndexedAccessTypeNode(top.objectType)) {
48602                     return getTopmostIndexedAccessType(top.objectType);
48603                 }
48604                 return top;
48605             }
48606             function getSpecifierForModuleSymbol(symbol, context) {
48607                 var _a;
48608                 var file = ts.getDeclarationOfKind(symbol, 297 /* SourceFile */);
48609                 if (!file) {
48610                     var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); });
48611                     if (equivalentFileSymbol) {
48612                         file = ts.getDeclarationOfKind(equivalentFileSymbol, 297 /* SourceFile */);
48613                     }
48614                 }
48615                 if (file && file.moduleName !== undefined) {
48616                     // Use the amd name if it is available
48617                     return file.moduleName;
48618                 }
48619                 if (!file) {
48620                     if (context.tracker.trackReferencedAmbientModule) {
48621                         var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
48622                         if (ts.length(ambientDecls)) {
48623                             for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) {
48624                                 var decl = ambientDecls_1[_i];
48625                                 context.tracker.trackReferencedAmbientModule(decl, symbol);
48626                             }
48627                         }
48628                     }
48629                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
48630                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
48631                     }
48632                 }
48633                 if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) {
48634                     // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name
48635                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
48636                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
48637                     }
48638                     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
48639                 }
48640                 var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration));
48641                 var links = getSymbolLinks(symbol);
48642                 var specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
48643                 if (!specifier) {
48644                     var isBundle_1 = !!ts.outFile(compilerOptions);
48645                     // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
48646                     // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
48647                     // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
48648                     // specifier preference
48649                     var moduleResolverHost = context.tracker.moduleResolverHost;
48650                     var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
48651                     specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, checker, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined }));
48652                     (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map());
48653                     links.specifierCache.set(contextFile.path, specifier);
48654                 }
48655                 return specifier;
48656             }
48657             function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
48658                 var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
48659                 var isTypeOf = meaning === 111551 /* Value */;
48660                 if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
48661                     // module is root, must use `ImportTypeNode`
48662                     var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
48663                     var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
48664                     var specifier = getSpecifierForModuleSymbol(chain[0], context);
48665                     if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
48666                         // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
48667                         // since declaration files with these kinds of references are liable to fail when published :(
48668                         context.encounteredError = true;
48669                         if (context.tracker.reportLikelyUnsafeImportRequiredError) {
48670                             context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
48671                         }
48672                     }
48673                     var lit = ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(specifier));
48674                     if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
48675                         context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
48676                     context.approximateLength += specifier.length + 10; // specifier + import("")
48677                     if (!nonRootParts || ts.isEntityName(nonRootParts)) {
48678                         if (nonRootParts) {
48679                             var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
48680                             lastId.typeArguments = undefined;
48681                         }
48682                         return ts.factory.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
48683                     }
48684                     else {
48685                         var splitNode = getTopmostIndexedAccessType(nonRootParts);
48686                         var qualifier = splitNode.objectType.typeName;
48687                         return ts.factory.createIndexedAccessTypeNode(ts.factory.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
48688                     }
48689                 }
48690                 var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
48691                 if (ts.isIndexedAccessTypeNode(entityName)) {
48692                     return entityName; // Indexed accesses can never be `typeof`
48693                 }
48694                 if (isTypeOf) {
48695                     return ts.factory.createTypeQueryNode(entityName);
48696                 }
48697                 else {
48698                     var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
48699                     var lastTypeArgs = lastId.typeArguments;
48700                     lastId.typeArguments = undefined;
48701                     return ts.factory.createTypeReferenceNode(entityName, lastTypeArgs);
48702                 }
48703                 function createAccessFromSymbolChain(chain, index, stopper) {
48704                     var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
48705                     var symbol = chain[index];
48706                     var parent = chain[index - 1];
48707                     var symbolName;
48708                     if (index === 0) {
48709                         context.flags |= 16777216 /* InInitialEntityName */;
48710                         symbolName = getNameOfSymbolAsWritten(symbol, context);
48711                         context.approximateLength += (symbolName ? symbolName.length : 0) + 1;
48712                         context.flags ^= 16777216 /* InInitialEntityName */;
48713                     }
48714                     else {
48715                         if (parent && getExportsOfSymbol(parent)) {
48716                             var exports_1 = getExportsOfSymbol(parent);
48717                             ts.forEachEntry(exports_1, function (ex, name) {
48718                                 if (getSymbolIfSameReference(ex, symbol) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) {
48719                                     symbolName = ts.unescapeLeadingUnderscores(name);
48720                                     return true;
48721                                 }
48722                             });
48723                         }
48724                     }
48725                     if (!symbolName) {
48726                         symbolName = getNameOfSymbolAsWritten(symbol, context);
48727                     }
48728                     context.approximateLength += symbolName.length + 1;
48729                     if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent &&
48730                         getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) &&
48731                         getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol.escapedName), symbol)) {
48732                         // Should use an indexed access
48733                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
48734                         if (ts.isIndexedAccessTypeNode(LHS)) {
48735                             return ts.factory.createIndexedAccessTypeNode(LHS, ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(symbolName)));
48736                         }
48737                         else {
48738                             return ts.factory.createIndexedAccessTypeNode(ts.factory.createTypeReferenceNode(LHS, typeParameterNodes), ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(symbolName)));
48739                         }
48740                     }
48741                     var identifier = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
48742                     identifier.symbol = symbol;
48743                     if (index > stopper) {
48744                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
48745                         if (!ts.isEntityName(LHS)) {
48746                             return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
48747                         }
48748                         return ts.factory.createQualifiedName(LHS, identifier);
48749                     }
48750                     return identifier;
48751                 }
48752             }
48753             function typeParameterShadowsNameInScope(escapedName, context, type) {
48754                 var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false);
48755                 if (result) {
48756                     if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) {
48757                         return false;
48758                     }
48759                     return true;
48760                 }
48761                 return false;
48762             }
48763             function typeParameterToName(type, context) {
48764                 var _a;
48765                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) {
48766                     var cached = context.typeParameterNames.get(getTypeId(type));
48767                     if (cached) {
48768                         return cached;
48769                     }
48770                 }
48771                 var result = symbolToName(type.symbol, context, 788968 /* Type */, /*expectsIdentifier*/ true);
48772                 if (!(result.kind & 78 /* Identifier */)) {
48773                     return ts.factory.createIdentifier("(Missing type parameter)");
48774                 }
48775                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
48776                     var rawtext = result.escapedText;
48777                     var i = 0;
48778                     var text = rawtext;
48779                     while (((_a = context.typeParameterNamesByText) === null || _a === void 0 ? void 0 : _a.has(text)) || typeParameterShadowsNameInScope(text, context, type)) {
48780                         i++;
48781                         text = rawtext + "_" + i;
48782                     }
48783                     if (text !== rawtext) {
48784                         result = ts.factory.createIdentifier(text, result.typeArguments);
48785                     }
48786                     (context.typeParameterNames || (context.typeParameterNames = new ts.Map())).set(getTypeId(type), result);
48787                     (context.typeParameterNamesByText || (context.typeParameterNamesByText = new ts.Set())).add(result.escapedText);
48788                 }
48789                 return result;
48790             }
48791             function symbolToName(symbol, context, meaning, expectsIdentifier) {
48792                 var chain = lookupSymbolChain(symbol, context, meaning);
48793                 if (expectsIdentifier && chain.length !== 1
48794                     && !context.encounteredError
48795                     && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) {
48796                     context.encounteredError = true;
48797                 }
48798                 return createEntityNameFromSymbolChain(chain, chain.length - 1);
48799                 function createEntityNameFromSymbolChain(chain, index) {
48800                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
48801                     var symbol = chain[index];
48802                     if (index === 0) {
48803                         context.flags |= 16777216 /* InInitialEntityName */;
48804                     }
48805                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
48806                     if (index === 0) {
48807                         context.flags ^= 16777216 /* InInitialEntityName */;
48808                     }
48809                     var identifier = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
48810                     identifier.symbol = symbol;
48811                     return index > 0 ? ts.factory.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
48812                 }
48813             }
48814             function symbolToExpression(symbol, context, meaning) {
48815                 var chain = lookupSymbolChain(symbol, context, meaning);
48816                 return createExpressionFromSymbolChain(chain, chain.length - 1);
48817                 function createExpressionFromSymbolChain(chain, index) {
48818                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
48819                     var symbol = chain[index];
48820                     if (index === 0) {
48821                         context.flags |= 16777216 /* InInitialEntityName */;
48822                     }
48823                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
48824                     if (index === 0) {
48825                         context.flags ^= 16777216 /* InInitialEntityName */;
48826                     }
48827                     var firstChar = symbolName.charCodeAt(0);
48828                     if (ts.isSingleOrDoubleQuote(firstChar) && ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
48829                         return ts.factory.createStringLiteral(getSpecifierForModuleSymbol(symbol, context));
48830                     }
48831                     var canUsePropertyAccess = firstChar === 35 /* hash */ ?
48832                         symbolName.length > 1 && ts.isIdentifierStart(symbolName.charCodeAt(1), languageVersion) :
48833                         ts.isIdentifierStart(firstChar, languageVersion);
48834                     if (index === 0 || canUsePropertyAccess) {
48835                         var identifier = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
48836                         identifier.symbol = symbol;
48837                         return index > 0 ? ts.factory.createPropertyAccessExpression(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier;
48838                     }
48839                     else {
48840                         if (firstChar === 91 /* openBracket */) {
48841                             symbolName = symbolName.substring(1, symbolName.length - 1);
48842                             firstChar = symbolName.charCodeAt(0);
48843                         }
48844                         var expression = void 0;
48845                         if (ts.isSingleOrDoubleQuote(firstChar)) {
48846                             expression = ts.factory.createStringLiteral(symbolName
48847                                 .substring(1, symbolName.length - 1)
48848                                 .replace(/\\./g, function (s) { return s.substring(1); }), firstChar === 39 /* singleQuote */);
48849                         }
48850                         else if (("" + +symbolName) === symbolName) {
48851                             expression = ts.factory.createNumericLiteral(+symbolName);
48852                         }
48853                         if (!expression) {
48854                             expression = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
48855                             expression.symbol = symbol;
48856                         }
48857                         return ts.factory.createElementAccessExpression(createExpressionFromSymbolChain(chain, index - 1), expression);
48858                     }
48859                 }
48860             }
48861             function isStringNamed(d) {
48862                 var name = ts.getNameOfDeclaration(d);
48863                 return !!name && ts.isStringLiteral(name);
48864             }
48865             function isSingleQuotedStringNamed(d) {
48866                 var name = ts.getNameOfDeclaration(d);
48867                 return !!(name && ts.isStringLiteral(name) && (name.singleQuote || !ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")));
48868             }
48869             function getPropertyNameNodeForSymbol(symbol, context) {
48870                 var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed);
48871                 var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote);
48872                 if (fromNameType) {
48873                     return fromNameType;
48874                 }
48875                 if (ts.isKnownSymbol(symbol)) {
48876                     return ts.factory.createComputedPropertyName(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("Symbol"), symbol.escapedName.substr(3)));
48877                 }
48878                 var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName);
48879                 var stringNamed = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isStringNamed);
48880                 return createPropertyNameNodeForIdentifierOrLiteral(rawName, stringNamed, singleQuote);
48881             }
48882             // See getNameForSymbolFromNameType for a stringy equivalent
48883             function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) {
48884                 var nameType = getSymbolLinks(symbol).nameType;
48885                 if (nameType) {
48886                     if (nameType.flags & 384 /* StringOrNumberLiteral */) {
48887                         var name = "" + nameType.value;
48888                         if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
48889                             return ts.factory.createStringLiteral(name, !!singleQuote);
48890                         }
48891                         if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
48892                             return ts.factory.createComputedPropertyName(ts.factory.createNumericLiteral(+name));
48893                         }
48894                         return createPropertyNameNodeForIdentifierOrLiteral(name);
48895                     }
48896                     if (nameType.flags & 8192 /* UniqueESSymbol */) {
48897                         return ts.factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */));
48898                     }
48899                 }
48900             }
48901             function createPropertyNameNodeForIdentifierOrLiteral(name, stringNamed, singleQuote) {
48902                 return ts.isIdentifierText(name, compilerOptions.target) ? ts.factory.createIdentifier(name) :
48903                     !stringNamed && isNumericLiteralName(name) && +name >= 0 ? ts.factory.createNumericLiteral(+name) :
48904                         ts.factory.createStringLiteral(name, !!singleQuote);
48905             }
48906             function cloneNodeBuilderContext(context) {
48907                 var initial = __assign({}, context);
48908                 // Make type parameters created within this context not consume the name outside this context
48909                 // The symbol serializer ends up creating many sibling scopes that all need "separate" contexts when
48910                 // it comes to naming things - within a normal `typeToTypeNode` call, the node builder only ever descends
48911                 // through the type tree, so the only cases where we could have used distinct sibling scopes was when there
48912                 // were multiple generic overloads with similar generated type parameter names
48913                 // The effect:
48914                 // When we write out
48915                 // export const x: <T>(x: T) => T
48916                 // export const y: <T>(x: T) => T
48917                 // we write it out like that, rather than as
48918                 // export const x: <T>(x: T) => T
48919                 // export const y: <T_1>(x: T_1) => T_1
48920                 if (initial.typeParameterNames) {
48921                     initial.typeParameterNames = new ts.Map(initial.typeParameterNames);
48922                 }
48923                 if (initial.typeParameterNamesByText) {
48924                     initial.typeParameterNamesByText = new ts.Set(initial.typeParameterNamesByText);
48925                 }
48926                 if (initial.typeParameterSymbolList) {
48927                     initial.typeParameterSymbolList = new ts.Set(initial.typeParameterSymbolList);
48928                 }
48929                 return initial;
48930             }
48931             function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) {
48932                 return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); });
48933             }
48934             function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) {
48935                 return !(ts.getObjectFlags(type) & 4 /* Reference */) || !ts.isTypeReferenceNode(existing) || ts.length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters);
48936             }
48937             /**
48938              * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag
48939              * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym`
48940              */
48941             function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) {
48942                 if (type !== errorType && enclosingDeclaration) {
48943                     var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration);
48944                     if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) {
48945                         // try to reuse the existing annotation
48946                         var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation);
48947                         if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) {
48948                             var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled);
48949                             if (result_5) {
48950                                 return result_5;
48951                             }
48952                         }
48953                     }
48954                 }
48955                 var oldFlags = context.flags;
48956                 if (type.flags & 8192 /* UniqueESSymbol */ &&
48957                     type.symbol === symbol && (!context.enclosingDeclaration || ts.some(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration); }))) {
48958                     context.flags |= 1048576 /* AllowUniqueESSymbolType */;
48959                 }
48960                 var result = typeToTypeNodeHelper(type, context);
48961                 context.flags = oldFlags;
48962                 return result;
48963             }
48964             function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) {
48965                 if (type !== errorType && context.enclosingDeclaration) {
48966                     var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
48967                     if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) {
48968                         var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled);
48969                         if (result) {
48970                             return result;
48971                         }
48972                     }
48973                 }
48974                 return typeToTypeNodeHelper(type, context);
48975             }
48976             function trackExistingEntityName(node, context, includePrivateSymbol) {
48977                 var _a, _b;
48978                 var introducesError = false;
48979                 var leftmost = ts.getFirstIdentifier(node);
48980                 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)))) {
48981                     introducesError = true;
48982                     return { introducesError: introducesError, node: node };
48983                 }
48984                 var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true);
48985                 if (sym) {
48986                     if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) {
48987                         introducesError = true;
48988                     }
48989                     else {
48990                         (_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 */);
48991                         includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym);
48992                     }
48993                     if (ts.isIdentifier(node)) {
48994                         var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.factory.cloneNode(node);
48995                         name.symbol = sym; // for quickinfo, which uses identifier symbol information
48996                         return { introducesError: introducesError, node: ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */) };
48997                     }
48998                 }
48999                 return { introducesError: introducesError, node: node };
49000             }
49001             function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) {
49002                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
49003                     cancellationToken.throwIfCancellationRequested();
49004                 }
49005                 var hadError = false;
49006                 var file = ts.getSourceFileOfNode(existing);
49007                 var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols);
49008                 if (hadError) {
49009                     return undefined;
49010                 }
49011                 return transformed === existing ? ts.setTextRange(ts.factory.cloneNode(existing), existing) : transformed;
49012                 function visitExistingNodeTreeSymbols(node) {
49013                     // We don't _actually_ support jsdoc namepath types, emit `any` instead
49014                     if (ts.isJSDocAllType(node) || node.kind === 310 /* JSDocNamepathType */) {
49015                         return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
49016                     }
49017                     if (ts.isJSDocUnknownType(node)) {
49018                         return ts.factory.createKeywordTypeNode(152 /* UnknownKeyword */);
49019                     }
49020                     if (ts.isJSDocNullableType(node)) {
49021                         return ts.factory.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.factory.createLiteralTypeNode(ts.factory.createNull())]);
49022                     }
49023                     if (ts.isJSDocOptionalType(node)) {
49024                         return ts.factory.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.factory.createKeywordTypeNode(150 /* UndefinedKeyword */)]);
49025                     }
49026                     if (ts.isJSDocNonNullableType(node)) {
49027                         return ts.visitNode(node.type, visitExistingNodeTreeSymbols);
49028                     }
49029                     if (ts.isJSDocVariadicType(node)) {
49030                         return ts.factory.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols));
49031                     }
49032                     if (ts.isJSDocTypeLiteral(node)) {
49033                         return ts.factory.createTypeLiteralNode(ts.map(node.jsDocPropertyTags, function (t) {
49034                             var name = ts.isIdentifier(t.name) ? t.name : t.name.right;
49035                             var typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText);
49036                             var overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : undefined;
49037                             return ts.factory.createPropertySignature(
49038                             /*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(128 /* AnyKeyword */));
49039                         }));
49040                     }
49041                     if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") {
49042                         return ts.setOriginalNode(ts.factory.createKeywordTypeNode(128 /* AnyKeyword */), node);
49043                     }
49044                     if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) {
49045                         return ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(
49046                             /*decorators*/ undefined, 
49047                             /*modifiers*/ undefined, [ts.factory.createParameterDeclaration(
49048                                 /*decorators*/ undefined, 
49049                                 /*modifiers*/ undefined, 
49050                                 /*dotdotdotToken*/ undefined, "x", 
49051                                 /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]);
49052                     }
49053                     if (ts.isJSDocFunctionType(node)) {
49054                         if (ts.isJSDocConstructSignature(node)) {
49055                             var newTypeNode_1;
49056                             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(
49057                             /*decorators*/ undefined, 
49058                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
49059                             /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
49060                         }
49061                         else {
49062                             return ts.factory.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.factory.createParameterDeclaration(
49063                             /*decorators*/ undefined, 
49064                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
49065                             /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
49066                         }
49067                     }
49068                     if (ts.isTypeReferenceNode(node) && ts.isInJSDoc(node) && (!existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(node, getTypeFromTypeNode(node)) || getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */, /*ignoreErrors*/ true))) {
49069                         return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node);
49070                     }
49071                     if (ts.isLiteralImportTypeNode(node)) {
49072                         var nodeSymbol = getNodeLinks(node).resolvedSymbol;
49073                         if (ts.isInJSDoc(node) &&
49074                             nodeSymbol &&
49075                             (
49076                             // The import type resolved using jsdoc fallback logic
49077                             (!node.isTypeOf && !(nodeSymbol.flags & 788968 /* Type */)) ||
49078                                 // The import type had type arguments autofilled by js fallback logic
49079                                 !(ts.length(node.typeArguments) >= getMinTypeArgumentCount(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(nodeSymbol))))) {
49080                             return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node);
49081                         }
49082                         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);
49083                     }
49084                     if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) {
49085                         var _a = trackExistingEntityName(node, context, includePrivateSymbol), introducesError = _a.introducesError, result = _a.node;
49086                         hadError = hadError || introducesError;
49087                         if (result !== node) {
49088                             return result;
49089                         }
49090                     }
49091                     if (file && ts.isTupleTypeNode(node) && (ts.getLineAndCharacterOfPosition(file, node.pos).line === ts.getLineAndCharacterOfPosition(file, node.end).line)) {
49092                         ts.setEmitFlags(node, 1 /* SingleLine */);
49093                     }
49094                     return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext);
49095                     function getEffectiveDotDotDotForParameter(p) {
49096                         return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined);
49097                     }
49098                     /** Note that `new:T` parameters are not handled, but should be before calling this function. */
49099                     function getNameForJSDocFunctionParameter(p, index) {
49100                         return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "this" ? "this"
49101                             : getEffectiveDotDotDotForParameter(p) ? "args"
49102                                 : "arg" + index;
49103                     }
49104                     function rewriteModuleSpecifier(parent, lit) {
49105                         if (bundled) {
49106                             if (context.tracker && context.tracker.moduleResolverHost) {
49107                                 var targetFile = getExternalModuleFileFromDeclaration(parent);
49108                                 if (targetFile) {
49109                                     var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames);
49110                                     var resolverHost = {
49111                                         getCanonicalFileName: getCanonicalFileName,
49112                                         getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); },
49113                                         getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); }
49114                                     };
49115                                     var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile);
49116                                     return ts.factory.createStringLiteral(newName);
49117                                 }
49118                             }
49119                         }
49120                         else {
49121                             if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) {
49122                                 var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined);
49123                                 if (moduleSym) {
49124                                     context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym);
49125                                 }
49126                             }
49127                         }
49128                         return lit;
49129                     }
49130                 }
49131             }
49132             function symbolTableToDeclarationStatements(symbolTable, context, bundled) {
49133                 var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 165 /* MethodDeclaration */, /*useAcessors*/ true);
49134                 var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 164 /* MethodSignature */, /*useAcessors*/ false);
49135                 // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of
49136                 // declaration mapping
49137                 // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration
49138                 // emit codepaths which want to apply more specific contexts (so we can still refer to the root real declaration
49139                 // we're trying to emit from later on)
49140                 var enclosingDeclaration = context.enclosingDeclaration;
49141                 var results = [];
49142                 var visitedSymbols = new ts.Set();
49143                 var deferredPrivatesStack = [];
49144                 var oldcontext = context;
49145                 context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) {
49146                             var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeAliases*/ false);
49147                             if (accessibleResult.accessibility === 0 /* Accessible */) {
49148                                 // Lookup the root symbol of the chain of refs we'll use to access it and serialize it
49149                                 var chain = lookupSymbolChainWorker(sym, context, meaning);
49150                                 if (!(sym.flags & 4 /* Property */)) {
49151                                     includePrivateSymbol(chain[0]);
49152                                 }
49153                             }
49154                             else if (oldcontext.tracker && oldcontext.tracker.trackSymbol) {
49155                                 oldcontext.tracker.trackSymbol(sym, decl, meaning);
49156                             }
49157                         } }) });
49158                 ts.forEachEntry(symbolTable, function (symbol, name) {
49159                     var baseName = ts.unescapeLeadingUnderscores(name);
49160                     void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames`
49161                 });
49162                 var addingDeclare = !bundled;
49163                 var exportEquals = symbolTable.get("export=" /* ExportEquals */);
49164                 if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) {
49165                     symbolTable = ts.createSymbolTable();
49166                     // Remove extraneous elements from root symbol table (they'll be mixed back in when the target of the `export=` is looked up)
49167                     symbolTable.set("export=" /* ExportEquals */, exportEquals);
49168                 }
49169                 visitSymbolTable(symbolTable);
49170                 return mergeRedundantStatements(results);
49171                 function isIdentifierAndNotUndefined(node) {
49172                     return !!node && node.kind === 78 /* Identifier */;
49173                 }
49174                 function getNamesOfDeclaration(statement) {
49175                     if (ts.isVariableStatement(statement)) {
49176                         return ts.filter(ts.map(statement.declarationList.declarations, ts.getNameOfDeclaration), isIdentifierAndNotUndefined);
49177                     }
49178                     return ts.filter([ts.getNameOfDeclaration(statement)], isIdentifierAndNotUndefined);
49179                 }
49180                 function flattenExportAssignedNamespace(statements) {
49181                     var exportAssignment = ts.find(statements, ts.isExportAssignment);
49182                     var nsIndex = ts.findIndex(statements, ts.isModuleDeclaration);
49183                     var ns = nsIndex !== -1 ? statements[nsIndex] : undefined;
49184                     if (ns && exportAssignment && exportAssignment.isExportEquals &&
49185                         ts.isIdentifier(exportAssignment.expression) && ts.isIdentifier(ns.name) && ts.idText(ns.name) === ts.idText(exportAssignment.expression) &&
49186                         ns.body && ts.isModuleBlock(ns.body)) {
49187                         // Pass 0: Correct situations where a module has both an `export = ns` and multiple top-level exports by stripping the export modifiers from
49188                         //  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
49189                         var excessExports = ts.filter(statements, function (s) { return !!(ts.getEffectiveModifierFlags(s) & 1 /* Export */); });
49190                         var name_2 = ns.name;
49191                         var body = ns.body;
49192                         if (ts.length(excessExports)) {
49193                             ns = ts.factory.updateModuleDeclaration(ns, ns.decorators, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArray(__spreadArray([], ns.body.statements), [ts.factory.createExportDeclaration(
49194                                 /*decorators*/ undefined, 
49195                                 /*modifiers*/ undefined, 
49196                                 /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.factory.createExportSpecifier(/*alias*/ undefined, id); })), 
49197                                 /*moduleSpecifier*/ undefined)]))));
49198                             statements = __spreadArray(__spreadArray(__spreadArray([], statements.slice(0, nsIndex)), [ns]), statements.slice(nsIndex + 1));
49199                         }
49200                         // Pass 1: Flatten `export namespace _exports {} export = _exports;` so long as the `export=` only points at a single namespace declaration
49201                         if (!ts.find(statements, function (s) { return s !== ns && ts.nodeHasName(s, name_2); })) {
49202                             results = [];
49203                             // If the namespace contains no export assignments or declarations, and no declarations flagged with `export`, then _everything_ is exported -
49204                             // to respect this as the top level, we need to add an `export` modifier to everything
49205                             var mixinExportFlag_1 = !ts.some(body.statements, function (s) { return ts.hasSyntacticModifier(s, 1 /* Export */) || ts.isExportAssignment(s) || ts.isExportDeclaration(s); });
49206                             ts.forEach(body.statements, function (s) {
49207                                 addResult(s, mixinExportFlag_1 ? 1 /* Export */ : 0 /* None */); // Recalculates the ambient (and export, if applicable from above) flag
49208                             });
49209                             statements = __spreadArray(__spreadArray([], ts.filter(statements, function (s) { return s !== ns && s !== exportAssignment; })), results);
49210                         }
49211                     }
49212                     return statements;
49213                 }
49214                 function mergeExportDeclarations(statements) {
49215                     // Pass 2: Combine all `export {}` declarations
49216                     var exports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
49217                     if (ts.length(exports) > 1) {
49218                         var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; });
49219                         statements = __spreadArray(__spreadArray([], nonExports), [ts.factory.createExportDeclaration(
49220                             /*decorators*/ undefined, 
49221                             /*modifiers*/ undefined, 
49222                             /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), 
49223                             /*moduleSpecifier*/ undefined)]);
49224                     }
49225                     // Pass 2b: Also combine all `export {} from "..."` declarations as needed
49226                     var reexports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
49227                     if (ts.length(reexports) > 1) {
49228                         var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; });
49229                         if (groups.length !== reexports.length) {
49230                             var _loop_9 = function (group_1) {
49231                                 if (group_1.length > 1) {
49232                                     // remove group members from statements and then merge group members and add back to statements
49233                                     statements = __spreadArray(__spreadArray([], ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; })), [
49234                                         ts.factory.createExportDeclaration(
49235                                         /*decorators*/ undefined, 
49236                                         /*modifiers*/ undefined, 
49237                                         /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier)
49238                                     ]);
49239                                 }
49240                             };
49241                             for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {
49242                                 var group_1 = groups_1[_i];
49243                                 _loop_9(group_1);
49244                             }
49245                         }
49246                     }
49247                     return statements;
49248                 }
49249                 function inlineExportModifiers(statements) {
49250                     // Pass 3: Move all `export {}`'s to `export` modifiers where possible
49251                     var index = ts.findIndex(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
49252                     if (index >= 0) {
49253                         var exportDecl = statements[index];
49254                         var replacements = ts.mapDefined(exportDecl.exportClause.elements, function (e) {
49255                             if (!e.propertyName) {
49256                                 // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it
49257                                 var indices = ts.indicesOf(statements);
49258                                 var associatedIndices = ts.filter(indices, function (i) { return ts.nodeHasName(statements[i], e.name); });
49259                                 if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return canHaveExportModifier(statements[i]); })) {
49260                                     for (var _i = 0, associatedIndices_1 = associatedIndices; _i < associatedIndices_1.length; _i++) {
49261                                         var index_1 = associatedIndices_1[_i];
49262                                         statements[index_1] = addExportModifier(statements[index_1]);
49263                                     }
49264                                     return undefined;
49265                                 }
49266                             }
49267                             return e;
49268                         });
49269                         if (!ts.length(replacements)) {
49270                             // all clauses removed, remove the export declaration
49271                             ts.orderedRemoveItemAt(statements, index);
49272                         }
49273                         else {
49274                             // some items filtered, others not - update the export declaration
49275                             statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier);
49276                         }
49277                     }
49278                     return statements;
49279                 }
49280                 function mergeRedundantStatements(statements) {
49281                     statements = flattenExportAssignedNamespace(statements);
49282                     statements = mergeExportDeclarations(statements);
49283                     statements = inlineExportModifiers(statements);
49284                     // 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
49285                     // declaration privacy is respected.
49286                     if (enclosingDeclaration &&
49287                         ((ts.isSourceFile(enclosingDeclaration) && ts.isExternalOrCommonJsModule(enclosingDeclaration)) || ts.isModuleDeclaration(enclosingDeclaration)) &&
49288                         (!ts.some(statements, ts.isExternalModuleIndicator) || (!ts.hasScopeMarker(statements) && ts.some(statements, ts.needsScopeMarker)))) {
49289                         statements.push(ts.createEmptyExports(ts.factory));
49290                     }
49291                     return statements;
49292                 }
49293                 function canHaveExportModifier(node) {
49294                     return ts.isEnumDeclaration(node) ||
49295                         ts.isVariableStatement(node) ||
49296                         ts.isFunctionDeclaration(node) ||
49297                         ts.isClassDeclaration(node) ||
49298                         (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) ||
49299                         ts.isInterfaceDeclaration(node) ||
49300                         isTypeDeclaration(node);
49301                 }
49302                 function addExportModifier(node) {
49303                     var flags = (ts.getEffectiveModifierFlags(node) | 1 /* Export */) & ~2 /* Ambient */;
49304                     return ts.factory.updateModifiers(node, flags);
49305                 }
49306                 function removeExportModifier(node) {
49307                     var flags = ts.getEffectiveModifierFlags(node) & ~1 /* Export */;
49308                     return ts.factory.updateModifiers(node, flags);
49309                 }
49310                 function visitSymbolTable(symbolTable, suppressNewPrivateContext, propertyAsAlias) {
49311                     if (!suppressNewPrivateContext) {
49312                         deferredPrivatesStack.push(new ts.Map());
49313                     }
49314                     symbolTable.forEach(function (symbol) {
49315                         serializeSymbol(symbol, /*isPrivate*/ false, !!propertyAsAlias);
49316                     });
49317                     if (!suppressNewPrivateContext) {
49318                         // deferredPrivates will be filled up by visiting the symbol table
49319                         // And will continue to iterate as elements are added while visited `deferredPrivates`
49320                         // (As that's how a map iterator is defined to work)
49321                         deferredPrivatesStack[deferredPrivatesStack.length - 1].forEach(function (symbol) {
49322                             serializeSymbol(symbol, /*isPrivate*/ true, !!propertyAsAlias);
49323                         });
49324                         deferredPrivatesStack.pop();
49325                     }
49326                 }
49327                 function serializeSymbol(symbol, isPrivate, propertyAsAlias) {
49328                     // cache visited list based on merged symbol, since we want to use the unmerged top-level symbol, but
49329                     // still skip reserializing it if we encounter the merged product later on
49330                     var visitedSym = getMergedSymbol(symbol);
49331                     if (visitedSymbols.has(getSymbolId(visitedSym))) {
49332                         return; // Already printed
49333                     }
49334                     visitedSymbols.add(getSymbolId(visitedSym));
49335                     // Only actually serialize symbols within the correct enclosing declaration, otherwise do nothing with the out-of-context symbol
49336                     var skipMembershipCheck = !isPrivate; // We only call this on exported symbols when we know they're in the correct scope
49337                     if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) {
49338                         var oldContext = context;
49339                         context = cloneNodeBuilderContext(context);
49340                         var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias);
49341                         context = oldContext;
49342                         return result;
49343                     }
49344                 }
49345                 // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias
49346                 // or a merge of some number of those.
49347                 // An interesting challenge is ensuring that when classes merge with namespaces and interfaces, is keeping
49348                 // each symbol in only one of the representations
49349                 // Also, synthesizing a default export of some kind
49350                 // If it's an alias: emit `export default ref`
49351                 // If it's a property: emit `export default _default` with a `_default` prop
49352                 // If it's a class/interface/function: emit a class/interface/function with a `default` modifier
49353                 // These forms can merge, eg (`export default 12; export default interface A {}`)
49354                 function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) {
49355                     var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName);
49356                     var isDefault = symbol.escapedName === "default" /* Default */;
49357                     if (isPrivate && !(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) {
49358                         // 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` :(
49359                         context.encounteredError = true;
49360                         // TODO: Issue error via symbol tracker?
49361                         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
49362                     }
49363                     var needsPostExportDefault = isDefault && !!(symbol.flags & -113 /* ExportDoesNotSupportDefaultModifier */
49364                         || (symbol.flags & 16 /* Function */ && ts.length(getPropertiesOfType(getTypeOfSymbol(symbol))))) && !(symbol.flags & 2097152 /* Alias */); // An alias symbol should preclude needing to make an alias ourselves
49365                     var needsExportDeclaration = !needsPostExportDefault && !isPrivate && ts.isStringANonContextualKeyword(symbolName) && !isDefault;
49366                     // `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
49367                     if (needsPostExportDefault || needsExportDeclaration) {
49368                         isPrivate = true;
49369                     }
49370                     var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0);
49371                     var isConstMergedWithNS = symbol.flags & 1536 /* Module */ &&
49372                         symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) &&
49373                         symbol.escapedName !== "export=" /* ExportEquals */;
49374                     var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol);
49375                     if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) {
49376                         serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
49377                     }
49378                     if (symbol.flags & 524288 /* TypeAlias */) {
49379                         serializeTypeAlias(symbol, symbolName, modifierFlags);
49380                     }
49381                     // Need to skip over export= symbols below - json source files get a single `Property` flagged
49382                     // symbol of name `export=` which needs to be handled like an alias. It's not great, but it is what it is.
49383                     if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */)
49384                         && symbol.escapedName !== "export=" /* ExportEquals */
49385                         && !(symbol.flags & 4194304 /* Prototype */)
49386                         && !(symbol.flags & 32 /* Class */)
49387                         && !isConstMergedWithNSPrintableAsSignatureMerge) {
49388                         if (propertyAsAlias) {
49389                             var createdExport = serializeMaybeAliasAssignment(symbol);
49390                             if (createdExport) {
49391                                 needsExportDeclaration = false;
49392                                 needsPostExportDefault = false;
49393                             }
49394                         }
49395                         else {
49396                             var type = getTypeOfSymbol(symbol);
49397                             var localName = getInternalSymbolName(symbol, symbolName);
49398                             if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) {
49399                                 // 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
49400                                 serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags);
49401                             }
49402                             else {
49403                                 // 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!_
49404                                 // `var` is `FunctionScopedVariable`, `const` and `let` are `BlockScopedVariable`, and `module.exports.thing =` is `Property`
49405                                 var flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? undefined
49406                                     : isConstVariable(symbol) ? 2 /* Const */
49407                                         : 1 /* Let */;
49408                                 var name = (needsPostExportDefault || !(symbol.flags & 4 /* Property */)) ? localName : getUnusedName(localName, symbol);
49409                                 var textRange = symbol.declarations && ts.find(symbol.declarations, function (d) { return ts.isVariableDeclaration(d); });
49410                                 if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) {
49411                                     textRange = textRange.parent.parent;
49412                                 }
49413                                 var propertyAccessRequire = ts.find(symbol.declarations, ts.isPropertyAccessExpression);
49414                                 if (propertyAccessRequire && ts.isBinaryExpression(propertyAccessRequire.parent) && ts.isIdentifier(propertyAccessRequire.parent.right)
49415                                     && type.symbol && ts.isSourceFile(type.symbol.valueDeclaration)) {
49416                                     var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right;
49417                                     addResult(ts.factory.createExportDeclaration(
49418                                     /*decorators*/ undefined, 
49419                                     /*modifiers*/ undefined, 
49420                                     /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(alias, localName)])), 0 /* None */);
49421                                     context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551 /* Value */);
49422                                 }
49423                                 else {
49424                                     var statement = ts.setTextRange(ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([
49425                                         ts.factory.createVariableDeclaration(name, /*exclamationToken*/ undefined, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
49426                                     ], flags)), textRange);
49427                                     addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags);
49428                                     if (name !== localName && !isPrivate) {
49429                                         // We rename the variable declaration we generate for Property symbols since they may have a name which
49430                                         // conflicts with a local declaration. For example, given input:
49431                                         // ```
49432                                         // function g() {}
49433                                         // module.exports.g = g
49434                                         // ```
49435                                         // In such a situation, we have a local variable named `g`, and a separate exported variable named `g`.
49436                                         // Naively, we would emit
49437                                         // ```
49438                                         // function g() {}
49439                                         // export const g: typeof g;
49440                                         // ```
49441                                         // That's obviously incorrect - the `g` in the type annotation needs to refer to the local `g`, but
49442                                         // the export declaration shadows it.
49443                                         // To work around that, we instead write
49444                                         // ```
49445                                         // function g() {}
49446                                         // const g_1: typeof g;
49447                                         // export { g_1 as g };
49448                                         // ```
49449                                         // To create an export named `g` that does _not_ shadow the local `g`
49450                                         addResult(ts.factory.createExportDeclaration(
49451                                         /*decorators*/ undefined, 
49452                                         /*modifiers*/ undefined, 
49453                                         /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(name, localName)])), 0 /* None */);
49454                                         needsExportDeclaration = false;
49455                                         needsPostExportDefault = false;
49456                                     }
49457                                 }
49458                             }
49459                         }
49460                     }
49461                     if (symbol.flags & 384 /* Enum */) {
49462                         serializeEnum(symbol, symbolName, modifierFlags);
49463                     }
49464                     if (symbol.flags & 32 /* Class */) {
49465                         if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) {
49466                             // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members,
49467                             // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property
49468                             // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today.
49469                             serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
49470                         }
49471                         else {
49472                             serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
49473                         }
49474                     }
49475                     if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) {
49476                         serializeModule(symbol, symbolName, modifierFlags);
49477                     }
49478                     // The class meaning serialization should handle serializing all interface members
49479                     if (symbol.flags & 64 /* Interface */ && !(symbol.flags & 32 /* Class */)) {
49480                         serializeInterface(symbol, symbolName, modifierFlags);
49481                     }
49482                     if (symbol.flags & 2097152 /* Alias */) {
49483                         serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
49484                     }
49485                     if (symbol.flags & 4 /* Property */ && symbol.escapedName === "export=" /* ExportEquals */) {
49486                         serializeMaybeAliasAssignment(symbol);
49487                     }
49488                     if (symbol.flags & 8388608 /* ExportStar */) {
49489                         // synthesize export * from "moduleReference"
49490                         // Straightforward - only one thing to do - make an export declaration
49491                         for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
49492                             var node = _a[_i];
49493                             var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
49494                             if (!resolvedModule)
49495                                 continue;
49496                             addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */);
49497                         }
49498                     }
49499                     if (needsPostExportDefault) {
49500                         addResult(ts.factory.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* None */);
49501                     }
49502                     else if (needsExportDeclaration) {
49503                         addResult(ts.factory.createExportDeclaration(
49504                         /*decorators*/ undefined, 
49505                         /*modifiers*/ undefined, 
49506                         /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(getInternalSymbolName(symbol, symbolName), symbolName)])), 0 /* None */);
49507                     }
49508                 }
49509                 function includePrivateSymbol(symbol) {
49510                     if (ts.some(symbol.declarations, ts.isParameterDeclaration))
49511                         return;
49512                     ts.Debug.assertIsDefined(deferredPrivatesStack[deferredPrivatesStack.length - 1]);
49513                     getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol
49514                     // Blanket moving (import) aliases into the root private context should work, since imports are not valid within namespaces
49515                     // (so they must have been in the root to begin with if they were real imports) cjs `require` aliases (an upcoming feature)
49516                     // will throw a wrench in this, since those may have been nested, but we'll need to synthesize them in the outer scope
49517                     // 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
49518                     // for the moved import; which hopefully the above `getUnusedName` call should produce.
49519                     var isExternalImportAlias = !!(symbol.flags & 2097152 /* Alias */) && !ts.some(symbol.declarations, function (d) {
49520                         return !!ts.findAncestor(d, ts.isExportDeclaration) ||
49521                             ts.isNamespaceExport(d) ||
49522                             (ts.isImportEqualsDeclaration(d) && !ts.isExternalModuleReference(d.moduleReference));
49523                     });
49524                     deferredPrivatesStack[isExternalImportAlias ? 0 : (deferredPrivatesStack.length - 1)].set(getSymbolId(symbol), symbol);
49525                 }
49526                 function isExportingScope(enclosingDeclaration) {
49527                     return ((ts.isSourceFile(enclosingDeclaration) && (ts.isExternalOrCommonJsModule(enclosingDeclaration) || ts.isJsonSourceFile(enclosingDeclaration))) ||
49528                         (ts.isAmbientModule(enclosingDeclaration) && !ts.isGlobalScopeAugmentation(enclosingDeclaration)));
49529                 }
49530                 // Prepends a `declare` and/or `export` modifier if the context requires it, and then adds `node` to `result` and returns `node`
49531                 function addResult(node, additionalModifierFlags) {
49532                     if (ts.canHaveModifiers(node)) {
49533                         var newModifierFlags = 0 /* None */;
49534                         var enclosingDeclaration_1 = context.enclosingDeclaration &&
49535                             (ts.isJSDocTypeAlias(context.enclosingDeclaration) ? ts.getSourceFileOfNode(context.enclosingDeclaration) : context.enclosingDeclaration);
49536                         if (additionalModifierFlags & 1 /* Export */ &&
49537                             enclosingDeclaration_1 && (isExportingScope(enclosingDeclaration_1) || ts.isModuleDeclaration(enclosingDeclaration_1)) &&
49538                             canHaveExportModifier(node)) {
49539                             // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private
49540                             newModifierFlags |= 1 /* Export */;
49541                         }
49542                         if (addingDeclare && !(newModifierFlags & 1 /* Export */) &&
49543                             (!enclosingDeclaration_1 || !(enclosingDeclaration_1.flags & 8388608 /* Ambient */)) &&
49544                             (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) {
49545                             // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope
49546                             newModifierFlags |= 2 /* Ambient */;
49547                         }
49548                         if ((additionalModifierFlags & 512 /* Default */) && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isFunctionDeclaration(node))) {
49549                             newModifierFlags |= 512 /* Default */;
49550                         }
49551                         if (newModifierFlags) {
49552                             node = ts.factory.updateModifiers(node, newModifierFlags | ts.getEffectiveModifierFlags(node));
49553                         }
49554                     }
49555                     results.push(node);
49556                 }
49557                 function serializeTypeAlias(symbol, symbolName, modifierFlags) {
49558                     var aliasType = getDeclaredTypeOfTypeAlias(symbol);
49559                     var typeParams = getSymbolLinks(symbol).typeParameters;
49560                     var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); });
49561                     var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias);
49562                     var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined;
49563                     var oldFlags = context.flags;
49564                     context.flags |= 8388608 /* InTypeAlias */;
49565                     var oldEnclosingDecl = context.enclosingDeclaration;
49566                     context.enclosingDeclaration = jsdocAliasDecl;
49567                     var typeNode = jsdocAliasDecl && jsdocAliasDecl.typeExpression
49568                         && ts.isJSDocTypeExpression(jsdocAliasDecl.typeExpression)
49569                         && serializeExistingTypeNode(context, jsdocAliasDecl.typeExpression.type, includePrivateSymbol, bundled)
49570                         || typeToTypeNodeHelper(aliasType, context);
49571                     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);
49572                     context.flags = oldFlags;
49573                     context.enclosingDeclaration = oldEnclosingDecl;
49574                 }
49575                 function serializeInterface(symbol, symbolName, modifierFlags) {
49576                     var interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
49577                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
49578                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
49579                     var baseTypes = getBaseTypes(interfaceType);
49580                     var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined;
49581                     var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); });
49582                     var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 169 /* CallSignature */);
49583                     var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 170 /* ConstructSignature */);
49584                     var indexSignatures = serializeIndexSignatures(interfaceType, baseType);
49585                     var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(93 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* Value */); }))];
49586                     addResult(ts.factory.createInterfaceDeclaration(
49587                     /*decorators*/ undefined, 
49588                     /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures), constructSignatures), callSignatures), members)), modifierFlags);
49589                 }
49590                 function getNamespaceMembersForSerialization(symbol) {
49591                     return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember);
49592                 }
49593                 function isTypeOnlyNamespace(symbol) {
49594                     return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); });
49595                 }
49596                 function serializeModule(symbol, symbolName, modifierFlags) {
49597                     var members = getNamespaceMembersForSerialization(symbol);
49598                     // 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)
49599                     var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; });
49600                     var realMembers = locationMap.get("real") || ts.emptyArray;
49601                     var mergedMembers = locationMap.get("merged") || ts.emptyArray;
49602                     // TODO: `suppressNewPrivateContext` is questionable -we need to simply be emitting privates in whatever scope they were declared in, rather
49603                     // 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,
49604                     // so we don't even have placeholders to fill in.
49605                     if (ts.length(realMembers)) {
49606                         var localName = getInternalSymbolName(symbol, symbolName);
49607                         serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */)));
49608                     }
49609                     if (ts.length(mergedMembers)) {
49610                         var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration);
49611                         var localName = getInternalSymbolName(symbol, symbolName);
49612                         var nsBody = ts.factory.createModuleBlock([ts.factory.createExportDeclaration(
49613                             /*decorators*/ undefined, 
49614                             /*modifiers*/ undefined, 
49615                             /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) {
49616                                 var _a, _b;
49617                                 var name = ts.unescapeLeadingUnderscores(s.escapedName);
49618                                 var localName = getInternalSymbolName(s, name);
49619                                 var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s);
49620                                 if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) {
49621                                     (_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);
49622                                     return undefined;
49623                                 }
49624                                 var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
49625                                 includePrivateSymbol(target || s);
49626                                 var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName;
49627                                 return ts.factory.createExportSpecifier(name === targetName ? undefined : targetName, name);
49628                             })))]);
49629                         addResult(ts.factory.createModuleDeclaration(
49630                         /*decorators*/ undefined, 
49631                         /*modifiers*/ undefined, ts.factory.createIdentifier(localName), nsBody, 16 /* Namespace */), 0 /* None */);
49632                     }
49633                 }
49634                 function serializeEnum(symbol, symbolName, modifierFlags) {
49635                     addResult(ts.factory.createEnumDeclaration(
49636                     /*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) {
49637                         // TODO: Handle computed names
49638                         // I hate that to get the initialized value we need to walk back to the declarations here; but there's no
49639                         // other way to get the possible const value of an enum member that I'm aware of, as the value is cached
49640                         // _on the declaration_, not on the declaration's symbol...
49641                         var initializedValue = p.declarations && p.declarations[0] && ts.isEnumMember(p.declarations[0]) ? getConstantValue(p.declarations[0]) : undefined;
49642                         return ts.factory.createEnumMember(ts.unescapeLeadingUnderscores(p.escapedName), initializedValue === undefined ? undefined :
49643                             typeof initializedValue === "string" ? ts.factory.createStringLiteral(initializedValue) :
49644                                 ts.factory.createNumericLiteral(initializedValue));
49645                     })), modifierFlags);
49646                 }
49647                 function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) {
49648                     var signatures = getSignaturesOfType(type, 0 /* Call */);
49649                     for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
49650                         var sig = signatures_2[_i];
49651                         // Each overload becomes a separate function declaration, in order
49652                         var decl = signatureToSignatureDeclarationHelper(sig, 251 /* FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled });
49653                         // for expressions assigned to `var`s, use the `var` as the text range
49654                         addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags);
49655                     }
49656                     // Module symbol emit will take care of module-y members, provided it has exports
49657                     if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) {
49658                         var props = ts.filter(getPropertiesOfType(type), isNamespaceMember);
49659                         serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true);
49660                     }
49661                 }
49662                 function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) {
49663                     if (ts.length(props)) {
49664                         var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) {
49665                             return !ts.length(p.declarations) || ts.some(p.declarations, function (d) {
49666                                 return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration);
49667                             }) ? "local" : "remote";
49668                         });
49669                         var localProps = localVsRemoteMap.get("local") || ts.emptyArray;
49670                         // handle remote props first - we need to make an `import` declaration that points at the module containing each remote
49671                         // prop in the outermost scope (TODO: a namespace within a namespace would need to be appropriately handled by this)
49672                         // Example:
49673                         // import Foo_1 = require("./exporter");
49674                         // export namespace ns {
49675                         //     import Foo = Foo_1.Foo;
49676                         //     export { Foo };
49677                         //     export const c: number;
49678                         // }
49679                         // This is needed because in JS, statements like `const x = require("./f")` support both type and value lookup, even if they're
49680                         // normally just value lookup (so it functions kinda like an alias even when it's not an alias)
49681                         // _Usually_, we'll simply print the top-level as an alias instead of a `var` in such situations, however is is theoretically
49682                         // possible to encounter a situation where a type has members from both the current file and other files - in those situations,
49683                         // emit akin to the above would be needed.
49684                         // Add a namespace
49685                         // Create namespace as non-synthetic so it is usable as an enclosing declaration
49686                         var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* Namespace */);
49687                         ts.setParent(fakespace, enclosingDeclaration);
49688                         fakespace.locals = ts.createSymbolTable(props);
49689                         fakespace.symbol = props[0].parent;
49690                         var oldResults = results;
49691                         results = [];
49692                         var oldAddingDeclare = addingDeclare;
49693                         addingDeclare = false;
49694                         var subcontext = __assign(__assign({}, context), { enclosingDeclaration: fakespace });
49695                         var oldContext = context;
49696                         context = subcontext;
49697                         // 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
49698                         visitSymbolTable(ts.createSymbolTable(localProps), suppressNewPrivateContext, /*propertyAsAlias*/ true);
49699                         context = oldContext;
49700                         addingDeclare = oldAddingDeclare;
49701                         var declarations = results;
49702                         results = oldResults;
49703                         // replace namespace with synthetic version
49704                         var defaultReplaced = ts.map(declarations, function (d) { return ts.isExportAssignment(d) && !d.isExportEquals && ts.isIdentifier(d.expression) ? ts.factory.createExportDeclaration(
49705                         /*decorators*/ undefined, 
49706                         /*modifiers*/ undefined, 
49707                         /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(d.expression, ts.factory.createIdentifier("default" /* Default */))])) : d; });
49708                         var exportModifierStripped = ts.every(defaultReplaced, function (d) { return ts.hasSyntacticModifier(d, 1 /* Export */); }) ? ts.map(defaultReplaced, removeExportModifier) : defaultReplaced;
49709                         fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.decorators, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped));
49710                         addResult(fakespace, modifierFlags); // namespaces can never be default exported
49711                     }
49712                 }
49713                 function isNamespaceMember(p) {
49714                     return !!(p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)) ||
49715                         !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.getEffectiveModifierFlags(p.valueDeclaration) & 32 /* Static */ && ts.isClassLike(p.valueDeclaration.parent));
49716                 }
49717                 function sanitizeJSDocImplements(clauses) {
49718                     var result = ts.mapDefined(clauses, function (e) {
49719                         var _a;
49720                         var oldEnclosing = context.enclosingDeclaration;
49721                         context.enclosingDeclaration = e;
49722                         var expr = e.expression;
49723                         if (ts.isEntityNameExpression(expr)) {
49724                             if (ts.isIdentifier(expr) && ts.idText(expr) === "") {
49725                                 return cleanup(/*result*/ undefined); // Empty heritage clause, should be an error, but prefer emitting no heritage clauses to reemitting the empty one
49726                             }
49727                             var introducesError = void 0;
49728                             (_a = trackExistingEntityName(expr, context, includePrivateSymbol), introducesError = _a.introducesError, expr = _a.node);
49729                             if (introducesError) {
49730                                 return cleanup(/*result*/ undefined);
49731                             }
49732                         }
49733                         return cleanup(ts.factory.createExpressionWithTypeArguments(expr, ts.map(e.typeArguments, function (a) {
49734                             return serializeExistingTypeNode(context, a, includePrivateSymbol, bundled)
49735                                 || typeToTypeNodeHelper(getTypeFromTypeNode(a), context);
49736                         })));
49737                         function cleanup(result) {
49738                             context.enclosingDeclaration = oldEnclosing;
49739                             return result;
49740                         }
49741                     });
49742                     if (result.length === clauses.length) {
49743                         return result;
49744                     }
49745                     return undefined;
49746                 }
49747                 function serializeAsClass(symbol, localName, modifierFlags) {
49748                     var _a;
49749                     var originalDecl = ts.find(symbol.declarations, ts.isClassLike);
49750                     var oldEnclosing = context.enclosingDeclaration;
49751                     context.enclosingDeclaration = originalDecl || oldEnclosing;
49752                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
49753                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
49754                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
49755                     var baseTypes = getBaseTypes(classType);
49756                     var originalImplements = originalDecl && ts.getEffectiveImplementsTypeNodes(originalDecl);
49757                     var implementsExpressions = originalImplements && sanitizeJSDocImplements(originalImplements)
49758                         || ts.mapDefined(getImplementsTypes(classType), serializeImplementedType);
49759                     var staticType = getTypeOfSymbol(symbol);
49760                     var isClass = !!((_a = staticType.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration);
49761                     var staticBaseType = isClass
49762                         ? getBaseConstructorTypeOfClass(staticType)
49763                         : anyType;
49764                     var heritageClauses = __spreadArray(__spreadArray([], !ts.length(baseTypes) ? [] : [ts.factory.createHeritageClause(93 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))]), !ts.length(implementsExpressions) ? [] : [ts.factory.createHeritageClause(116 /* ImplementsKeyword */, implementsExpressions)]);
49765                     var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType));
49766                     var publicSymbolProps = ts.filter(symbolProps, function (s) {
49767                         // `valueDeclaration` could be undefined if inherited from
49768                         // a union/intersection base type, but inherited properties
49769                         // don't matter here.
49770                         var valueDecl = s.valueDeclaration;
49771                         return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name));
49772                     });
49773                     var hasPrivateIdentifier = ts.some(symbolProps, function (s) {
49774                         // `valueDeclaration` could be undefined if inherited from
49775                         // a union/intersection base type, but inherited properties
49776                         // don't matter here.
49777                         var valueDecl = s.valueDeclaration;
49778                         return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name);
49779                     });
49780                     // Boil down all private properties into a single one.
49781                     var privateProperties = hasPrivateIdentifier ?
49782                         [ts.factory.createPropertyDeclaration(
49783                             /*decorators*/ undefined, 
49784                             /*modifiers*/ undefined, ts.factory.createPrivateIdentifier("#private"), 
49785                             /*questionOrExclamationToken*/ undefined, 
49786                             /*type*/ undefined, 
49787                             /*initializer*/ undefined)] :
49788                         ts.emptyArray;
49789                     var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); });
49790                     // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics
49791                     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); });
49792                     // When we encounter an `X.prototype.y` assignment in a JS file, we bind `X` as a class regardless as to whether
49793                     // the value is ever initialized with a class or function-like value. For cases where `X` could never be
49794                     // created via `new`, we will inject a `private constructor()` declaration to indicate it is not createable.
49795                     var isNonConstructableClassLikeInJsFile = !isClass &&
49796                         !!symbol.valueDeclaration &&
49797                         ts.isInJSFile(symbol.valueDeclaration) &&
49798                         !ts.some(getSignaturesOfType(staticType, 1 /* Construct */));
49799                     var constructors = isNonConstructableClassLikeInJsFile ?
49800                         [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* Private */), [], /*body*/ undefined)] :
49801                         serializeSignatures(1 /* Construct */, staticType, staticBaseType, 166 /* Constructor */);
49802                     var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
49803                     context.enclosingDeclaration = oldEnclosing;
49804                     addResult(ts.setTextRange(ts.factory.createClassDeclaration(
49805                     /*decorators*/ undefined, 
49806                     /*modifiers*/ undefined, localName, typeParamDecls, heritageClauses, __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], indexSignatures), staticMembers), constructors), publicProperties), privateProperties)), symbol.declarations && ts.filter(symbol.declarations, function (d) { return ts.isClassDeclaration(d) || ts.isClassExpression(d); })[0]), modifierFlags);
49807                 }
49808                 function serializeAsAlias(symbol, localName, modifierFlags) {
49809                     var _a, _b, _c, _d, _e;
49810                     // synthesize an alias, eg `export { symbolName as Name }`
49811                     // need to mark the alias `symbol` points at
49812                     // as something we need to serialize as a private declaration as well
49813                     var node = getDeclarationOfAliasSymbol(symbol);
49814                     if (!node)
49815                         return ts.Debug.fail();
49816                     var target = getMergedSymbol(getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true));
49817                     if (!target) {
49818                         return;
49819                     }
49820                     var verbatimTargetName = ts.unescapeLeadingUnderscores(target.escapedName);
49821                     if (verbatimTargetName === "export=" /* ExportEquals */ && (compilerOptions.esModuleInterop || compilerOptions.allowSyntheticDefaultImports)) {
49822                         // target refers to an `export=` symbol that was hoisted into a synthetic default - rename here to match
49823                         verbatimTargetName = "default" /* Default */;
49824                     }
49825                     var targetName = getInternalSymbolName(target, verbatimTargetName);
49826                     includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first
49827                     switch (node.kind) {
49828                         case 198 /* BindingElement */:
49829                             if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 249 /* VariableDeclaration */) {
49830                                 // const { SomeClass } = require('./lib');
49831                                 var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib'
49832                                 var propertyName = node.propertyName;
49833                                 addResult(ts.factory.createImportDeclaration(
49834                                 /*decorators*/ undefined, 
49835                                 /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamedImports([ts.factory.createImportSpecifier(propertyName && ts.isIdentifier(propertyName) ? ts.factory.createIdentifier(ts.idText(propertyName)) : undefined, ts.factory.createIdentifier(localName))])), ts.factory.createStringLiteral(specifier_1)), 0 /* None */);
49836                                 break;
49837                             }
49838                             // We don't know how to serialize this (nested?) binding element
49839                             ts.Debug.failBadSyntaxKind(((_c = node.parent) === null || _c === void 0 ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization");
49840                             break;
49841                         case 289 /* ShorthandPropertyAssignment */:
49842                             if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 216 /* BinaryExpression */) {
49843                                 // module.exports = { SomeClass }
49844                                 serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), targetName);
49845                             }
49846                             break;
49847                         case 249 /* VariableDeclaration */:
49848                             // commonjs require: const x = require('y')
49849                             if (ts.isPropertyAccessExpression(node.initializer)) {
49850                                 // const x = require('y').z
49851                                 var initializer = node.initializer; // require('y').z
49852                                 var uniqueName = ts.factory.createUniqueName(localName); // _x
49853                                 var specifier_2 = getSpecifierForModuleSymbol(target.parent || target, context); // 'y'
49854                                 // import _x = require('y');
49855                                 addResult(ts.factory.createImportEqualsDeclaration(
49856                                 /*decorators*/ undefined, 
49857                                 /*modifiers*/ undefined, 
49858                                 /*isTypeOnly*/ false, uniqueName, ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(specifier_2))), 0 /* None */);
49859                                 // import x = _x.z
49860                                 addResult(ts.factory.createImportEqualsDeclaration(
49861                                 /*decorators*/ undefined, 
49862                                 /*modifiers*/ undefined, 
49863                                 /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), ts.factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags);
49864                                 break;
49865                             }
49866                         // else fall through and treat commonjs require just like import=
49867                         case 260 /* ImportEqualsDeclaration */:
49868                             // This _specifically_ only exists to handle json declarations - where we make aliases, but since
49869                             // we emit no declarations for the json document, must not refer to it in the declarations
49870                             if (target.escapedName === "export=" /* ExportEquals */ && ts.some(target.declarations, ts.isJsonSourceFile)) {
49871                                 serializeMaybeAliasAssignment(symbol);
49872                                 break;
49873                             }
49874                             // Could be a local `import localName = ns.member` or
49875                             // an external `import localName = require("whatever")`
49876                             var isLocalImport = !(target.flags & 512 /* ValueModule */) && !ts.isVariableDeclaration(node);
49877                             addResult(ts.factory.createImportEqualsDeclaration(
49878                             /*decorators*/ undefined, 
49879                             /*modifiers*/ undefined, 
49880                             /*isTypeOnly*/ false, ts.factory.createIdentifier(localName), isLocalImport
49881                                 ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)
49882                                 : ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))), isLocalImport ? modifierFlags : 0 /* None */);
49883                             break;
49884                         case 259 /* NamespaceExportDeclaration */:
49885                             // export as namespace foo
49886                             // TODO: Not part of a file's local or export symbol tables
49887                             // Is bound into file.symbol.globalExports instead, which we don't currently traverse
49888                             addResult(ts.factory.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */);
49889                             break;
49890                         case 262 /* ImportClause */:
49891                             addResult(ts.factory.createImportDeclaration(
49892                             /*decorators*/ undefined, 
49893                             /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), 
49894                             // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned
49895                             // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag
49896                             // In such cases, the `target` refers to the module itself already
49897                             ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
49898                             break;
49899                         case 263 /* NamespaceImport */:
49900                             addResult(ts.factory.createImportDeclaration(
49901                             /*decorators*/ undefined, 
49902                             /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
49903                             break;
49904                         case 269 /* NamespaceExport */:
49905                             addResult(ts.factory.createExportDeclaration(
49906                             /*decorators*/ undefined, 
49907                             /*modifiers*/ undefined, 
49908                             /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
49909                             break;
49910                         case 265 /* ImportSpecifier */:
49911                             addResult(ts.factory.createImportDeclaration(
49912                             /*decorators*/ undefined, 
49913                             /*modifiers*/ undefined, ts.factory.createImportClause(
49914                             /*isTypeOnly*/ false, 
49915                             /*importClause*/ undefined, ts.factory.createNamedImports([
49916                                 ts.factory.createImportSpecifier(localName !== verbatimTargetName ? ts.factory.createIdentifier(verbatimTargetName) : undefined, ts.factory.createIdentifier(localName))
49917                             ])), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
49918                             break;
49919                         case 270 /* ExportSpecifier */:
49920                             // does not use localName because the symbol name in this case refers to the name in the exports table,
49921                             // which we must exactly preserve
49922                             var specifier = node.parent.parent.moduleSpecifier;
49923                             // targetName is only used when the target is local, as otherwise the target is an alias that points at
49924                             // another file
49925                             serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.factory.createStringLiteral(specifier.text) : undefined);
49926                             break;
49927                         case 266 /* ExportAssignment */:
49928                             serializeMaybeAliasAssignment(symbol);
49929                             break;
49930                         case 216 /* BinaryExpression */:
49931                         case 201 /* PropertyAccessExpression */:
49932                         case 202 /* ElementAccessExpression */:
49933                             // Could be best encoded as though an export specifier or as though an export assignment
49934                             // If name is default or export=, do an export assignment
49935                             // Otherwise do an export specifier
49936                             if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */) {
49937                                 serializeMaybeAliasAssignment(symbol);
49938                             }
49939                             else {
49940                                 serializeExportSpecifier(localName, targetName);
49941                             }
49942                             break;
49943                         default:
49944                             return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!");
49945                     }
49946                 }
49947                 function serializeExportSpecifier(localName, targetName, specifier) {
49948                     addResult(ts.factory.createExportDeclaration(
49949                     /*decorators*/ undefined, 
49950                     /*modifiers*/ undefined, 
49951                     /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* None */);
49952                 }
49953                 /**
49954                  * Returns `true` if an export assignment or declaration was produced for the symbol
49955                  */
49956                 function serializeMaybeAliasAssignment(symbol) {
49957                     if (symbol.flags & 4194304 /* Prototype */) {
49958                         return false;
49959                     }
49960                     var name = ts.unescapeLeadingUnderscores(symbol.escapedName);
49961                     var isExportEquals = name === "export=" /* ExportEquals */;
49962                     var isDefault = name === "default" /* Default */;
49963                     var isExportAssignmentCompatibleSymbolName = isExportEquals || isDefault;
49964                     // synthesize export = ref
49965                     // ref should refer to either be a locally scoped symbol which we need to emit, or
49966                     // a reference to another namespace/module which we may need to emit an `import` statement for
49967                     var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol);
49968                     // serialize what the alias points to, preserve the declaration's initializer
49969                     var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
49970                     // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const
49971                     if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) {
49972                         // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it
49973                         // eg, `namespace A { export class B {} }; exports = A.B;`
49974                         // Technically, this is all that's required in the case where the assignment is an entity name expression
49975                         var expr = aliasDecl && ((ts.isExportAssignment(aliasDecl) || ts.isBinaryExpression(aliasDecl)) ? ts.getExportAssignmentExpression(aliasDecl) : ts.getPropertyAssignmentAliasLikeExpression(aliasDecl));
49976                         var first_1 = expr && ts.isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : undefined;
49977                         var referenced = first_1 && resolveEntityName(first_1, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, enclosingDeclaration);
49978                         if (referenced || target) {
49979                             includePrivateSymbol(referenced || target);
49980                         }
49981                         // We disable the context's symbol tracker for the duration of this name serialization
49982                         // as, by virtue of being here, the name is required to print something, and we don't want to
49983                         // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue
49984                         // a visibility error here (as they're not visible within any scope), but we want to hoist them
49985                         // into the containing scope anyway, so we want to skip the visibility checks.
49986                         var oldTrack = context.tracker.trackSymbol;
49987                         context.tracker.trackSymbol = ts.noop;
49988                         if (isExportAssignmentCompatibleSymbolName) {
49989                             results.push(ts.factory.createExportAssignment(
49990                             /*decorators*/ undefined, 
49991                             /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* All */)));
49992                         }
49993                         else {
49994                             if (first_1 === expr && first_1) {
49995                                 // serialize as `export {target as name}`
49996                                 serializeExportSpecifier(name, ts.idText(first_1));
49997                             }
49998                             else if (expr && ts.isClassExpression(expr)) {
49999                                 serializeExportSpecifier(name, getInternalSymbolName(target, ts.symbolName(target)));
50000                             }
50001                             else {
50002                                 // serialize as `import _Ref = t.arg.et; export { _Ref as name }`
50003                                 var varName = getUnusedName(name, symbol);
50004                                 addResult(ts.factory.createImportEqualsDeclaration(
50005                                 /*decorators*/ undefined, 
50006                                 /*modifiers*/ undefined, 
50007                                 /*isTypeOnly*/ false, ts.factory.createIdentifier(varName), symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)), 0 /* None */);
50008                                 serializeExportSpecifier(name, varName);
50009                             }
50010                         }
50011                         context.tracker.trackSymbol = oldTrack;
50012                         return true;
50013                     }
50014                     else {
50015                         // serialize as an anonymous property declaration
50016                         var varName = getUnusedName(name, symbol);
50017                         // We have to use `getWidenedType` here since the object within a json file is unwidened within the file
50018                         // (Unwidened types can only exist in expression contexts and should never be serialized)
50019                         var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol)));
50020                         if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) {
50021                             // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const
50022                             serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignmentCompatibleSymbolName ? 0 /* None */ : 1 /* Export */);
50023                         }
50024                         else {
50025                             var statement = ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([
50026                                 ts.factory.createVariableDeclaration(varName, /*exclamationToken*/ undefined, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
50027                             ], 2 /* Const */));
50028                             // Inlined JSON types exported with [module.]exports= will already emit an export=, so should use `declare`.
50029                             // Otherwise, the type itself should be exported.
50030                             addResult(statement, target && target.flags & 4 /* Property */ && target.escapedName === "export=" /* ExportEquals */ ? 2 /* Ambient */
50031                                 : name === varName ? 1 /* Export */
50032                                     : 0 /* None */);
50033                         }
50034                         if (isExportAssignmentCompatibleSymbolName) {
50035                             results.push(ts.factory.createExportAssignment(
50036                             /*decorators*/ undefined, 
50037                             /*modifiers*/ undefined, isExportEquals, ts.factory.createIdentifier(varName)));
50038                             return true;
50039                         }
50040                         else if (name !== varName) {
50041                             serializeExportSpecifier(name, varName);
50042                             return true;
50043                         }
50044                         return false;
50045                     }
50046                 }
50047                 function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) {
50048                     // Only object types which are not constructable, or indexable, whose members all come from the
50049                     // context source file, and whose property names are all valid identifiers and not late-bound, _and_
50050                     // whose input is not type annotated (if the input symbol has an annotation we can reuse, we should prefer it)
50051                     var ctxSrc = ts.getSourceFileOfNode(context.enclosingDeclaration);
50052                     return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) &&
50053                         !getIndexInfoOfType(typeToSerialize, 0 /* String */) &&
50054                         !getIndexInfoOfType(typeToSerialize, 1 /* Number */) &&
50055                         !isClassInstanceSide(typeToSerialize) && // While a class instance is potentially representable as a NS, prefer printing a reference to the instance type and serializing the class
50056                         !!(ts.length(ts.filter(getPropertiesOfType(typeToSerialize), isNamespaceMember)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) &&
50057                         !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK
50058                         !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) &&
50059                         !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) &&
50060                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) &&
50061                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) &&
50062                         ts.every(getPropertiesOfType(typeToSerialize), function (p) { return ts.isIdentifierText(ts.symbolName(p), languageVersion); });
50063                 }
50064                 function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) {
50065                     return function serializePropertySymbol(p, isStatic, baseType) {
50066                         var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p);
50067                         var isPrivate = !!(modifierFlags & 8 /* Private */);
50068                         if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) {
50069                             // Only value-only-meaning symbols can be correctly encoded as class statics, type/namespace/alias meaning symbols
50070                             // need to be merged namespace members
50071                             return [];
50072                         }
50073                         if (p.flags & 4194304 /* Prototype */ ||
50074                             (baseType && getPropertyOfType(baseType, p.escapedName)
50075                                 && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p)
50076                                 && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */)
50077                                 && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) {
50078                             return [];
50079                         }
50080                         var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0);
50081                         var name = getPropertyNameNodeForSymbol(p, context);
50082                         var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression));
50083                         if (p.flags & 98304 /* Accessor */ && useAccessors) {
50084                             var result = [];
50085                             if (p.flags & 65536 /* SetAccessor */) {
50086                                 result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration(
50087                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration(
50088                                     /*decorators*/ undefined, 
50089                                     /*modifiers*/ undefined, 
50090                                     /*dotDotDotToken*/ undefined, "arg", 
50091                                     /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], 
50092                                 /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl));
50093                             }
50094                             if (p.flags & 32768 /* GetAccessor */) {
50095                                 var isPrivate_1 = modifierFlags & 8 /* Private */;
50096                                 result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration(
50097                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), 
50098                                 /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl));
50099                             }
50100                             return result;
50101                         }
50102                         // This is an else/if as accessors and properties can't merge in TS, but might in JS
50103                         // If this happens, we assume the accessor takes priority, as it imposes more constraints
50104                         else if (p.flags & (4 /* Property */ | 3 /* Variable */ | 98304 /* Accessor */)) {
50105                             return ts.setTextRange(createProperty(
50106                             /*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), 
50107                             // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357
50108                             // interface members can't have initializers, however class members _can_
50109                             /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl);
50110                         }
50111                         if (p.flags & (8192 /* Method */ | 16 /* Function */)) {
50112                             var type = getTypeOfSymbol(p);
50113                             var signatures = getSignaturesOfType(type, 0 /* Call */);
50114                             if (flag & 8 /* Private */) {
50115                                 return ts.setTextRange(createProperty(
50116                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, 
50117                                 /*type*/ undefined, 
50118                                 /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]);
50119                             }
50120                             var results_1 = [];
50121                             for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) {
50122                                 var sig = signatures_3[_i];
50123                                 // Each overload becomes a separate method declaration, in order
50124                                 var decl = signatureToSignatureDeclarationHelper(sig, methodKind, context, {
50125                                     name: name,
50126                                     questionToken: p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined,
50127                                     modifiers: flag ? ts.factory.createModifiersFromModifierFlags(flag) : undefined
50128                                 });
50129                                 results_1.push(ts.setTextRange(decl, sig.declaration));
50130                             }
50131                             return results_1;
50132                         }
50133                         // The `Constructor`'s symbol isn't in the class's properties lists, obviously, since it's a signature on the static
50134                         return ts.Debug.fail("Unhandled class member kind! " + (p.__debugFlags || p.flags));
50135                     };
50136                 }
50137                 function serializePropertySymbolForInterface(p, baseType) {
50138                     return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType);
50139                 }
50140                 function serializeSignatures(kind, input, baseType, outputKind) {
50141                     var signatures = getSignaturesOfType(input, kind);
50142                     if (kind === 1 /* Construct */) {
50143                         if (!baseType && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
50144                             return []; // No base type, every constructor is empty - elide the extraneous `constructor()`
50145                         }
50146                         if (baseType) {
50147                             // If there is a base type, if every signature in the class is identical to a signature in the baseType, elide all the declarations
50148                             var baseSigs = getSignaturesOfType(baseType, 1 /* Construct */);
50149                             if (!ts.length(baseSigs) && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
50150                                 return []; // Base had no explicit signatures, if all our signatures are also implicit, return an empty list
50151                             }
50152                             if (baseSigs.length === signatures.length) {
50153                                 var failed = false;
50154                                 for (var i = 0; i < baseSigs.length; i++) {
50155                                     if (!compareSignaturesIdentical(signatures[i], baseSigs[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
50156                                         failed = true;
50157                                         break;
50158                                     }
50159                                 }
50160                                 if (!failed) {
50161                                     return []; // Every signature was identical - elide constructor list as it is inherited
50162                                 }
50163                             }
50164                         }
50165                         var privateProtected = 0;
50166                         for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) {
50167                             var s = signatures_4[_i];
50168                             if (s.declaration) {
50169                                 privateProtected |= ts.getSelectedEffectiveModifierFlags(s.declaration, 8 /* Private */ | 16 /* Protected */);
50170                             }
50171                         }
50172                         if (privateProtected) {
50173                             return [ts.setTextRange(ts.factory.createConstructorDeclaration(
50174                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(privateProtected), 
50175                                 /*parameters*/ [], 
50176                                 /*body*/ undefined), signatures[0].declaration)];
50177                         }
50178                     }
50179                     var results = [];
50180                     for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) {
50181                         var sig = signatures_5[_a];
50182                         // Each overload becomes a separate constructor declaration, in order
50183                         var decl = signatureToSignatureDeclarationHelper(sig, outputKind, context);
50184                         results.push(ts.setTextRange(decl, sig.declaration));
50185                     }
50186                     return results;
50187                 }
50188                 function serializeIndexSignatures(input, baseType) {
50189                     var results = [];
50190                     for (var _i = 0, _a = [0 /* String */, 1 /* Number */]; _i < _a.length; _i++) {
50191                         var type = _a[_i];
50192                         var info = getIndexInfoOfType(input, type);
50193                         if (info) {
50194                             if (baseType) {
50195                                 var baseInfo = getIndexInfoOfType(baseType, type);
50196                                 if (baseInfo) {
50197                                     if (isTypeIdenticalTo(info.type, baseInfo.type)) {
50198                                         continue; // elide identical index signatures
50199                                     }
50200                                 }
50201                             }
50202                             results.push(indexInfoToIndexSignatureDeclarationHelper(info, type, context, /*typeNode*/ undefined));
50203                         }
50204                     }
50205                     return results;
50206                 }
50207                 function serializeBaseType(t, staticType, rootName) {
50208                     var ref = trySerializeAsTypeReference(t, 111551 /* Value */);
50209                     if (ref) {
50210                         return ref;
50211                     }
50212                     var tempName = getUnusedName(rootName + "_base");
50213                     var statement = ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([
50214                         ts.factory.createVariableDeclaration(tempName, /*exclamationToken*/ undefined, typeToTypeNodeHelper(staticType, context))
50215                     ], 2 /* Const */));
50216                     addResult(statement, 0 /* None */);
50217                     return ts.factory.createExpressionWithTypeArguments(ts.factory.createIdentifier(tempName), /*typeArgs*/ undefined);
50218                 }
50219                 function trySerializeAsTypeReference(t, flags) {
50220                     var typeArgs;
50221                     var reference;
50222                     // We don't use `isValueSymbolAccessible` below. since that considers alternative containers (like modules)
50223                     // which we can't write out in a syntactically valid way as an expression
50224                     if (t.target && isSymbolAccessibleByFlags(t.target.symbol, enclosingDeclaration, flags)) {
50225                         typeArgs = ts.map(getTypeArguments(t), function (t) { return typeToTypeNodeHelper(t, context); });
50226                         reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */);
50227                     }
50228                     else if (t.symbol && isSymbolAccessibleByFlags(t.symbol, enclosingDeclaration, flags)) {
50229                         reference = symbolToExpression(t.symbol, context, 788968 /* Type */);
50230                     }
50231                     if (reference) {
50232                         return ts.factory.createExpressionWithTypeArguments(reference, typeArgs);
50233                     }
50234                 }
50235                 function serializeImplementedType(t) {
50236                     var ref = trySerializeAsTypeReference(t, 788968 /* Type */);
50237                     if (ref) {
50238                         return ref;
50239                     }
50240                     if (t.symbol) {
50241                         return ts.factory.createExpressionWithTypeArguments(symbolToExpression(t.symbol, context, 788968 /* Type */), /*typeArgs*/ undefined);
50242                     }
50243                 }
50244                 function getUnusedName(input, symbol) {
50245                     var _a, _b;
50246                     var id = symbol ? getSymbolId(symbol) : undefined;
50247                     if (id) {
50248                         if (context.remappedSymbolNames.has(id)) {
50249                             return context.remappedSymbolNames.get(id);
50250                         }
50251                     }
50252                     if (symbol) {
50253                         input = getNameCandidateWorker(symbol, input);
50254                     }
50255                     var i = 0;
50256                     var original = input;
50257                     while ((_a = context.usedSymbolNames) === null || _a === void 0 ? void 0 : _a.has(input)) {
50258                         i++;
50259                         input = original + "_" + i;
50260                     }
50261                     (_b = context.usedSymbolNames) === null || _b === void 0 ? void 0 : _b.add(input);
50262                     if (id) {
50263                         context.remappedSymbolNames.set(id, input);
50264                     }
50265                     return input;
50266                 }
50267                 function getNameCandidateWorker(symbol, localName) {
50268                     if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) {
50269                         var flags = context.flags;
50270                         context.flags |= 16777216 /* InInitialEntityName */;
50271                         var nameCandidate = getNameOfSymbolAsWritten(symbol, context);
50272                         context.flags = flags;
50273                         localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate;
50274                     }
50275                     if (localName === "default" /* Default */) {
50276                         localName = "_default";
50277                     }
50278                     else if (localName === "export=" /* ExportEquals */) {
50279                         localName = "_exports";
50280                     }
50281                     localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_");
50282                     return localName;
50283                 }
50284                 function getInternalSymbolName(symbol, localName) {
50285                     var id = getSymbolId(symbol);
50286                     if (context.remappedSymbolNames.has(id)) {
50287                         return context.remappedSymbolNames.get(id);
50288                     }
50289                     localName = getNameCandidateWorker(symbol, localName);
50290                     // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up
50291                     context.remappedSymbolNames.set(id, localName);
50292                     return localName;
50293                 }
50294             }
50295         }
50296         function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) {
50297             if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
50298             return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
50299             function typePredicateToStringWorker(writer) {
50300                 var predicate = ts.factory.createTypePredicateNode(typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? ts.factory.createToken(127 /* AssertsKeyword */) : undefined, typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? ts.factory.createIdentifier(typePredicate.parameterName) : ts.factory.createThisTypeNode(), typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */) // TODO: GH#18217
50301                 );
50302                 var printer = ts.createPrinter({ removeComments: true });
50303                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
50304                 printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
50305                 return writer;
50306             }
50307         }
50308         function formatUnionTypes(types) {
50309             var result = [];
50310             var flags = 0;
50311             for (var i = 0; i < types.length; i++) {
50312                 var t = types[i];
50313                 flags |= t.flags;
50314                 if (!(t.flags & 98304 /* Nullable */)) {
50315                     if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) {
50316                         var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t);
50317                         if (baseType.flags & 1048576 /* Union */) {
50318                             var count = baseType.types.length;
50319                             if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
50320                                 result.push(baseType);
50321                                 i += count - 1;
50322                                 continue;
50323                             }
50324                         }
50325                     }
50326                     result.push(t);
50327                 }
50328             }
50329             if (flags & 65536 /* Null */)
50330                 result.push(nullType);
50331             if (flags & 32768 /* Undefined */)
50332                 result.push(undefinedType);
50333             return result || types;
50334         }
50335         function visibilityToString(flags) {
50336             if (flags === 8 /* Private */) {
50337                 return "private";
50338             }
50339             if (flags === 16 /* Protected */) {
50340                 return "protected";
50341             }
50342             return "public";
50343         }
50344         function getTypeAliasForTypeLiteral(type) {
50345             if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) {
50346                 var node = ts.walkUpParenthesizedTypes(type.symbol.declarations[0].parent);
50347                 if (node.kind === 254 /* TypeAliasDeclaration */) {
50348                     return getSymbolOfNode(node);
50349                 }
50350             }
50351             return undefined;
50352         }
50353         function isTopLevelInExternalModuleAugmentation(node) {
50354             return node && node.parent &&
50355                 node.parent.kind === 257 /* ModuleBlock */ &&
50356                 ts.isExternalModuleAugmentation(node.parent.parent);
50357         }
50358         function isDefaultBindingContext(location) {
50359             return location.kind === 297 /* SourceFile */ || ts.isAmbientModule(location);
50360         }
50361         function getNameOfSymbolFromNameType(symbol, context) {
50362             var nameType = getSymbolLinks(symbol).nameType;
50363             if (nameType) {
50364                 if (nameType.flags & 384 /* StringOrNumberLiteral */) {
50365                     var name = "" + nameType.value;
50366                     if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
50367                         return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\"";
50368                     }
50369                     if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
50370                         return "[" + name + "]";
50371                     }
50372                     return name;
50373                 }
50374                 if (nameType.flags & 8192 /* UniqueESSymbol */) {
50375                     return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]";
50376                 }
50377             }
50378         }
50379         /**
50380          * Gets a human-readable name for a symbol.
50381          * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
50382          *
50383          * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal.
50384          * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
50385          */
50386         function getNameOfSymbolAsWritten(symbol, context) {
50387             if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) &&
50388                 // If it's not the first part of an entity name, it must print as `default`
50389                 (!(context.flags & 16777216 /* InInitialEntityName */) ||
50390                     // if the symbol is synthesized, it will only be referenced externally it must print as `default`
50391                     !symbol.declarations ||
50392                     // if not in the same binding context (source file, module declaration), it must print as `default`
50393                     (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) {
50394                 return "default";
50395             }
50396             if (symbol.declarations && symbol.declarations.length) {
50397                 var declaration = ts.firstDefined(symbol.declarations, function (d) { return ts.getNameOfDeclaration(d) ? d : undefined; }); // Try using a declaration with a name, first
50398                 var name_3 = declaration && ts.getNameOfDeclaration(declaration);
50399                 if (declaration && name_3) {
50400                     if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
50401                         return ts.symbolName(symbol);
50402                     }
50403                     if (ts.isComputedPropertyName(name_3) && !(ts.getCheckFlags(symbol) & 4096 /* Late */)) {
50404                         var nameType = getSymbolLinks(symbol).nameType;
50405                         if (nameType && nameType.flags & 384 /* StringOrNumberLiteral */) {
50406                             // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name
50407                             var result = getNameOfSymbolFromNameType(symbol, context);
50408                             if (result !== undefined) {
50409                                 return result;
50410                             }
50411                         }
50412                     }
50413                     return ts.declarationNameToString(name_3);
50414                 }
50415                 if (!declaration) {
50416                     declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway
50417                 }
50418                 if (declaration.parent && declaration.parent.kind === 249 /* VariableDeclaration */) {
50419                     return ts.declarationNameToString(declaration.parent.name);
50420                 }
50421                 switch (declaration.kind) {
50422                     case 221 /* ClassExpression */:
50423                     case 208 /* FunctionExpression */:
50424                     case 209 /* ArrowFunction */:
50425                         if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
50426                             context.encounteredError = true;
50427                         }
50428                         return declaration.kind === 221 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
50429                 }
50430             }
50431             var name = getNameOfSymbolFromNameType(symbol, context);
50432             return name !== undefined ? name : ts.symbolName(symbol);
50433         }
50434         function isDeclarationVisible(node) {
50435             if (node) {
50436                 var links = getNodeLinks(node);
50437                 if (links.isVisible === undefined) {
50438                     links.isVisible = !!determineIfDeclarationIsVisible();
50439                 }
50440                 return links.isVisible;
50441             }
50442             return false;
50443             function determineIfDeclarationIsVisible() {
50444                 switch (node.kind) {
50445                     case 324 /* JSDocCallbackTag */:
50446                     case 331 /* JSDocTypedefTag */:
50447                     case 325 /* JSDocEnumTag */:
50448                         // Top-level jsdoc type aliases are considered exported
50449                         // 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
50450                         return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
50451                     case 198 /* BindingElement */:
50452                         return isDeclarationVisible(node.parent.parent);
50453                     case 249 /* VariableDeclaration */:
50454                         if (ts.isBindingPattern(node.name) &&
50455                             !node.name.elements.length) {
50456                             // If the binding pattern is empty, this variable declaration is not visible
50457                             return false;
50458                         }
50459                     // falls through
50460                     case 256 /* ModuleDeclaration */:
50461                     case 252 /* ClassDeclaration */:
50462                     case 253 /* InterfaceDeclaration */:
50463                     case 254 /* TypeAliasDeclaration */:
50464                     case 251 /* FunctionDeclaration */:
50465                     case 255 /* EnumDeclaration */:
50466                     case 260 /* ImportEqualsDeclaration */:
50467                         // external module augmentation is always visible
50468                         if (ts.isExternalModuleAugmentation(node)) {
50469                             return true;
50470                         }
50471                         var parent = getDeclarationContainer(node);
50472                         // If the node is not exported or it is not ambient module element (except import declaration)
50473                         if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
50474                             !(node.kind !== 260 /* ImportEqualsDeclaration */ && parent.kind !== 297 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) {
50475                             return isGlobalSourceFile(parent);
50476                         }
50477                         // Exported members/ambient module elements (exception import declaration) are visible if parent is visible
50478                         return isDeclarationVisible(parent);
50479                     case 163 /* PropertyDeclaration */:
50480                     case 162 /* PropertySignature */:
50481                     case 167 /* GetAccessor */:
50482                     case 168 /* SetAccessor */:
50483                     case 165 /* MethodDeclaration */:
50484                     case 164 /* MethodSignature */:
50485                         if (ts.hasEffectiveModifier(node, 8 /* Private */ | 16 /* Protected */)) {
50486                             // Private/protected properties/methods are not visible
50487                             return false;
50488                         }
50489                     // Public properties/methods are visible if its parents are visible, so:
50490                     // falls through
50491                     case 166 /* Constructor */:
50492                     case 170 /* ConstructSignature */:
50493                     case 169 /* CallSignature */:
50494                     case 171 /* IndexSignature */:
50495                     case 160 /* Parameter */:
50496                     case 257 /* ModuleBlock */:
50497                     case 174 /* FunctionType */:
50498                     case 175 /* ConstructorType */:
50499                     case 177 /* TypeLiteral */:
50500                     case 173 /* TypeReference */:
50501                     case 178 /* ArrayType */:
50502                     case 179 /* TupleType */:
50503                     case 182 /* UnionType */:
50504                     case 183 /* IntersectionType */:
50505                     case 186 /* ParenthesizedType */:
50506                     case 192 /* NamedTupleMember */:
50507                         return isDeclarationVisible(node.parent);
50508                     // Default binding, import specifier and namespace import is visible
50509                     // only on demand so by default it is not visible
50510                     case 262 /* ImportClause */:
50511                     case 263 /* NamespaceImport */:
50512                     case 265 /* ImportSpecifier */:
50513                         return false;
50514                     // Type parameters are always visible
50515                     case 159 /* TypeParameter */:
50516                     // Source file and namespace export are always visible
50517                     // falls through
50518                     case 297 /* SourceFile */:
50519                     case 259 /* NamespaceExportDeclaration */:
50520                         return true;
50521                     // Export assignments do not create name bindings outside the module
50522                     case 266 /* ExportAssignment */:
50523                         return false;
50524                     default:
50525                         return false;
50526                 }
50527             }
50528         }
50529         function collectLinkedAliases(node, setVisibility) {
50530             var exportSymbol;
50531             if (node.parent && node.parent.kind === 266 /* ExportAssignment */) {
50532                 exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
50533             }
50534             else if (node.parent.kind === 270 /* ExportSpecifier */) {
50535                 exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
50536             }
50537             var result;
50538             var visited;
50539             if (exportSymbol) {
50540                 visited = new ts.Set();
50541                 visited.add(getSymbolId(exportSymbol));
50542                 buildVisibleNodeList(exportSymbol.declarations);
50543             }
50544             return result;
50545             function buildVisibleNodeList(declarations) {
50546                 ts.forEach(declarations, function (declaration) {
50547                     var resultNode = getAnyImportSyntax(declaration) || declaration;
50548                     if (setVisibility) {
50549                         getNodeLinks(declaration).isVisible = true;
50550                     }
50551                     else {
50552                         result = result || [];
50553                         ts.pushIfUnique(result, resultNode);
50554                     }
50555                     if (ts.isInternalModuleImportEqualsDeclaration(declaration)) {
50556                         // Add the referenced top container visible
50557                         var internalModuleReference = declaration.moduleReference;
50558                         var firstIdentifier = ts.getFirstIdentifier(internalModuleReference);
50559                         var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
50560                         if (importSymbol && visited) {
50561                             if (ts.tryAddToSet(visited, getSymbolId(importSymbol))) {
50562                                 buildVisibleNodeList(importSymbol.declarations);
50563                             }
50564                         }
50565                     }
50566                 });
50567             }
50568         }
50569         /**
50570          * Push an entry on the type resolution stack. If an entry with the given target and the given property name
50571          * is already on the stack, and no entries in between already have a type, then a circularity has occurred.
50572          * In this case, the result values of the existing entry and all entries pushed after it are changed to false,
50573          * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned.
50574          * In order to see if the same query has already been done before, the target object and the propertyName both
50575          * must match the one passed in.
50576          *
50577          * @param target The symbol, type, or signature whose type is being queried
50578          * @param propertyName The property name that should be used to query the target for its type
50579          */
50580         function pushTypeResolution(target, propertyName) {
50581             var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
50582             if (resolutionCycleStartIndex >= 0) {
50583                 // A cycle was found
50584                 var length_3 = resolutionTargets.length;
50585                 for (var i = resolutionCycleStartIndex; i < length_3; i++) {
50586                     resolutionResults[i] = false;
50587                 }
50588                 return false;
50589             }
50590             resolutionTargets.push(target);
50591             resolutionResults.push(/*items*/ true);
50592             resolutionPropertyNames.push(propertyName);
50593             return true;
50594         }
50595         function findResolutionCycleStartIndex(target, propertyName) {
50596             for (var i = resolutionTargets.length - 1; i >= 0; i--) {
50597                 if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) {
50598                     return -1;
50599                 }
50600                 if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
50601                     return i;
50602                 }
50603             }
50604             return -1;
50605         }
50606         function hasType(target, propertyName) {
50607             switch (propertyName) {
50608                 case 0 /* Type */:
50609                     return !!getSymbolLinks(target).type;
50610                 case 5 /* EnumTagType */:
50611                     return !!(getNodeLinks(target).resolvedEnumType);
50612                 case 2 /* DeclaredType */:
50613                     return !!getSymbolLinks(target).declaredType;
50614                 case 1 /* ResolvedBaseConstructorType */:
50615                     return !!target.resolvedBaseConstructorType;
50616                 case 3 /* ResolvedReturnType */:
50617                     return !!target.resolvedReturnType;
50618                 case 4 /* ImmediateBaseConstraint */:
50619                     return !!target.immediateBaseConstraint;
50620                 case 6 /* ResolvedTypeArguments */:
50621                     return !!target.resolvedTypeArguments;
50622                 case 7 /* ResolvedBaseTypes */:
50623                     return !!target.baseTypesResolved;
50624             }
50625             return ts.Debug.assertNever(propertyName);
50626         }
50627         /**
50628          * Pop an entry from the type resolution stack and return its associated result value. The result value will
50629          * be true if no circularities were detected, or false if a circularity was found.
50630          */
50631         function popTypeResolution() {
50632             resolutionTargets.pop();
50633             resolutionPropertyNames.pop();
50634             return resolutionResults.pop();
50635         }
50636         function getDeclarationContainer(node) {
50637             return ts.findAncestor(ts.getRootDeclaration(node), function (node) {
50638                 switch (node.kind) {
50639                     case 249 /* VariableDeclaration */:
50640                     case 250 /* VariableDeclarationList */:
50641                     case 265 /* ImportSpecifier */:
50642                     case 264 /* NamedImports */:
50643                     case 263 /* NamespaceImport */:
50644                     case 262 /* ImportClause */:
50645                         return false;
50646                     default:
50647                         return true;
50648                 }
50649             }).parent;
50650         }
50651         function getTypeOfPrototypeProperty(prototype) {
50652             // TypeScript 1.0 spec (April 2014): 8.4
50653             // Every class automatically contains a static property member named 'prototype',
50654             // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
50655             // It is an error to explicitly declare a static property member with the name 'prototype'.
50656             var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
50657             return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType;
50658         }
50659         // Return the type of the given property in the given type, or undefined if no such property exists
50660         function getTypeOfPropertyOfType(type, name) {
50661             var prop = getPropertyOfType(type, name);
50662             return prop ? getTypeOfSymbol(prop) : undefined;
50663         }
50664         function getTypeOfPropertyOrIndexSignature(type, name) {
50665             return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType;
50666         }
50667         function isTypeAny(type) {
50668             return type && (type.flags & 1 /* Any */) !== 0;
50669         }
50670         // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been
50671         // assigned by contextual typing.
50672         function getTypeForBindingElementParent(node) {
50673             var symbol = getSymbolOfNode(node);
50674             return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
50675         }
50676         function getRestType(source, properties, symbol) {
50677             source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); });
50678             if (source.flags & 131072 /* Never */) {
50679                 return emptyObjectType;
50680             }
50681             if (source.flags & 1048576 /* Union */) {
50682                 return mapType(source, function (t) { return getRestType(t, properties, symbol); });
50683             }
50684             var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName));
50685             if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
50686                 if (omitKeyType.flags & 131072 /* Never */) {
50687                     return source;
50688                 }
50689                 var omitTypeAlias = getGlobalOmitSymbol();
50690                 if (!omitTypeAlias) {
50691                     return errorType;
50692                 }
50693                 return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]);
50694             }
50695             var members = ts.createSymbolTable();
50696             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
50697                 var prop = _a[_i];
50698                 if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
50699                     && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
50700                     && isSpreadableProperty(prop)) {
50701                     members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
50702                 }
50703             }
50704             var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
50705             var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */);
50706             var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
50707             result.objectFlags |= 131072 /* ObjectRestType */;
50708             return result;
50709         }
50710         // Determine the control flow type associated with a destructuring declaration or assignment. The following
50711         // forms of destructuring are possible:
50712         //   let { x } = obj;  // BindingElement
50713         //   let [ x ] = obj;  // BindingElement
50714         //   { x } = obj;      // ShorthandPropertyAssignment
50715         //   { x: v } = obj;   // PropertyAssignment
50716         //   [ x ] = obj;      // Expression
50717         // We construct a synthetic element access expression corresponding to 'obj.x' such that the control
50718         // flow analyzer doesn't have to handle all the different syntactic forms.
50719         function getFlowTypeOfDestructuring(node, declaredType) {
50720             var reference = getSyntheticElementAccess(node);
50721             return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
50722         }
50723         function getSyntheticElementAccess(node) {
50724             var parentAccess = getParentElementAccess(node);
50725             if (parentAccess && parentAccess.flowNode) {
50726                 var propName = getDestructuringPropertyName(node);
50727                 if (propName) {
50728                     var literal = ts.setTextRange(ts.parseNodeFactory.createStringLiteral(propName), node);
50729                     var lhsExpr = ts.isLeftHandSideExpression(parentAccess) ? parentAccess : ts.parseNodeFactory.createParenthesizedExpression(parentAccess);
50730                     var result = ts.setTextRange(ts.parseNodeFactory.createElementAccessExpression(lhsExpr, literal), node);
50731                     ts.setParent(literal, result);
50732                     ts.setParent(result, node);
50733                     if (lhsExpr !== parentAccess) {
50734                         ts.setParent(lhsExpr, result);
50735                     }
50736                     result.flowNode = parentAccess.flowNode;
50737                     return result;
50738                 }
50739             }
50740         }
50741         function getParentElementAccess(node) {
50742             var ancestor = node.parent.parent;
50743             switch (ancestor.kind) {
50744                 case 198 /* BindingElement */:
50745                 case 288 /* PropertyAssignment */:
50746                     return getSyntheticElementAccess(ancestor);
50747                 case 199 /* ArrayLiteralExpression */:
50748                     return getSyntheticElementAccess(node.parent);
50749                 case 249 /* VariableDeclaration */:
50750                     return ancestor.initializer;
50751                 case 216 /* BinaryExpression */:
50752                     return ancestor.right;
50753             }
50754         }
50755         function getDestructuringPropertyName(node) {
50756             var parent = node.parent;
50757             if (node.kind === 198 /* BindingElement */ && parent.kind === 196 /* ObjectBindingPattern */) {
50758                 return getLiteralPropertyNameText(node.propertyName || node.name);
50759             }
50760             if (node.kind === 288 /* PropertyAssignment */ || node.kind === 289 /* ShorthandPropertyAssignment */) {
50761                 return getLiteralPropertyNameText(node.name);
50762             }
50763             return "" + parent.elements.indexOf(node);
50764         }
50765         function getLiteralPropertyNameText(name) {
50766             var type = getLiteralTypeFromPropertyName(name);
50767             return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined;
50768         }
50769         /** Return the inferred type for a binding element */
50770         function getTypeForBindingElement(declaration) {
50771             var pattern = declaration.parent;
50772             var parentType = getTypeForBindingElementParent(pattern.parent);
50773             // If no type or an any type was inferred for parent, infer that for the binding element
50774             if (!parentType || isTypeAny(parentType)) {
50775                 return parentType;
50776             }
50777             // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
50778             if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) {
50779                 parentType = getNonNullableType(parentType);
50780             }
50781             // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined`
50782             else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) {
50783                 parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */);
50784             }
50785             var type;
50786             if (pattern.kind === 196 /* ObjectBindingPattern */) {
50787                 if (declaration.dotDotDotToken) {
50788                     parentType = getReducedType(parentType);
50789                     if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
50790                         error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types);
50791                         return errorType;
50792                     }
50793                     var literalMembers = [];
50794                     for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
50795                         var element = _a[_i];
50796                         if (!element.dotDotDotToken) {
50797                             literalMembers.push(element.propertyName || element.name);
50798                         }
50799                     }
50800                     type = getRestType(parentType, literalMembers, declaration.symbol);
50801                 }
50802                 else {
50803                     // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
50804                     var name = declaration.propertyName || declaration.name;
50805                     var indexType = getLiteralTypeFromPropertyName(name);
50806                     var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */), declaration.name);
50807                     type = getFlowTypeOfDestructuring(declaration, declaredType);
50808                 }
50809             }
50810             else {
50811                 // This elementType will be used if the specific property corresponding to this index is not
50812                 // present (aka the tuple element property). This call also checks that the parentType is in
50813                 // fact an iterable or array (depending on target language).
50814                 var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */ | (declaration.dotDotDotToken ? 0 : 128 /* PossiblyOutOfBounds */), parentType, undefinedType, pattern);
50815                 var index_2 = pattern.elements.indexOf(declaration);
50816                 if (declaration.dotDotDotToken) {
50817                     // If the parent is a tuple type, the rest element has a tuple type of the
50818                     // remaining tuple element types. Otherwise, the rest element has an array type with same
50819                     // element type as the parent type.
50820                     type = everyType(parentType, isTupleType) ?
50821                         mapType(parentType, function (t) { return sliceTupleType(t, index_2); }) :
50822                         createArrayType(elementType);
50823                 }
50824                 else if (isArrayLikeType(parentType)) {
50825                     var indexType = getLiteralType(index_2);
50826                     var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0;
50827                     var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | 16 /* ExpressionPosition */) || errorType, declaration.name);
50828                     type = getFlowTypeOfDestructuring(declaration, declaredType);
50829                 }
50830                 else {
50831                     type = elementType;
50832                 }
50833             }
50834             if (!declaration.initializer) {
50835                 return type;
50836             }
50837             if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) {
50838                 // In strict null checking mode, if a default value of a non-undefined type is specified, remove
50839                 // undefined from the final type.
50840                 return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ?
50841                     getTypeWithFacts(type, 524288 /* NEUndefined */) :
50842                     type;
50843             }
50844             return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */));
50845         }
50846         function getTypeForDeclarationFromJSDocComment(declaration) {
50847             var jsdocType = ts.getJSDocType(declaration);
50848             if (jsdocType) {
50849                 return getTypeFromTypeNode(jsdocType);
50850             }
50851             return undefined;
50852         }
50853         function isNullOrUndefined(node) {
50854             var expr = ts.skipParentheses(node);
50855             return expr.kind === 103 /* NullKeyword */ || expr.kind === 78 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
50856         }
50857         function isEmptyArrayLiteral(node) {
50858             var expr = ts.skipParentheses(node);
50859             return expr.kind === 199 /* ArrayLiteralExpression */ && expr.elements.length === 0;
50860         }
50861         function addOptionality(type, optional) {
50862             if (optional === void 0) { optional = true; }
50863             return strictNullChecks && optional ? getOptionalType(type) : type;
50864         }
50865         // Return the inferred type for a variable, parameter, or property declaration
50866         function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
50867             // A variable declared in a for..in statement is of type string, or of type keyof T when the
50868             // right hand expression is of a type parameter type.
50869             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 238 /* ForInStatement */) {
50870                 var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression)));
50871                 return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType;
50872             }
50873             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) {
50874                 // checkRightHandSideOfForOf will return undefined if the for-of expression type was
50875                 // missing properties/signatures required to get its iteratedType (like
50876                 // [Symbol.iterator] or next). This may be because we accessed properties from anyType,
50877                 // or it may have led to an error inside getElementTypeOfIterable.
50878                 var forOfStatement = declaration.parent.parent;
50879                 return checkRightHandSideOfForOf(forOfStatement) || anyType;
50880             }
50881             if (ts.isBindingPattern(declaration.parent)) {
50882                 return getTypeForBindingElement(declaration);
50883             }
50884             var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration)
50885                 || isOptionalJSDocPropertyLikeTag(declaration)
50886                 || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken);
50887             // Use type from type annotation if one is present
50888             var declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
50889             if (declaredType) {
50890                 return addOptionality(declaredType, isOptional);
50891             }
50892             if ((noImplicitAny || ts.isInJSFile(declaration)) &&
50893                 ts.isVariableDeclaration(declaration) && !ts.isBindingPattern(declaration.name) &&
50894                 !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 8388608 /* Ambient */)) {
50895                 // If --noImplicitAny is on or the declaration is in a Javascript file,
50896                 // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
50897                 // initializer or a 'null' or 'undefined' initializer.
50898                 if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
50899                     return autoType;
50900                 }
50901                 // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array
50902                 // literal initializer.
50903                 if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
50904                     return autoArrayType;
50905                 }
50906             }
50907             if (ts.isParameter(declaration)) {
50908                 var func = declaration.parent;
50909                 // For a parameter of a set accessor, use the type of the get accessor if one is present
50910                 if (func.kind === 168 /* SetAccessor */ && hasBindableName(func)) {
50911                     var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167 /* GetAccessor */);
50912                     if (getter) {
50913                         var getterSignature = getSignatureFromDeclaration(getter);
50914                         var thisParameter = getAccessorThisParameter(func);
50915                         if (thisParameter && declaration === thisParameter) {
50916                             // Use the type from the *getter*
50917                             ts.Debug.assert(!thisParameter.type);
50918                             return getTypeOfSymbol(getterSignature.thisParameter);
50919                         }
50920                         return getReturnTypeOfSignature(getterSignature);
50921                     }
50922                 }
50923                 if (ts.isInJSFile(declaration)) {
50924                     var typeTag = ts.getJSDocType(func);
50925                     if (typeTag && ts.isFunctionTypeNode(typeTag)) {
50926                         var signature = getSignatureFromDeclaration(typeTag);
50927                         var pos = func.parameters.indexOf(declaration);
50928                         return declaration.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos);
50929                     }
50930                 }
50931                 // Use contextual parameter type if one is available
50932                 var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
50933                 if (type) {
50934                     return addOptionality(type, isOptional);
50935                 }
50936             }
50937             // Use the type of the initializer expression if one is present and the declaration is
50938             // not a parameter of a contextually typed function
50939             if (ts.hasOnlyExpressionInitializer(declaration) && !!declaration.initializer) {
50940                 if (ts.isInJSFile(declaration) && !ts.isParameter(declaration)) {
50941                     var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration));
50942                     if (containerObjectType) {
50943                         return containerObjectType;
50944                     }
50945                 }
50946                 var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration));
50947                 return addOptionality(type, isOptional);
50948             }
50949             if (ts.isPropertyDeclaration(declaration) && !ts.hasStaticModifier(declaration) && (noImplicitAny || ts.isInJSFile(declaration))) {
50950                 // We have a property declaration with no type annotation or initializer, in noImplicitAny mode or a .js file.
50951                 // Use control flow analysis of this.xxx assignments in the constructor to determine the type of the property.
50952                 var constructor = findConstructorDeclaration(declaration.parent);
50953                 var type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) :
50954                     ts.getEffectiveModifierFlags(declaration) & 2 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) :
50955                         undefined;
50956                 return type && addOptionality(type, isOptional);
50957             }
50958             if (ts.isJsxAttribute(declaration)) {
50959                 // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true.
50960                 // I.e <Elem attr /> is sugar for <Elem attr={true} />
50961                 return trueType;
50962             }
50963             // If the declaration specifies a binding pattern and is not a parameter of a contextually
50964             // typed function, use the type implied by the binding pattern
50965             if (ts.isBindingPattern(declaration.name)) {
50966                 return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
50967             }
50968             // No type specified and nothing can be inferred
50969             return undefined;
50970         }
50971         function isConstructorDeclaredProperty(symbol) {
50972             // A property is considered a constructor declared property when all declaration sites are this.xxx assignments,
50973             // when no declaration sites have JSDoc type annotations, and when at least one declaration site is in the body of
50974             // a class constructor.
50975             if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration)) {
50976                 var links = getSymbolLinks(symbol);
50977                 if (links.isConstructorDeclaredProperty === undefined) {
50978                     links.isConstructorDeclaredProperty = false;
50979                     links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) {
50980                         return ts.isBinaryExpression(declaration) &&
50981                             isPossiblyAliasedThisProperty(declaration) &&
50982                             (declaration.left.kind !== 202 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) &&
50983                             !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration);
50984                     });
50985                 }
50986                 return links.isConstructorDeclaredProperty;
50987             }
50988             return false;
50989         }
50990         function isAutoTypedProperty(symbol) {
50991             // A property is auto-typed when its declaration has no type annotation or initializer and we're in
50992             // noImplicitAny mode or a .js file.
50993             var declaration = symbol.valueDeclaration;
50994             return declaration && ts.isPropertyDeclaration(declaration) && !ts.getEffectiveTypeAnnotationNode(declaration) &&
50995                 !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration));
50996         }
50997         function getDeclaringConstructor(symbol) {
50998             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
50999                 var declaration = _a[_i];
51000                 var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false);
51001                 if (container && (container.kind === 166 /* Constructor */ || isJSConstructor(container))) {
51002                     return container;
51003                 }
51004             }
51005         }
51006         function getFlowTypeInConstructor(symbol, constructor) {
51007             var accessName = ts.startsWith(symbol.escapedName, "__#")
51008                 ? ts.factory.createPrivateIdentifier(symbol.escapedName.split("@")[1])
51009                 : ts.unescapeLeadingUnderscores(symbol.escapedName);
51010             var reference = ts.factory.createPropertyAccessExpression(ts.factory.createThis(), accessName);
51011             ts.setParent(reference.expression, reference);
51012             ts.setParent(reference, constructor);
51013             reference.flowNode = constructor.returnFlowNode;
51014             var flowType = getFlowTypeOfProperty(reference, symbol);
51015             if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) {
51016                 error(symbol.valueDeclaration, ts.Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
51017             }
51018             // We don't infer a type if assignments are only null or undefined.
51019             return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType);
51020         }
51021         function getFlowTypeOfProperty(reference, prop) {
51022             var initialType = prop && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType;
51023             return getFlowTypeOfReference(reference, autoType, initialType);
51024         }
51025         function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) {
51026             // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers
51027             var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration);
51028             if (container) {
51029                 var tag = ts.getJSDocTypeTag(container);
51030                 if (tag && tag.typeExpression) {
51031                     return getTypeFromTypeNode(tag.typeExpression);
51032                 }
51033                 var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
51034                 return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
51035             }
51036             var type;
51037             var definedInConstructor = false;
51038             var definedInMethod = false;
51039             // We use control flow analysis to determine the type of the property if the property qualifies as a constructor
51040             // declared property and the resulting control flow type isn't just undefined or null.
51041             if (isConstructorDeclaredProperty(symbol)) {
51042                 type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol));
51043             }
51044             if (!type) {
51045                 var jsdocType = void 0;
51046                 var types = void 0;
51047                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
51048                     var declaration = _a[_i];
51049                     var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration :
51050                         ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration :
51051                             undefined;
51052                     if (!expression) {
51053                         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
51054                     }
51055                     var kind = ts.isAccessExpression(expression)
51056                         ? ts.getAssignmentDeclarationPropertyAccessKind(expression)
51057                         : ts.getAssignmentDeclarationKind(expression);
51058                     if (kind === 4 /* ThisProperty */ || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) {
51059                         if (isDeclarationInConstructor(expression)) {
51060                             definedInConstructor = true;
51061                         }
51062                         else {
51063                             definedInMethod = true;
51064                         }
51065                     }
51066                     if (!ts.isCallExpression(expression)) {
51067                         jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration);
51068                     }
51069                     if (!jsdocType) {
51070                         (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
51071                     }
51072                 }
51073                 type = jsdocType;
51074                 if (!type) {
51075                     if (!ts.length(types)) {
51076                         return errorType; // No types from any declarations :(
51077                     }
51078                     var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined;
51079                     // use only the constructor types unless they were only assigned null | undefined (including widening variants)
51080                     if (definedInMethod) {
51081                         var propType = getTypeOfPropertyInBaseClass(symbol);
51082                         if (propType) {
51083                             (constructorTypes || (constructorTypes = [])).push(propType);
51084                             definedInConstructor = true;
51085                         }
51086                     }
51087                     var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
51088                     type = getUnionType(sourceTypes, 2 /* Subtype */);
51089                 }
51090             }
51091             var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
51092             if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) {
51093                 reportImplicitAny(symbol.valueDeclaration, anyType);
51094                 return anyType;
51095             }
51096             return widened;
51097         }
51098         function getJSContainerObjectType(decl, symbol, init) {
51099             var _a, _b;
51100             if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
51101                 return undefined;
51102             }
51103             var exports = ts.createSymbolTable();
51104             while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) {
51105                 var s_2 = getSymbolOfNode(decl);
51106                 if ((_a = s_2 === null || s_2 === void 0 ? void 0 : s_2.exports) === null || _a === void 0 ? void 0 : _a.size) {
51107                     mergeSymbolTable(exports, s_2.exports);
51108                 }
51109                 decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
51110             }
51111             var s = getSymbolOfNode(decl);
51112             if ((_b = s === null || s === void 0 ? void 0 : s.exports) === null || _b === void 0 ? void 0 : _b.size) {
51113                 mergeSymbolTable(exports, s.exports);
51114             }
51115             var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
51116             type.objectFlags |= 16384 /* JSLiteral */;
51117             return type;
51118         }
51119         function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) {
51120             var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent);
51121             if (typeNode) {
51122                 var type = getWidenedType(getTypeFromTypeNode(typeNode));
51123                 if (!declaredType) {
51124                     return type;
51125                 }
51126                 else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) {
51127                     errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type);
51128                 }
51129             }
51130             if (symbol.parent) {
51131                 var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration);
51132                 if (typeNode_2) {
51133                     return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName);
51134                 }
51135             }
51136             return declaredType;
51137         }
51138         /** If we don't have an explicit JSDoc type, get the type from the initializer. */
51139         function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
51140             if (ts.isCallExpression(expression)) {
51141                 if (resolvedSymbol) {
51142                     return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments
51143                 }
51144                 var objectLitType = checkExpressionCached(expression.arguments[2]);
51145                 var valueType = getTypeOfPropertyOfType(objectLitType, "value");
51146                 if (valueType) {
51147                     return valueType;
51148                 }
51149                 var getFunc = getTypeOfPropertyOfType(objectLitType, "get");
51150                 if (getFunc) {
51151                     var getSig = getSingleCallSignature(getFunc);
51152                     if (getSig) {
51153                         return getReturnTypeOfSignature(getSig);
51154                     }
51155                 }
51156                 var setFunc = getTypeOfPropertyOfType(objectLitType, "set");
51157                 if (setFunc) {
51158                     var setSig = getSingleCallSignature(setFunc);
51159                     if (setSig) {
51160                         return getTypeOfFirstParameterOfSignature(setSig);
51161                     }
51162                 }
51163                 return anyType;
51164             }
51165             if (containsSameNamedThisProperty(expression.left, expression.right)) {
51166                 return anyType;
51167             }
51168             var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right));
51169             if (type.flags & 524288 /* Object */ &&
51170                 kind === 2 /* ModuleExports */ &&
51171                 symbol.escapedName === "export=" /* ExportEquals */) {
51172                 var exportedType = resolveStructuredTypeMembers(type);
51173                 var members_4 = ts.createSymbolTable();
51174                 ts.copyEntries(exportedType.members, members_4);
51175                 var initialSize = members_4.size;
51176                 if (resolvedSymbol && !resolvedSymbol.exports) {
51177                     resolvedSymbol.exports = ts.createSymbolTable();
51178                 }
51179                 (resolvedSymbol || symbol).exports.forEach(function (s, name) {
51180                     var _a;
51181                     var exportedMember = members_4.get(name);
51182                     if (exportedMember && exportedMember !== s) {
51183                         if (s.flags & 111551 /* Value */ && exportedMember.flags & 111551 /* Value */) {
51184                             // If the member has an additional value-like declaration, union the types from the two declarations,
51185                             // but issue an error if they occurred in two different files. The purpose is to support a JS file with
51186                             // a pattern like:
51187                             //
51188                             // module.exports = { a: true };
51189                             // module.exports.a = 3;
51190                             //
51191                             // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation
51192                             // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because
51193                             // it's unclear what that's supposed to mean, so it's probably a mistake.
51194                             if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) {
51195                                 var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName);
51196                                 var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration;
51197                                 ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName));
51198                                 ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName));
51199                             }
51200                             var union = createSymbol(s.flags | exportedMember.flags, name);
51201                             union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
51202                             union.valueDeclaration = exportedMember.valueDeclaration;
51203                             union.declarations = ts.concatenate(exportedMember.declarations, s.declarations);
51204                             members_4.set(name, union);
51205                         }
51206                         else {
51207                             members_4.set(name, mergeSymbol(s, exportedMember));
51208                         }
51209                     }
51210                     else {
51211                         members_4.set(name, s);
51212                     }
51213                 });
51214                 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
51215                 members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo);
51216                 result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag
51217                 if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) {
51218                     result.objectFlags |= 1073741824 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type
51219                 }
51220                 return result;
51221             }
51222             if (isEmptyArrayLiteralType(type)) {
51223                 reportImplicitAny(expression, anyArrayType);
51224                 return anyArrayType;
51225             }
51226             return type;
51227         }
51228         function containsSameNamedThisProperty(thisProperty, expression) {
51229             return ts.isPropertyAccessExpression(thisProperty)
51230                 && thisProperty.expression.kind === 107 /* ThisKeyword */
51231                 && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); });
51232         }
51233         function isDeclarationInConstructor(expression) {
51234             var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false);
51235             // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added.
51236             // Function expressions that are assigned to the prototype count as methods.
51237             return thisContainer.kind === 166 /* Constructor */ ||
51238                 thisContainer.kind === 251 /* FunctionDeclaration */ ||
51239                 (thisContainer.kind === 208 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent));
51240         }
51241         function getConstructorDefinedThisAssignmentTypes(types, declarations) {
51242             ts.Debug.assert(types.length === declarations.length);
51243             return types.filter(function (_, i) {
51244                 var declaration = declarations[i];
51245                 var expression = ts.isBinaryExpression(declaration) ? declaration :
51246                     ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined;
51247                 return expression && isDeclarationInConstructor(expression);
51248             });
51249         }
51250         // Return the type implied by a binding pattern element. This is the type of the initializer of the element if
51251         // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
51252         // pattern. Otherwise, it is the type any.
51253         function getTypeFromBindingElement(element, includePatternInType, reportErrors) {
51254             if (element.initializer) {
51255                 // The type implied by a binding pattern is independent of context, so we check the initializer with no
51256                 // contextual type or, if the element itself is a binding pattern, with the type implied by that binding
51257                 // pattern.
51258                 var contextualType = ts.isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, /*includePatternInType*/ true, /*reportErrors*/ false) : unknownType;
51259                 return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, contextualType)));
51260             }
51261             if (ts.isBindingPattern(element.name)) {
51262                 return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
51263             }
51264             if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
51265                 reportImplicitAny(element, anyType);
51266             }
51267             // When we're including the pattern in the type (an indication we're obtaining a contextual type), we
51268             // use the non-inferrable any type. Inference will never directly infer this type, but it is possible
51269             // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
51270             // widening of the binding pattern type substitutes a regular any for the non-inferrable any.
51271             return includePatternInType ? nonInferrableAnyType : anyType;
51272         }
51273         // Return the type implied by an object binding pattern
51274         function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
51275             var members = ts.createSymbolTable();
51276             var stringIndexInfo;
51277             var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
51278             ts.forEach(pattern.elements, function (e) {
51279                 var name = e.propertyName || e.name;
51280                 if (e.dotDotDotToken) {
51281                     stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
51282                     return;
51283                 }
51284                 var exprType = getLiteralTypeFromPropertyName(name);
51285                 if (!isTypeUsableAsPropertyName(exprType)) {
51286                     // do not include computed properties in the implied type
51287                     objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
51288                     return;
51289                 }
51290                 var text = getPropertyNameFromType(exprType);
51291                 var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
51292                 var symbol = createSymbol(flags, text);
51293                 symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
51294                 symbol.bindingElement = e;
51295                 members.set(symbol.escapedName, symbol);
51296             });
51297             var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
51298             result.objectFlags |= objectFlags;
51299             if (includePatternInType) {
51300                 result.pattern = pattern;
51301                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
51302             }
51303             return result;
51304         }
51305         // Return the type implied by an array binding pattern
51306         function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) {
51307             var elements = pattern.elements;
51308             var lastElement = ts.lastOrUndefined(elements);
51309             var restElement = lastElement && lastElement.kind === 198 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined;
51310             if (elements.length === 0 || elements.length === 1 && restElement) {
51311                 return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
51312             }
51313             var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); });
51314             var minLength = ts.findLastIndex(elements, function (e) { return !(e === restElement || ts.isOmittedExpression(e) || hasDefaultValue(e)); }, elements.length - 1) + 1;
51315             var elementFlags = ts.map(elements, function (e, i) { return e === restElement ? 4 /* Rest */ : i >= minLength ? 2 /* Optional */ : 1 /* Required */; });
51316             var result = createTupleType(elementTypes, elementFlags);
51317             if (includePatternInType) {
51318                 result = cloneTypeReference(result);
51319                 result.pattern = pattern;
51320                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
51321             }
51322             return result;
51323         }
51324         // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself
51325         // and without regard to its context (i.e. without regard any type annotation or initializer associated with the
51326         // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any]
51327         // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is
51328         // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring
51329         // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
51330         // the parameter.
51331         function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) {
51332             if (includePatternInType === void 0) { includePatternInType = false; }
51333             if (reportErrors === void 0) { reportErrors = false; }
51334             return pattern.kind === 196 /* ObjectBindingPattern */
51335                 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors)
51336                 : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
51337         }
51338         // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type
51339         // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it
51340         // is a bit more involved. For example:
51341         //
51342         //   var [x, s = ""] = [1, "one"];
51343         //
51344         // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the
51345         // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the
51346         // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string.
51347         function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) {
51348             return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors);
51349         }
51350         function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) {
51351             if (type) {
51352                 if (reportErrors) {
51353                     reportErrorsFromWidening(declaration, type);
51354                 }
51355                 // always widen a 'unique symbol' type if the type was created for a different declaration.
51356                 if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) {
51357                     type = esSymbolType;
51358                 }
51359                 return getWidenedType(type);
51360             }
51361             // Rest parameters default to type any[], other parameters default to type any
51362             type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
51363             // Report implicit any errors unless this is a private property within an ambient declaration
51364             if (reportErrors) {
51365                 if (!declarationBelongsToPrivateAmbientMember(declaration)) {
51366                     reportImplicitAny(declaration, type);
51367                 }
51368             }
51369             return type;
51370         }
51371         function declarationBelongsToPrivateAmbientMember(declaration) {
51372             var root = ts.getRootDeclaration(declaration);
51373             var memberDeclaration = root.kind === 160 /* Parameter */ ? root.parent : root;
51374             return isPrivateWithinAmbient(memberDeclaration);
51375         }
51376         function tryGetTypeFromEffectiveTypeNode(declaration) {
51377             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
51378             if (typeNode) {
51379                 return getTypeFromTypeNode(typeNode);
51380             }
51381         }
51382         function getTypeOfVariableOrParameterOrProperty(symbol) {
51383             var links = getSymbolLinks(symbol);
51384             if (!links.type) {
51385                 var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
51386                 // For a contextually typed parameter it is possible that a type has already
51387                 // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
51388                 // to preserve this type.
51389                 if (!links.type) {
51390                     links.type = type;
51391                 }
51392             }
51393             return links.type;
51394         }
51395         function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
51396             // Handle prototype property
51397             if (symbol.flags & 4194304 /* Prototype */) {
51398                 return getTypeOfPrototypeProperty(symbol);
51399             }
51400             // CommonsJS require and module both have type any.
51401             if (symbol === requireSymbol) {
51402                 return anyType;
51403             }
51404             if (symbol.flags & 134217728 /* ModuleExports */) {
51405                 var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration));
51406                 var result = createSymbol(fileSymbol.flags, "exports");
51407                 result.declarations = fileSymbol.declarations ? fileSymbol.declarations.slice() : [];
51408                 result.parent = symbol;
51409                 result.target = fileSymbol;
51410                 if (fileSymbol.valueDeclaration)
51411                     result.valueDeclaration = fileSymbol.valueDeclaration;
51412                 if (fileSymbol.members)
51413                     result.members = new ts.Map(fileSymbol.members);
51414                 if (fileSymbol.exports)
51415                     result.exports = new ts.Map(fileSymbol.exports);
51416                 var members = ts.createSymbolTable();
51417                 members.set("exports", result);
51418                 return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
51419             }
51420             // Handle catch clause variables
51421             var declaration = symbol.valueDeclaration;
51422             if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
51423                 var decl = declaration;
51424                 if (!decl.type)
51425                     return anyType;
51426                 var type_1 = getTypeOfNode(decl.type);
51427                 // an errorType will make `checkTryStatement` issue an error
51428                 return isTypeAny(type_1) || type_1 === unknownType ? type_1 : errorType;
51429             }
51430             // Handle export default expressions
51431             if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) {
51432                 if (!declaration.statements.length) {
51433                     return emptyObjectType;
51434                 }
51435                 return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression)));
51436             }
51437             // Handle variable, parameter or property
51438             if (!pushTypeResolution(symbol, 0 /* Type */)) {
51439                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
51440                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
51441                     return getTypeOfFuncClassEnumModule(symbol);
51442                 }
51443                 return reportCircularityError(symbol);
51444             }
51445             var type;
51446             if (declaration.kind === 266 /* ExportAssignment */) {
51447                 type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
51448             }
51449             else if (ts.isBinaryExpression(declaration) ||
51450                 (ts.isInJSFile(declaration) &&
51451                     (ts.isCallExpression(declaration) || (ts.isPropertyAccessExpression(declaration) || ts.isBindableStaticElementAccessExpression(declaration)) && ts.isBinaryExpression(declaration.parent)))) {
51452                 type = getWidenedTypeForAssignmentDeclaration(symbol);
51453             }
51454             else if (ts.isPropertyAccessExpression(declaration)
51455                 || ts.isElementAccessExpression(declaration)
51456                 || ts.isIdentifier(declaration)
51457                 || ts.isStringLiteralLike(declaration)
51458                 || ts.isNumericLiteral(declaration)
51459                 || ts.isClassDeclaration(declaration)
51460                 || ts.isFunctionDeclaration(declaration)
51461                 || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
51462                 || ts.isMethodSignature(declaration)
51463                 || ts.isSourceFile(declaration)) {
51464                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
51465                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
51466                     return getTypeOfFuncClassEnumModule(symbol);
51467                 }
51468                 type = ts.isBinaryExpression(declaration.parent) ?
51469                     getWidenedTypeForAssignmentDeclaration(symbol) :
51470                     tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
51471             }
51472             else if (ts.isPropertyAssignment(declaration)) {
51473                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
51474             }
51475             else if (ts.isJsxAttribute(declaration)) {
51476                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
51477             }
51478             else if (ts.isShorthandPropertyAssignment(declaration)) {
51479                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
51480             }
51481             else if (ts.isObjectLiteralMethod(declaration)) {
51482                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
51483             }
51484             else if (ts.isParameter(declaration)
51485                 || ts.isPropertyDeclaration(declaration)
51486                 || ts.isPropertySignature(declaration)
51487                 || ts.isVariableDeclaration(declaration)
51488                 || ts.isBindingElement(declaration)
51489                 || ts.isJSDocPropertyLikeTag(declaration)) {
51490                 type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
51491             }
51492             // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive.
51493             // Re-dispatch based on valueDeclaration.kind instead.
51494             else if (ts.isEnumDeclaration(declaration)) {
51495                 type = getTypeOfFuncClassEnumModule(symbol);
51496             }
51497             else if (ts.isEnumMember(declaration)) {
51498                 type = getTypeOfEnumMember(symbol);
51499             }
51500             else if (ts.isAccessor(declaration)) {
51501                 type = resolveTypeOfAccessors(symbol);
51502             }
51503             else {
51504                 return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol));
51505             }
51506             if (!popTypeResolution()) {
51507                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
51508                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
51509                     return getTypeOfFuncClassEnumModule(symbol);
51510                 }
51511                 return reportCircularityError(symbol);
51512             }
51513             return type;
51514         }
51515         function getAnnotatedAccessorTypeNode(accessor) {
51516             if (accessor) {
51517                 if (accessor.kind === 167 /* GetAccessor */) {
51518                     var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor);
51519                     return getterTypeAnnotation;
51520                 }
51521                 else {
51522                     var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor);
51523                     return setterTypeAnnotation;
51524                 }
51525             }
51526             return undefined;
51527         }
51528         function getAnnotatedAccessorType(accessor) {
51529             var node = getAnnotatedAccessorTypeNode(accessor);
51530             return node && getTypeFromTypeNode(node);
51531         }
51532         function getAnnotatedAccessorThisParameter(accessor) {
51533             var parameter = getAccessorThisParameter(accessor);
51534             return parameter && parameter.symbol;
51535         }
51536         function getThisTypeOfDeclaration(declaration) {
51537             return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
51538         }
51539         function getTypeOfAccessors(symbol) {
51540             var links = getSymbolLinks(symbol);
51541             return links.type || (links.type = getTypeOfAccessorsWorker(symbol));
51542         }
51543         function getTypeOfAccessorsWorker(symbol) {
51544             if (!pushTypeResolution(symbol, 0 /* Type */)) {
51545                 return errorType;
51546             }
51547             var type = resolveTypeOfAccessors(symbol);
51548             if (!popTypeResolution()) {
51549                 type = anyType;
51550                 if (noImplicitAny) {
51551                     var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */);
51552                     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));
51553                 }
51554             }
51555             return type;
51556         }
51557         function resolveTypeOfAccessors(symbol) {
51558             var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */);
51559             var setter = ts.getDeclarationOfKind(symbol, 168 /* SetAccessor */);
51560             if (getter && ts.isInJSFile(getter)) {
51561                 var jsDocType = getTypeForDeclarationFromJSDocComment(getter);
51562                 if (jsDocType) {
51563                     return jsDocType;
51564                 }
51565             }
51566             // First try to see if the user specified a return type on the get-accessor.
51567             var getterReturnType = getAnnotatedAccessorType(getter);
51568             if (getterReturnType) {
51569                 return getterReturnType;
51570             }
51571             else {
51572                 // If the user didn't specify a return type, try to use the set-accessor's parameter type.
51573                 var setterParameterType = getAnnotatedAccessorType(setter);
51574                 if (setterParameterType) {
51575                     return setterParameterType;
51576                 }
51577                 else {
51578                     // If there are no specified types, try to infer it from the body of the get accessor if it exists.
51579                     if (getter && getter.body) {
51580                         return getReturnTypeFromBody(getter);
51581                     }
51582                     // Otherwise, fall back to 'any'.
51583                     else {
51584                         if (setter) {
51585                             if (!isPrivateWithinAmbient(setter)) {
51586                                 errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
51587                             }
51588                         }
51589                         else {
51590                             ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function");
51591                             if (!isPrivateWithinAmbient(getter)) {
51592                                 errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
51593                             }
51594                         }
51595                         return anyType;
51596                     }
51597                 }
51598             }
51599         }
51600         function getBaseTypeVariableOfClass(symbol) {
51601             var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
51602             return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType :
51603                 baseConstructorType.flags & 2097152 /* Intersection */ ? ts.find(baseConstructorType.types, function (t) { return !!(t.flags & 8650752 /* TypeVariable */); }) :
51604                     undefined;
51605         }
51606         function getTypeOfFuncClassEnumModule(symbol) {
51607             var links = getSymbolLinks(symbol);
51608             var originalLinks = links;
51609             if (!links.type) {
51610                 var expando = symbol.valueDeclaration && getSymbolOfExpando(symbol.valueDeclaration, /*allowDeclaration*/ false);
51611                 if (expando) {
51612                     var merged = mergeJSSymbols(symbol, expando);
51613                     if (merged) {
51614                         // note:we overwrite links because we just cloned the symbol
51615                         symbol = links = merged;
51616                     }
51617                 }
51618                 originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
51619             }
51620             return links.type;
51621         }
51622         function getTypeOfFuncClassEnumModuleWorker(symbol) {
51623             var declaration = symbol.valueDeclaration;
51624             if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) {
51625                 return anyType;
51626             }
51627             else if (declaration && (declaration.kind === 216 /* BinaryExpression */ ||
51628                 ts.isAccessExpression(declaration) &&
51629                     declaration.parent.kind === 216 /* BinaryExpression */)) {
51630                 return getWidenedTypeForAssignmentDeclaration(symbol);
51631             }
51632             else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
51633                 var resolvedModule = resolveExternalModuleSymbol(symbol);
51634                 if (resolvedModule !== symbol) {
51635                     if (!pushTypeResolution(symbol, 0 /* Type */)) {
51636                         return errorType;
51637                     }
51638                     var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
51639                     var type_2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
51640                     if (!popTypeResolution()) {
51641                         return reportCircularityError(symbol);
51642                     }
51643                     return type_2;
51644                 }
51645             }
51646             var type = createObjectType(16 /* Anonymous */, symbol);
51647             if (symbol.flags & 32 /* Class */) {
51648                 var baseTypeVariable = getBaseTypeVariableOfClass(symbol);
51649                 return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
51650             }
51651             else {
51652                 return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type;
51653             }
51654         }
51655         function getTypeOfEnumMember(symbol) {
51656             var links = getSymbolLinks(symbol);
51657             return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
51658         }
51659         function getTypeOfAlias(symbol) {
51660             var links = getSymbolLinks(symbol);
51661             if (!links.type) {
51662                 var targetSymbol = resolveAlias(symbol);
51663                 // It only makes sense to get the type of a value symbol. If the result of resolving
51664                 // the alias is not a value, then it has no type. To get the type associated with a
51665                 // type symbol, call getDeclaredTypeOfSymbol.
51666                 // This check is important because without it, a call to getTypeOfSymbol could end
51667                 // up recursively calling getTypeOfAlias, causing a stack overflow.
51668                 links.type = targetSymbol.flags & 111551 /* Value */
51669                     ? getTypeOfSymbol(targetSymbol)
51670                     : errorType;
51671             }
51672             return links.type;
51673         }
51674         function getTypeOfInstantiatedSymbol(symbol) {
51675             var links = getSymbolLinks(symbol);
51676             if (!links.type) {
51677                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
51678                     return links.type = errorType;
51679                 }
51680                 var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
51681                 if (!popTypeResolution()) {
51682                     type = reportCircularityError(symbol);
51683                 }
51684                 links.type = type;
51685             }
51686             return links.type;
51687         }
51688         function reportCircularityError(symbol) {
51689             var declaration = symbol.valueDeclaration;
51690             // Check if variable has type annotation that circularly references the variable itself
51691             if (ts.getEffectiveTypeAnnotationNode(declaration)) {
51692                 error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
51693                 return errorType;
51694             }
51695             // Check if variable has initializer that circularly references the variable itself
51696             if (noImplicitAny && (declaration.kind !== 160 /* Parameter */ || declaration.initializer)) {
51697                 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));
51698             }
51699             // Circularities could also result from parameters in function expressions that end up
51700             // having themselves as contextual types following type argument inference. In those cases
51701             // we have already reported an implicit any error so we don't report anything here.
51702             return anyType;
51703         }
51704         function getTypeOfSymbolWithDeferredType(symbol) {
51705             var links = getSymbolLinks(symbol);
51706             if (!links.type) {
51707                 ts.Debug.assertIsDefined(links.deferralParent);
51708                 ts.Debug.assertIsDefined(links.deferralConstituents);
51709                 links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
51710             }
51711             return links.type;
51712         }
51713         function getTypeOfSymbol(symbol) {
51714             var checkFlags = ts.getCheckFlags(symbol);
51715             if (checkFlags & 65536 /* DeferredType */) {
51716                 return getTypeOfSymbolWithDeferredType(symbol);
51717             }
51718             if (checkFlags & 1 /* Instantiated */) {
51719                 return getTypeOfInstantiatedSymbol(symbol);
51720             }
51721             if (checkFlags & 262144 /* Mapped */) {
51722                 return getTypeOfMappedSymbol(symbol);
51723             }
51724             if (checkFlags & 8192 /* ReverseMapped */) {
51725                 return getTypeOfReverseMappedSymbol(symbol);
51726             }
51727             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
51728                 return getTypeOfVariableOrParameterOrProperty(symbol);
51729             }
51730             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
51731                 return getTypeOfFuncClassEnumModule(symbol);
51732             }
51733             if (symbol.flags & 8 /* EnumMember */) {
51734                 return getTypeOfEnumMember(symbol);
51735             }
51736             if (symbol.flags & 98304 /* Accessor */) {
51737                 return getTypeOfAccessors(symbol);
51738             }
51739             if (symbol.flags & 2097152 /* Alias */) {
51740                 return getTypeOfAlias(symbol);
51741             }
51742             return errorType;
51743         }
51744         function isReferenceToType(type, target) {
51745             return type !== undefined
51746                 && target !== undefined
51747                 && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0
51748                 && type.target === target;
51749         }
51750         function getTargetType(type) {
51751             return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
51752         }
51753         // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false.
51754         function hasBaseType(type, checkBase) {
51755             return check(type);
51756             function check(type) {
51757                 if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
51758                     var target = getTargetType(type);
51759                     return target === checkBase || ts.some(getBaseTypes(target), check);
51760                 }
51761                 else if (type.flags & 2097152 /* Intersection */) {
51762                     return ts.some(type.types, check);
51763                 }
51764                 return false;
51765             }
51766         }
51767         // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set.
51768         // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set
51769         // in-place and returns the same array.
51770         function appendTypeParameters(typeParameters, declarations) {
51771             for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
51772                 var declaration = declarations_2[_i];
51773                 typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)));
51774             }
51775             return typeParameters;
51776         }
51777         // Return the outer type parameters of a node or undefined if the node has no outer type parameters.
51778         function getOuterTypeParameters(node, includeThisTypes) {
51779             while (true) {
51780                 node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead
51781                 if (node && ts.isBinaryExpression(node)) {
51782                     // prototype assignments get the outer type parameters of their constructor function
51783                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
51784                     if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) {
51785                         var symbol = getSymbolOfNode(node.left);
51786                         if (symbol && symbol.parent && !ts.findAncestor(symbol.parent.valueDeclaration, function (d) { return node === d; })) {
51787                             node = symbol.parent.valueDeclaration;
51788                         }
51789                     }
51790                 }
51791                 if (!node) {
51792                     return undefined;
51793                 }
51794                 switch (node.kind) {
51795                     case 232 /* VariableStatement */:
51796                     case 252 /* ClassDeclaration */:
51797                     case 221 /* ClassExpression */:
51798                     case 253 /* InterfaceDeclaration */:
51799                     case 169 /* CallSignature */:
51800                     case 170 /* ConstructSignature */:
51801                     case 164 /* MethodSignature */:
51802                     case 174 /* FunctionType */:
51803                     case 175 /* ConstructorType */:
51804                     case 308 /* JSDocFunctionType */:
51805                     case 251 /* FunctionDeclaration */:
51806                     case 165 /* MethodDeclaration */:
51807                     case 208 /* FunctionExpression */:
51808                     case 209 /* ArrowFunction */:
51809                     case 254 /* TypeAliasDeclaration */:
51810                     case 330 /* JSDocTemplateTag */:
51811                     case 331 /* JSDocTypedefTag */:
51812                     case 325 /* JSDocEnumTag */:
51813                     case 324 /* JSDocCallbackTag */:
51814                     case 190 /* MappedType */:
51815                     case 184 /* ConditionalType */:
51816                         var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
51817                         if (node.kind === 190 /* MappedType */) {
51818                             return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)));
51819                         }
51820                         else if (node.kind === 184 /* ConditionalType */) {
51821                             return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
51822                         }
51823                         else if (node.kind === 232 /* VariableStatement */ && !ts.isInJSFile(node)) {
51824                             break;
51825                         }
51826                         var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
51827                         var thisType = includeThisTypes &&
51828                             (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */ || node.kind === 253 /* InterfaceDeclaration */ || isJSConstructor(node)) &&
51829                             getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
51830                         return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
51831                     case 326 /* JSDocParameterTag */:
51832                         var paramSymbol = ts.getParameterSymbolFromJSDoc(node);
51833                         if (paramSymbol) {
51834                             node = paramSymbol.valueDeclaration;
51835                         }
51836                         break;
51837                 }
51838             }
51839         }
51840         // The outer type parameters are those defined by enclosing generic classes, methods, or functions.
51841         function getOuterTypeParametersOfClassOrInterface(symbol) {
51842             var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */);
51843             ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations");
51844             return getOuterTypeParameters(declaration);
51845         }
51846         // The local type parameters are the combined set of type parameters from all declarations of the class,
51847         // interface, or type alias.
51848         function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
51849             var result;
51850             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
51851                 var node = _a[_i];
51852                 if (node.kind === 253 /* InterfaceDeclaration */ ||
51853                     node.kind === 252 /* ClassDeclaration */ ||
51854                     node.kind === 221 /* ClassExpression */ ||
51855                     isJSConstructor(node) ||
51856                     ts.isTypeAlias(node)) {
51857                     var declaration = node;
51858                     result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
51859                 }
51860             }
51861             return result;
51862         }
51863         // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus
51864         // its locally declared type parameters.
51865         function getTypeParametersOfClassOrInterface(symbol) {
51866             return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
51867         }
51868         // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single
51869         // rest parameter of type any[].
51870         function isMixinConstructorType(type) {
51871             var signatures = getSignaturesOfType(type, 1 /* Construct */);
51872             if (signatures.length === 1) {
51873                 var s = signatures[0];
51874                 if (!s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s)) {
51875                     var paramType = getTypeOfParameter(s.parameters[0]);
51876                     return isTypeAny(paramType) || getElementTypeOfArrayType(paramType) === anyType;
51877                 }
51878             }
51879             return false;
51880         }
51881         function isConstructorType(type) {
51882             if (getSignaturesOfType(type, 1 /* Construct */).length > 0) {
51883                 return true;
51884             }
51885             if (type.flags & 8650752 /* TypeVariable */) {
51886                 var constraint = getBaseConstraintOfType(type);
51887                 return !!constraint && isMixinConstructorType(constraint);
51888             }
51889             return false;
51890         }
51891         function getBaseTypeNodeOfClass(type) {
51892             return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration);
51893         }
51894         function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
51895             var typeArgCount = ts.length(typeArgumentNodes);
51896             var isJavascript = ts.isInJSFile(location);
51897             return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); });
51898         }
51899         function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
51900             var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
51901             var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode);
51902             return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; });
51903         }
51904         /**
51905          * The base constructor of a class can resolve to
51906          * * undefinedType if the class has no extends clause,
51907          * * unknownType if an error occurred during resolution of the extends expression,
51908          * * nullType if the extends expression is the null value,
51909          * * anyType if the extends expression has type any, or
51910          * * an object type with at least one construct signature.
51911          */
51912         function getBaseConstructorTypeOfClass(type) {
51913             if (!type.resolvedBaseConstructorType) {
51914                 var decl = type.symbol.valueDeclaration;
51915                 var extended = ts.getEffectiveBaseTypeNode(decl);
51916                 var baseTypeNode = getBaseTypeNodeOfClass(type);
51917                 if (!baseTypeNode) {
51918                     return type.resolvedBaseConstructorType = undefinedType;
51919                 }
51920                 if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
51921                     return errorType;
51922                 }
51923                 var baseConstructorType = checkExpression(baseTypeNode.expression);
51924                 if (extended && baseTypeNode !== extended) {
51925                     ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag
51926                     checkExpression(extended.expression);
51927                 }
51928                 if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
51929                     // Resolving the members of a class requires us to resolve the base class of that class.
51930                     // We force resolution here such that we catch circularities now.
51931                     resolveStructuredTypeMembers(baseConstructorType);
51932                 }
51933                 if (!popTypeResolution()) {
51934                     error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
51935                     return type.resolvedBaseConstructorType = errorType;
51936                 }
51937                 if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
51938                     var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
51939                     if (baseConstructorType.flags & 262144 /* TypeParameter */) {
51940                         var constraint = getConstraintFromTypeParameter(baseConstructorType);
51941                         var ctorReturn = unknownType;
51942                         if (constraint) {
51943                             var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */);
51944                             if (ctorSig[0]) {
51945                                 ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
51946                             }
51947                         }
51948                         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)));
51949                     }
51950                     return type.resolvedBaseConstructorType = errorType;
51951                 }
51952                 type.resolvedBaseConstructorType = baseConstructorType;
51953             }
51954             return type.resolvedBaseConstructorType;
51955         }
51956         function getImplementsTypes(type) {
51957             var resolvedImplementsTypes = ts.emptyArray;
51958             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
51959                 var declaration = _a[_i];
51960                 var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration);
51961                 if (!implementsTypeNodes)
51962                     continue;
51963                 for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) {
51964                     var node = implementsTypeNodes_1[_b];
51965                     var implementsType = getTypeFromTypeNode(node);
51966                     if (implementsType !== errorType) {
51967                         if (resolvedImplementsTypes === ts.emptyArray) {
51968                             resolvedImplementsTypes = [implementsType];
51969                         }
51970                         else {
51971                             resolvedImplementsTypes.push(implementsType);
51972                         }
51973                     }
51974                 }
51975             }
51976             return resolvedImplementsTypes;
51977         }
51978         function reportCircularBaseType(node, type) {
51979             error(node, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
51980         }
51981         function getBaseTypes(type) {
51982             if (!type.baseTypesResolved) {
51983                 if (pushTypeResolution(type, 7 /* ResolvedBaseTypes */)) {
51984                     if (type.objectFlags & 8 /* Tuple */) {
51985                         type.resolvedBaseTypes = [getTupleBaseType(type)];
51986                     }
51987                     else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
51988                         if (type.symbol.flags & 32 /* Class */) {
51989                             resolveBaseTypesOfClass(type);
51990                         }
51991                         if (type.symbol.flags & 64 /* Interface */) {
51992                             resolveBaseTypesOfInterface(type);
51993                         }
51994                     }
51995                     else {
51996                         ts.Debug.fail("type must be class or interface");
51997                     }
51998                     if (!popTypeResolution()) {
51999                         for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
52000                             var declaration = _a[_i];
52001                             if (declaration.kind === 252 /* ClassDeclaration */ || declaration.kind === 253 /* InterfaceDeclaration */) {
52002                                 reportCircularBaseType(declaration, type);
52003                             }
52004                         }
52005                     }
52006                 }
52007                 type.baseTypesResolved = true;
52008             }
52009             return type.resolvedBaseTypes;
52010         }
52011         function getTupleBaseType(type) {
52012             var elementTypes = ts.sameMap(type.typeParameters, function (t, i) { return type.elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t; });
52013             return createArrayType(getUnionType(elementTypes || ts.emptyArray), type.readonly);
52014         }
52015         function resolveBaseTypesOfClass(type) {
52016             type.resolvedBaseTypes = ts.resolvingEmptyArray;
52017             var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
52018             if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) {
52019                 return type.resolvedBaseTypes = ts.emptyArray;
52020             }
52021             var baseTypeNode = getBaseTypeNodeOfClass(type);
52022             var baseType;
52023             var originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
52024             if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
52025                 areAllOuterTypeParametersApplied(originalBaseType)) {
52026                 // 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
52027                 // class and all return the instance type of the class. There is no need for further checks and we can apply the
52028                 // type arguments in the same manner as a type reference to get the same error reporting experience.
52029                 baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
52030             }
52031             else if (baseConstructorType.flags & 1 /* Any */) {
52032                 baseType = baseConstructorType;
52033             }
52034             else {
52035                 // The class derives from a "class-like" constructor function, check that we have at least one construct signature
52036                 // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
52037                 // we check that all instantiated signatures return the same type.
52038                 var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
52039                 if (!constructors.length) {
52040                     error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
52041                     return type.resolvedBaseTypes = ts.emptyArray;
52042                 }
52043                 baseType = getReturnTypeOfSignature(constructors[0]);
52044             }
52045             if (baseType === errorType) {
52046                 return type.resolvedBaseTypes = ts.emptyArray;
52047             }
52048             var reducedBaseType = getReducedType(baseType);
52049             if (!isValidBaseType(reducedBaseType)) {
52050                 var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType);
52051                 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));
52052                 diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic));
52053                 return type.resolvedBaseTypes = ts.emptyArray;
52054             }
52055             if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) {
52056                 error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
52057                 return type.resolvedBaseTypes = ts.emptyArray;
52058             }
52059             if (type.resolvedBaseTypes === ts.resolvingEmptyArray) {
52060                 // Circular reference, likely through instantiation of default parameters
52061                 // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset
52062                 // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a
52063                 // partial instantiation of the members without the base types fully resolved
52064                 type.members = undefined;
52065             }
52066             return type.resolvedBaseTypes = [reducedBaseType];
52067         }
52068         function areAllOuterTypeParametersApplied(type) {
52069             // An unapplied type parameter has its symbol still the same as the matching argument symbol.
52070             // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
52071             var outerTypeParameters = type.outerTypeParameters;
52072             if (outerTypeParameters) {
52073                 var last_1 = outerTypeParameters.length - 1;
52074                 var typeArguments = getTypeArguments(type);
52075                 return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol;
52076             }
52077             return true;
52078         }
52079         // A valid base type is `any`, an object type or intersection of object types.
52080         function isValidBaseType(type) {
52081             if (type.flags & 262144 /* TypeParameter */) {
52082                 var constraint = getBaseConstraintOfType(type);
52083                 if (constraint) {
52084                     return isValidBaseType(constraint);
52085                 }
52086             }
52087             // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed?
52088             // There's no reason a `T` should be allowed while a `Readonly<T>` should not.
52089             return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) ||
52090                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType));
52091         }
52092         function resolveBaseTypesOfInterface(type) {
52093             type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray;
52094             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
52095                 var declaration = _a[_i];
52096                 if (declaration.kind === 253 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
52097                     for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) {
52098                         var node = _c[_b];
52099                         var baseType = getReducedType(getTypeFromTypeNode(node));
52100                         if (baseType !== errorType) {
52101                             if (isValidBaseType(baseType)) {
52102                                 if (type !== baseType && !hasBaseType(baseType, type)) {
52103                                     if (type.resolvedBaseTypes === ts.emptyArray) {
52104                                         type.resolvedBaseTypes = [baseType];
52105                                     }
52106                                     else {
52107                                         type.resolvedBaseTypes.push(baseType);
52108                                     }
52109                                 }
52110                                 else {
52111                                     reportCircularBaseType(declaration, type);
52112                                 }
52113                             }
52114                             else {
52115                                 error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
52116                             }
52117                         }
52118                     }
52119                 }
52120             }
52121         }
52122         /**
52123          * Returns true if the interface given by the symbol is free of "this" references.
52124          *
52125          * Specifically, the result is true if the interface itself contains no references
52126          * to "this" in its body, if all base types are interfaces,
52127          * and if none of the base interfaces have a "this" type.
52128          */
52129         function isThislessInterface(symbol) {
52130             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
52131                 var declaration = _a[_i];
52132                 if (declaration.kind === 253 /* InterfaceDeclaration */) {
52133                     if (declaration.flags & 128 /* ContainsThis */) {
52134                         return false;
52135                     }
52136                     var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration);
52137                     if (baseTypeNodes) {
52138                         for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) {
52139                             var node = baseTypeNodes_1[_b];
52140                             if (ts.isEntityNameExpression(node.expression)) {
52141                                 var baseSymbol = resolveEntityName(node.expression, 788968 /* Type */, /*ignoreErrors*/ true);
52142                                 if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
52143                                     return false;
52144                                 }
52145                             }
52146                         }
52147                     }
52148                 }
52149             }
52150             return true;
52151         }
52152         function getDeclaredTypeOfClassOrInterface(symbol) {
52153             var links = getSymbolLinks(symbol);
52154             var originalLinks = links;
52155             if (!links.declaredType) {
52156                 var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
52157                 var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration));
52158                 if (merged) {
52159                     // note:we overwrite links because we just cloned the symbol
52160                     symbol = links = merged;
52161                 }
52162                 var type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol);
52163                 var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
52164                 var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
52165                 // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type
52166                 // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular,
52167                 // property types inferred from initializers and method return types inferred from return statements are very hard
52168                 // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
52169                 // "this" references.
52170                 if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
52171                     type.objectFlags |= 4 /* Reference */;
52172                     type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters);
52173                     type.outerTypeParameters = outerTypeParameters;
52174                     type.localTypeParameters = localTypeParameters;
52175                     type.instantiations = new ts.Map();
52176                     type.instantiations.set(getTypeListId(type.typeParameters), type);
52177                     type.target = type;
52178                     type.resolvedTypeArguments = type.typeParameters;
52179                     type.thisType = createTypeParameter(symbol);
52180                     type.thisType.isThisType = true;
52181                     type.thisType.constraint = type;
52182                 }
52183             }
52184             return links.declaredType;
52185         }
52186         function getDeclaredTypeOfTypeAlias(symbol) {
52187             var links = getSymbolLinks(symbol);
52188             if (!links.declaredType) {
52189                 // Note that we use the links object as the target here because the symbol object is used as the unique
52190                 // identity for resolution of the 'type' property in SymbolLinks.
52191                 if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
52192                     return errorType;
52193                 }
52194                 var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found");
52195                 var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
52196                 // If typeNode is missing, we will error in checkJSDocTypedefTag.
52197                 var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
52198                 if (popTypeResolution()) {
52199                     var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
52200                     if (typeParameters) {
52201                         // Initialize the instantiation cache for generic type aliases. The declared type corresponds to
52202                         // an instantiation of the type alias with the type parameters supplied as type arguments.
52203                         links.typeParameters = typeParameters;
52204                         links.instantiations = new ts.Map();
52205                         links.instantiations.set(getTypeListId(typeParameters), type);
52206                     }
52207                 }
52208                 else {
52209                     type = errorType;
52210                     error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
52211                 }
52212                 links.declaredType = type;
52213             }
52214             return links.declaredType;
52215         }
52216         function isStringConcatExpression(expr) {
52217             if (ts.isStringLiteralLike(expr)) {
52218                 return true;
52219             }
52220             else if (expr.kind === 216 /* BinaryExpression */) {
52221                 return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right);
52222             }
52223             return false;
52224         }
52225         function isLiteralEnumMember(member) {
52226             var expr = member.initializer;
52227             if (!expr) {
52228                 return !(member.flags & 8388608 /* Ambient */);
52229             }
52230             switch (expr.kind) {
52231                 case 10 /* StringLiteral */:
52232                 case 8 /* NumericLiteral */:
52233                 case 14 /* NoSubstitutionTemplateLiteral */:
52234                     return true;
52235                 case 214 /* PrefixUnaryExpression */:
52236                     return expr.operator === 40 /* MinusToken */ &&
52237                         expr.operand.kind === 8 /* NumericLiteral */;
52238                 case 78 /* Identifier */:
52239                     return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText);
52240                 case 216 /* BinaryExpression */:
52241                     return isStringConcatExpression(expr);
52242                 default:
52243                     return false;
52244             }
52245         }
52246         function getEnumKind(symbol) {
52247             var links = getSymbolLinks(symbol);
52248             if (links.enumKind !== undefined) {
52249                 return links.enumKind;
52250             }
52251             var hasNonLiteralMember = false;
52252             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
52253                 var declaration = _a[_i];
52254                 if (declaration.kind === 255 /* EnumDeclaration */) {
52255                     for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
52256                         var member = _c[_b];
52257                         if (member.initializer && ts.isStringLiteralLike(member.initializer)) {
52258                             return links.enumKind = 1 /* Literal */;
52259                         }
52260                         if (!isLiteralEnumMember(member)) {
52261                             hasNonLiteralMember = true;
52262                         }
52263                     }
52264                 }
52265             }
52266             return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */;
52267         }
52268         function getBaseTypeOfEnumLiteralType(type) {
52269             return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
52270         }
52271         function getDeclaredTypeOfEnum(symbol) {
52272             var links = getSymbolLinks(symbol);
52273             if (links.declaredType) {
52274                 return links.declaredType;
52275             }
52276             if (getEnumKind(symbol) === 1 /* Literal */) {
52277                 enumCount++;
52278                 var memberTypeList = [];
52279                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
52280                     var declaration = _a[_i];
52281                     if (declaration.kind === 255 /* EnumDeclaration */) {
52282                         for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
52283                             var member = _c[_b];
52284                             var value = getEnumMemberValue(member);
52285                             var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member)));
52286                             getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType;
52287                             memberTypeList.push(getRegularTypeOfLiteralType(memberType));
52288                         }
52289                     }
52290                 }
52291                 if (memberTypeList.length) {
52292                     var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined);
52293                     if (enumType_1.flags & 1048576 /* Union */) {
52294                         enumType_1.flags |= 1024 /* EnumLiteral */;
52295                         enumType_1.symbol = symbol;
52296                     }
52297                     return links.declaredType = enumType_1;
52298                 }
52299             }
52300             var enumType = createType(32 /* Enum */);
52301             enumType.symbol = symbol;
52302             return links.declaredType = enumType;
52303         }
52304         function getDeclaredTypeOfEnumMember(symbol) {
52305             var links = getSymbolLinks(symbol);
52306             if (!links.declaredType) {
52307                 var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
52308                 if (!links.declaredType) {
52309                     links.declaredType = enumType;
52310                 }
52311             }
52312             return links.declaredType;
52313         }
52314         function getDeclaredTypeOfTypeParameter(symbol) {
52315             var links = getSymbolLinks(symbol);
52316             return links.declaredType || (links.declaredType = createTypeParameter(symbol));
52317         }
52318         function getDeclaredTypeOfAlias(symbol) {
52319             var links = getSymbolLinks(symbol);
52320             return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
52321         }
52322         function getDeclaredTypeOfSymbol(symbol) {
52323             return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
52324         }
52325         function tryGetDeclaredTypeOfSymbol(symbol) {
52326             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
52327                 return getDeclaredTypeOfClassOrInterface(symbol);
52328             }
52329             if (symbol.flags & 524288 /* TypeAlias */) {
52330                 return getDeclaredTypeOfTypeAlias(symbol);
52331             }
52332             if (symbol.flags & 262144 /* TypeParameter */) {
52333                 return getDeclaredTypeOfTypeParameter(symbol);
52334             }
52335             if (symbol.flags & 384 /* Enum */) {
52336                 return getDeclaredTypeOfEnum(symbol);
52337             }
52338             if (symbol.flags & 8 /* EnumMember */) {
52339                 return getDeclaredTypeOfEnumMember(symbol);
52340             }
52341             if (symbol.flags & 2097152 /* Alias */) {
52342                 return getDeclaredTypeOfAlias(symbol);
52343             }
52344             return undefined;
52345         }
52346         /**
52347          * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string
52348          * literal type, an array with an element type that is free of this references, or a type reference that is
52349          * free of this references.
52350          */
52351         function isThislessType(node) {
52352             switch (node.kind) {
52353                 case 128 /* AnyKeyword */:
52354                 case 152 /* UnknownKeyword */:
52355                 case 147 /* StringKeyword */:
52356                 case 144 /* NumberKeyword */:
52357                 case 155 /* BigIntKeyword */:
52358                 case 131 /* BooleanKeyword */:
52359                 case 148 /* SymbolKeyword */:
52360                 case 145 /* ObjectKeyword */:
52361                 case 113 /* VoidKeyword */:
52362                 case 150 /* UndefinedKeyword */:
52363                 case 141 /* NeverKeyword */:
52364                 case 191 /* LiteralType */:
52365                     return true;
52366                 case 178 /* ArrayType */:
52367                     return isThislessType(node.elementType);
52368                 case 173 /* TypeReference */:
52369                     return !node.typeArguments || node.typeArguments.every(isThislessType);
52370             }
52371             return false;
52372         }
52373         /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
52374         function isThislessTypeParameter(node) {
52375             var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
52376             return !constraint || isThislessType(constraint);
52377         }
52378         /**
52379          * A variable-like declaration is free of this references if it has a type annotation
52380          * that is thisless, or if it has no type annotation and no initializer (and is thus of type any).
52381          */
52382         function isThislessVariableLikeDeclaration(node) {
52383             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
52384             return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node);
52385         }
52386         /**
52387          * A function-like declaration is considered free of `this` references if it has a return type
52388          * annotation that is free of this references and if each parameter is thisless and if
52389          * each type parameter (if present) is thisless.
52390          */
52391         function isThislessFunctionLikeDeclaration(node) {
52392             var returnType = ts.getEffectiveReturnTypeNode(node);
52393             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
52394             return (node.kind === 166 /* Constructor */ || (!!returnType && isThislessType(returnType))) &&
52395                 node.parameters.every(isThislessVariableLikeDeclaration) &&
52396                 typeParameters.every(isThislessTypeParameter);
52397         }
52398         /**
52399          * Returns true if the class or interface member given by the symbol is free of "this" references. The
52400          * function may return false for symbols that are actually free of "this" references because it is not
52401          * feasible to perform a complete analysis in all cases. In particular, property members with types
52402          * inferred from their initializers and function members with inferred return types are conservatively
52403          * assumed not to be free of "this" references.
52404          */
52405         function isThisless(symbol) {
52406             if (symbol.declarations && symbol.declarations.length === 1) {
52407                 var declaration = symbol.declarations[0];
52408                 if (declaration) {
52409                     switch (declaration.kind) {
52410                         case 163 /* PropertyDeclaration */:
52411                         case 162 /* PropertySignature */:
52412                             return isThislessVariableLikeDeclaration(declaration);
52413                         case 165 /* MethodDeclaration */:
52414                         case 164 /* MethodSignature */:
52415                         case 166 /* Constructor */:
52416                         case 167 /* GetAccessor */:
52417                         case 168 /* SetAccessor */:
52418                             return isThislessFunctionLikeDeclaration(declaration);
52419                     }
52420                 }
52421             }
52422             return false;
52423         }
52424         // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true,
52425         // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation.
52426         function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
52427             var result = ts.createSymbolTable();
52428             for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
52429                 var symbol = symbols_2[_i];
52430                 result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
52431             }
52432             return result;
52433         }
52434         function addInheritedMembers(symbols, baseSymbols) {
52435             for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) {
52436                 var s = baseSymbols_1[_i];
52437                 if (!symbols.has(s.escapedName) && !isStaticPrivateIdentifierProperty(s)) {
52438                     symbols.set(s.escapedName, s);
52439                 }
52440             }
52441         }
52442         function isStaticPrivateIdentifierProperty(s) {
52443             return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32 /* Static */);
52444         }
52445         function resolveDeclaredMembers(type) {
52446             if (!type.declaredProperties) {
52447                 var symbol = type.symbol;
52448                 var members = getMembersOfSymbol(symbol);
52449                 type.declaredProperties = getNamedMembers(members);
52450                 // Start with signatures at empty array in case of recursive types
52451                 type.declaredCallSignatures = ts.emptyArray;
52452                 type.declaredConstructSignatures = ts.emptyArray;
52453                 type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
52454                 type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
52455                 type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
52456                 type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
52457             }
52458             return type;
52459         }
52460         /**
52461          * Indicates whether a type can be used as a property name.
52462          */
52463         function isTypeUsableAsPropertyName(type) {
52464             return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */);
52465         }
52466         /**
52467          * Indicates whether a declaration name is definitely late-bindable.
52468          * A declaration name is only late-bindable if:
52469          * - It is a `ComputedPropertyName`.
52470          * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an
52471          * `ElementAccessExpression` consisting only of these same three types of nodes.
52472          * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type.
52473          */
52474         function isLateBindableName(node) {
52475             if (!ts.isComputedPropertyName(node) && !ts.isElementAccessExpression(node)) {
52476                 return false;
52477             }
52478             var expr = ts.isComputedPropertyName(node) ? node.expression : node.argumentExpression;
52479             return ts.isEntityNameExpression(expr)
52480                 && isTypeUsableAsPropertyName(ts.isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(expr));
52481         }
52482         function isLateBoundName(name) {
52483             return name.charCodeAt(0) === 95 /* _ */ &&
52484                 name.charCodeAt(1) === 95 /* _ */ &&
52485                 name.charCodeAt(2) === 64 /* at */;
52486         }
52487         /**
52488          * Indicates whether a declaration has a late-bindable dynamic name.
52489          */
52490         function hasLateBindableName(node) {
52491             var name = ts.getNameOfDeclaration(node);
52492             return !!name && isLateBindableName(name);
52493         }
52494         /**
52495          * Indicates whether a declaration has an early-bound name or a dynamic name that can be late-bound.
52496          */
52497         function hasBindableName(node) {
52498             return !ts.hasDynamicName(node) || hasLateBindableName(node);
52499         }
52500         /**
52501          * Indicates whether a declaration name is a dynamic name that cannot be late-bound.
52502          */
52503         function isNonBindableDynamicName(node) {
52504             return ts.isDynamicName(node) && !isLateBindableName(node);
52505         }
52506         /**
52507          * Gets the symbolic name for a member from its type.
52508          */
52509         function getPropertyNameFromType(type) {
52510             if (type.flags & 8192 /* UniqueESSymbol */) {
52511                 return type.escapedName;
52512             }
52513             if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
52514                 return ts.escapeLeadingUnderscores("" + type.value);
52515             }
52516             return ts.Debug.fail();
52517         }
52518         /**
52519          * Adds a declaration to a late-bound dynamic member. This performs the same function for
52520          * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound
52521          * members.
52522          */
52523         function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
52524             ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol.");
52525             symbol.flags |= symbolFlags;
52526             getSymbolLinks(member.symbol).lateSymbol = symbol;
52527             if (!symbol.declarations) {
52528                 symbol.declarations = [member];
52529             }
52530             else {
52531                 symbol.declarations.push(member);
52532             }
52533             if (symbolFlags & 111551 /* Value */) {
52534                 if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
52535                     symbol.valueDeclaration = member;
52536                 }
52537             }
52538         }
52539         /**
52540          * Performs late-binding of a dynamic member. This performs the same function for
52541          * late-bound members that `declareSymbol` in binder.ts performs for early-bound
52542          * members.
52543          *
52544          * If a symbol is a dynamic name from a computed property, we perform an additional "late"
52545          * binding phase to attempt to resolve the name for the symbol from the type of the computed
52546          * property's expression. If the type of the expression is a string-literal, numeric-literal,
52547          * or unique symbol type, we can use that type as the name of the symbol.
52548          *
52549          * For example, given:
52550          *
52551          *   const x = Symbol();
52552          *
52553          *   interface I {
52554          *     [x]: number;
52555          *   }
52556          *
52557          * The binder gives the property `[x]: number` a special symbol with the name "__computed".
52558          * In the late-binding phase we can type-check the expression `x` and see that it has a
52559          * unique symbol type which we can then use as the name of the member. This allows users
52560          * to define custom symbols that can be used in the members of an object type.
52561          *
52562          * @param parent The containing symbol for the member.
52563          * @param earlySymbols The early-bound symbols of the parent.
52564          * @param lateSymbols The late-bound symbols of the parent.
52565          * @param decl The member to bind.
52566          */
52567         function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
52568             ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
52569             var links = getNodeLinks(decl);
52570             if (!links.resolvedSymbol) {
52571                 // In the event we attempt to resolve the late-bound name of this member recursively,
52572                 // fall back to the early-bound name of this member.
52573                 links.resolvedSymbol = decl.symbol;
52574                 var declName = ts.isBinaryExpression(decl) ? decl.left : decl.name;
52575                 var type = ts.isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
52576                 if (isTypeUsableAsPropertyName(type)) {
52577                     var memberName = getPropertyNameFromType(type);
52578                     var symbolFlags = decl.symbol.flags;
52579                     // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations.
52580                     var lateSymbol = lateSymbols.get(memberName);
52581                     if (!lateSymbol)
52582                         lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */));
52583                     // Report an error if a late-bound member has the same name as an early-bound member,
52584                     // or if we have another early-bound symbol declaration with the same name and
52585                     // conflicting flags.
52586                     var earlySymbol = earlySymbols && earlySymbols.get(memberName);
52587                     if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) {
52588                         // If we have an existing early-bound member, combine its declarations so that we can
52589                         // report an error at each declaration.
52590                         var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
52591                         var name_4 = !(type.flags & 8192 /* UniqueESSymbol */) && ts.unescapeLeadingUnderscores(memberName) || ts.declarationNameToString(declName);
52592                         ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Property_0_was_also_declared_here, name_4); });
52593                         error(declName || decl, ts.Diagnostics.Duplicate_property_0, name_4);
52594                         lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */);
52595                     }
52596                     lateSymbol.nameType = type;
52597                     addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
52598                     if (lateSymbol.parent) {
52599                         ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
52600                     }
52601                     else {
52602                         lateSymbol.parent = parent;
52603                     }
52604                     return links.resolvedSymbol = lateSymbol;
52605                 }
52606             }
52607             return links.resolvedSymbol;
52608         }
52609         function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
52610             var links = getSymbolLinks(symbol);
52611             if (!links[resolutionKind]) {
52612                 var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */;
52613                 var earlySymbols = !isStatic ? symbol.members :
52614                     symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) :
52615                         symbol.exports;
52616                 // In the event we recursively resolve the members/exports of the symbol, we
52617                 // set the initial value of resolvedMembers/resolvedExports to the early-bound
52618                 // members/exports of the symbol.
52619                 links[resolutionKind] = earlySymbols || emptySymbols;
52620                 // fill in any as-yet-unresolved late-bound members.
52621                 var lateSymbols = ts.createSymbolTable();
52622                 for (var _i = 0, _a = symbol.declarations || ts.emptyArray; _i < _a.length; _i++) {
52623                     var decl = _a[_i];
52624                     var members = ts.getMembersOfDeclaration(decl);
52625                     if (members) {
52626                         for (var _b = 0, members_5 = members; _b < members_5.length; _b++) {
52627                             var member = members_5[_b];
52628                             if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) {
52629                                 lateBindMember(symbol, earlySymbols, lateSymbols, member);
52630                             }
52631                         }
52632                     }
52633                 }
52634                 var assignments = symbol.assignmentDeclarationMembers;
52635                 if (assignments) {
52636                     var decls = ts.arrayFrom(assignments.values());
52637                     for (var _c = 0, decls_1 = decls; _c < decls_1.length; _c++) {
52638                         var member = decls_1[_c];
52639                         var assignmentKind = ts.getAssignmentDeclarationKind(member);
52640                         var isInstanceMember = assignmentKind === 3 /* PrototypeProperty */
52641                             || ts.isBinaryExpression(member) && isPossiblyAliasedThisProperty(member, assignmentKind)
52642                             || assignmentKind === 9 /* ObjectDefinePrototypeProperty */
52643                             || assignmentKind === 6 /* Prototype */; // A straight `Prototype` assignment probably can never have a computed name
52644                         if (isStatic === !isInstanceMember && hasLateBindableName(member)) {
52645                             lateBindMember(symbol, earlySymbols, lateSymbols, member);
52646                         }
52647                     }
52648                 }
52649                 links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols;
52650             }
52651             return links[resolutionKind];
52652         }
52653         /**
52654          * Gets a SymbolTable containing both the early- and late-bound members of a symbol.
52655          *
52656          * For a description of late-binding, see `lateBindMember`.
52657          */
52658         function getMembersOfSymbol(symbol) {
52659             return symbol.flags & 6256 /* LateBindingContainer */
52660                 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */)
52661                 : symbol.members || emptySymbols;
52662         }
52663         /**
52664          * If a symbol is the dynamic name of the member of an object type, get the late-bound
52665          * symbol of the member.
52666          *
52667          * For a description of late-binding, see `lateBindMember`.
52668          */
52669         function getLateBoundSymbol(symbol) {
52670             if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
52671                 var links = getSymbolLinks(symbol);
52672                 if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) {
52673                     // force late binding of members/exports. This will set the late-bound symbol
52674                     var parent = getMergedSymbol(symbol.parent);
52675                     if (ts.some(symbol.declarations, ts.hasStaticModifier)) {
52676                         getExportsOfSymbol(parent);
52677                     }
52678                     else {
52679                         getMembersOfSymbol(parent);
52680                     }
52681                 }
52682                 return links.lateSymbol || (links.lateSymbol = symbol);
52683             }
52684             return symbol;
52685         }
52686         function getTypeWithThisArgument(type, thisArgument, needApparentType) {
52687             if (ts.getObjectFlags(type) & 4 /* Reference */) {
52688                 var target = type.target;
52689                 var typeArguments = getTypeArguments(type);
52690                 if (ts.length(target.typeParameters) === ts.length(typeArguments)) {
52691                     var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType]));
52692                     return needApparentType ? getApparentType(ref) : ref;
52693                 }
52694             }
52695             else if (type.flags & 2097152 /* Intersection */) {
52696                 var types = ts.sameMap(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); });
52697                 return types !== type.types ? getIntersectionType(types) : type;
52698             }
52699             return needApparentType ? getApparentType(type) : type;
52700         }
52701         function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
52702             var mapper;
52703             var members;
52704             var callSignatures;
52705             var constructSignatures;
52706             var stringIndexInfo;
52707             var numberIndexInfo;
52708             if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
52709                 members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties);
52710                 callSignatures = source.declaredCallSignatures;
52711                 constructSignatures = source.declaredConstructSignatures;
52712                 stringIndexInfo = source.declaredStringIndexInfo;
52713                 numberIndexInfo = source.declaredNumberIndexInfo;
52714             }
52715             else {
52716                 mapper = createTypeMapper(typeParameters, typeArguments);
52717                 members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
52718                 callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
52719                 constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
52720                 stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper);
52721                 numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper);
52722             }
52723             var baseTypes = getBaseTypes(source);
52724             if (baseTypes.length) {
52725                 if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
52726                     members = ts.createSymbolTable(source.declaredProperties);
52727                 }
52728                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
52729                 var thisArgument = ts.lastOrUndefined(typeArguments);
52730                 for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) {
52731                     var baseType = baseTypes_1[_i];
52732                     var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
52733                     addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
52734                     callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
52735                     constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
52736                     if (!stringIndexInfo) {
52737                         stringIndexInfo = instantiatedBaseType === anyType ?
52738                             createIndexInfo(anyType, /*isReadonly*/ false) :
52739                             getIndexInfoOfType(instantiatedBaseType, 0 /* String */);
52740                     }
52741                     numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */);
52742                 }
52743             }
52744             setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
52745         }
52746         function resolveClassOrInterfaceMembers(type) {
52747             resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray);
52748         }
52749         function resolveTypeReferenceMembers(type) {
52750             var source = resolveDeclaredMembers(type.target);
52751             var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]);
52752             var typeArguments = getTypeArguments(type);
52753             var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]);
52754             resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments);
52755         }
52756         function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) {
52757             var sig = new Signature(checker, flags);
52758             sig.declaration = declaration;
52759             sig.typeParameters = typeParameters;
52760             sig.parameters = parameters;
52761             sig.thisParameter = thisParameter;
52762             sig.resolvedReturnType = resolvedReturnType;
52763             sig.resolvedTypePredicate = resolvedTypePredicate;
52764             sig.minArgumentCount = minArgumentCount;
52765             sig.resolvedMinArgumentCount = undefined;
52766             sig.target = undefined;
52767             sig.mapper = undefined;
52768             sig.unionSignatures = undefined;
52769             return sig;
52770         }
52771         function cloneSignature(sig) {
52772             var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, 
52773             /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 39 /* PropagatingFlags */);
52774             result.target = sig.target;
52775             result.mapper = sig.mapper;
52776             result.unionSignatures = sig.unionSignatures;
52777             return result;
52778         }
52779         function createUnionSignature(signature, unionSignatures) {
52780             var result = cloneSignature(signature);
52781             result.unionSignatures = unionSignatures;
52782             result.target = undefined;
52783             result.mapper = undefined;
52784             return result;
52785         }
52786         function getOptionalCallSignature(signature, callChainFlags) {
52787             if ((signature.flags & 24 /* CallChainFlags */) === callChainFlags) {
52788                 return signature;
52789             }
52790             if (!signature.optionalCallSignatureCache) {
52791                 signature.optionalCallSignatureCache = {};
52792             }
52793             var key = callChainFlags === 8 /* IsInnerCallChain */ ? "inner" : "outer";
52794             return signature.optionalCallSignatureCache[key]
52795                 || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
52796         }
52797         function createOptionalCallSignature(signature, callChainFlags) {
52798             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.");
52799             var result = cloneSignature(signature);
52800             result.flags |= callChainFlags;
52801             return result;
52802         }
52803         function getExpandedParameters(sig, skipUnionExpanding) {
52804             if (signatureHasRestParameter(sig)) {
52805                 var restIndex_1 = sig.parameters.length - 1;
52806                 var restType = getTypeOfSymbol(sig.parameters[restIndex_1]);
52807                 if (isTupleType(restType)) {
52808                     return [expandSignatureParametersWithTupleMembers(restType, restIndex_1)];
52809                 }
52810                 else if (!skipUnionExpanding && restType.flags & 1048576 /* Union */ && ts.every(restType.types, isTupleType)) {
52811                     return ts.map(restType.types, function (t) { return expandSignatureParametersWithTupleMembers(t, restIndex_1); });
52812                 }
52813             }
52814             return [sig.parameters];
52815             function expandSignatureParametersWithTupleMembers(restType, restIndex) {
52816                 var elementTypes = getTypeArguments(restType);
52817                 var associatedNames = restType.target.labeledElementDeclarations;
52818                 var restParams = ts.map(elementTypes, function (t, i) {
52819                     // Lookup the label from the individual tuple passed in before falling back to the signature `rest` parameter name
52820                     var tupleLabelName = !!associatedNames && getTupleElementLabel(associatedNames[i]);
52821                     var name = tupleLabelName || getParameterNameAtPosition(sig, restIndex + i, restType);
52822                     var flags = restType.target.elementFlags[i];
52823                     var checkFlags = flags & 12 /* Variable */ ? 32768 /* RestParameter */ :
52824                         flags & 2 /* Optional */ ? 16384 /* OptionalParameter */ : 0;
52825                     var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
52826                     symbol.type = flags & 4 /* Rest */ ? createArrayType(t) : t;
52827                     return symbol;
52828                 });
52829                 return ts.concatenate(sig.parameters.slice(0, restIndex), restParams);
52830             }
52831         }
52832         function getDefaultConstructSignatures(classType) {
52833             var baseConstructorType = getBaseConstructorTypeOfClass(classType);
52834             var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
52835             var declaration = ts.getClassLikeDeclarationOfSymbol(classType.symbol);
52836             var isAbstract = !!declaration && ts.hasSyntacticModifier(declaration, 128 /* Abstract */);
52837             if (baseSignatures.length === 0) {
52838                 return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, isAbstract ? 4 /* Abstract */ : 0 /* None */)];
52839             }
52840             var baseTypeNode = getBaseTypeNodeOfClass(classType);
52841             var isJavaScript = ts.isInJSFile(baseTypeNode);
52842             var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
52843             var typeArgCount = ts.length(typeArguments);
52844             var result = [];
52845             for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) {
52846                 var baseSig = baseSignatures_1[_i];
52847                 var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
52848                 var typeParamCount = ts.length(baseSig.typeParameters);
52849                 if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
52850                     var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
52851                     sig.typeParameters = classType.localTypeParameters;
52852                     sig.resolvedReturnType = classType;
52853                     sig.flags = isAbstract ? sig.flags | 4 /* Abstract */ : sig.flags & ~4 /* Abstract */;
52854                     result.push(sig);
52855                 }
52856             }
52857             return result;
52858         }
52859         function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
52860             for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) {
52861                 var s = signatureList_1[_i];
52862                 if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
52863                     return s;
52864                 }
52865             }
52866         }
52867         function findMatchingSignatures(signatureLists, signature, listIndex) {
52868             if (signature.typeParameters) {
52869                 // We require an exact match for generic signatures, so we only return signatures from the first
52870                 // signature list and only if they have exact matches in the other signature lists.
52871                 if (listIndex > 0) {
52872                     return undefined;
52873                 }
52874                 for (var i = 1; i < signatureLists.length; i++) {
52875                     if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) {
52876                         return undefined;
52877                     }
52878                 }
52879                 return [signature];
52880             }
52881             var result;
52882             for (var i = 0; i < signatureLists.length; i++) {
52883                 // Allow matching non-generic signatures to have excess parameters and different return types.
52884                 // Prefer matching this types if possible.
52885                 var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true);
52886                 if (!match) {
52887                     return undefined;
52888                 }
52889                 result = ts.appendIfUnique(result, match);
52890             }
52891             return result;
52892         }
52893         // The signatures of a union type are those signatures that are present in each of the constituent types.
52894         // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional
52895         // parameters and may differ in return types. When signatures differ in return types, the resulting return
52896         // type is the union of the constituent return types.
52897         function getUnionSignatures(signatureLists) {
52898             var result;
52899             var indexWithLengthOverOne;
52900             for (var i = 0; i < signatureLists.length; i++) {
52901                 if (signatureLists[i].length === 0)
52902                     return ts.emptyArray;
52903                 if (signatureLists[i].length > 1) {
52904                     indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets
52905                 }
52906                 for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
52907                     var signature = _a[_i];
52908                     // Only process signatures with parameter lists that aren't already in the result list
52909                     if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true)) {
52910                         var unionSignatures = findMatchingSignatures(signatureLists, signature, i);
52911                         if (unionSignatures) {
52912                             var s = signature;
52913                             // Union the result types when more than one signature matches
52914                             if (unionSignatures.length > 1) {
52915                                 var thisParameter = signature.thisParameter;
52916                                 var firstThisParameterOfUnionSignatures = ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; });
52917                                 if (firstThisParameterOfUnionSignatures) {
52918                                     var thisType = getIntersectionType(ts.mapDefined(unionSignatures, function (sig) { return sig.thisParameter && getTypeOfSymbol(sig.thisParameter); }));
52919                                     thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
52920                                 }
52921                                 s = createUnionSignature(signature, unionSignatures);
52922                                 s.thisParameter = thisParameter;
52923                             }
52924                             (result || (result = [])).push(s);
52925                         }
52926                     }
52927                 }
52928             }
52929             if (!ts.length(result) && indexWithLengthOverOne !== -1) {
52930                 // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single
52931                 // signature that handles all over them. We only do this when there are overloads in only one constituent.
52932                 // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of
52933                 // signatures from the type, whose ordering would be non-obvious)
52934                 var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0];
52935                 var results = masterList.slice();
52936                 var _loop_10 = function (signatures) {
52937                     if (signatures !== masterList) {
52938                         var signature_1 = signatures[0];
52939                         ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
52940                         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); });
52941                         if (!results) {
52942                             return "break";
52943                         }
52944                     }
52945                 };
52946                 for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) {
52947                     var signatures = signatureLists_1[_b];
52948                     var state_3 = _loop_10(signatures);
52949                     if (state_3 === "break")
52950                         break;
52951                 }
52952                 result = results;
52953             }
52954             return result || ts.emptyArray;
52955         }
52956         function compareTypeParametersIdentical(sourceParams, targetParams) {
52957             if (sourceParams.length !== targetParams.length) {
52958                 return false;
52959             }
52960             var mapper = createTypeMapper(targetParams, sourceParams);
52961             for (var i = 0; i < sourceParams.length; i++) {
52962                 var source = sourceParams[i];
52963                 var target = targetParams[i];
52964                 if (source === target)
52965                     continue;
52966                 // 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>`
52967                 if (!isTypeIdenticalTo(getConstraintFromTypeParameter(source) || unknownType, instantiateType(getConstraintFromTypeParameter(target) || unknownType, mapper)))
52968                     return false;
52969                 // We don't compare defaults - we just use the type parameter defaults from the first signature that seems to match.
52970                 // It might make sense to combine these defaults in the future, but doing so intelligently requires knowing
52971                 // 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)
52972                 // and, since it's just an inference _default_, just picking one arbitrarily works OK.
52973             }
52974             return true;
52975         }
52976         function combineUnionThisParam(left, right, mapper) {
52977             if (!left || !right) {
52978                 return left || right;
52979             }
52980             // A signature `this` type might be a read or a write position... It's very possible that it should be invariant
52981             // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be
52982             // permissive when calling, for now, we'll intersect the `this` types just like we do for param types in union signatures.
52983             var thisType = getIntersectionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]);
52984             return createSymbolWithType(left, thisType);
52985         }
52986         function combineUnionParameters(left, right, mapper) {
52987             var leftCount = getParameterCount(left);
52988             var rightCount = getParameterCount(right);
52989             var longest = leftCount >= rightCount ? left : right;
52990             var shorter = longest === left ? right : left;
52991             var longestCount = longest === left ? leftCount : rightCount;
52992             var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right));
52993             var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
52994             var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
52995             for (var i = 0; i < longestCount; i++) {
52996                 var longestParamType = tryGetTypeAtPosition(longest, i);
52997                 if (longest === right) {
52998                     longestParamType = instantiateType(longestParamType, mapper);
52999                 }
53000                 var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
53001                 if (shorter === right) {
53002                     shorterParamType = instantiateType(shorterParamType, mapper);
53003                 }
53004                 var unionParamType = getIntersectionType([longestParamType, shorterParamType]);
53005                 var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1);
53006                 var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
53007                 var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i);
53008                 var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i);
53009                 var paramName = leftName === rightName ? leftName :
53010                     !leftName ? rightName :
53011                         !rightName ? leftName :
53012                             undefined;
53013                 var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i);
53014                 paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
53015                 params[i] = paramSymbol;
53016             }
53017             if (needsExtraRestElement) {
53018                 var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args");
53019                 restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount));
53020                 if (shorter === right) {
53021                     restParamSymbol.type = instantiateType(restParamSymbol.type, mapper);
53022                 }
53023                 params[longestCount] = restParamSymbol;
53024             }
53025             return params;
53026         }
53027         function combineSignaturesOfUnionMembers(left, right) {
53028             var typeParams = left.typeParameters || right.typeParameters;
53029             var paramMapper;
53030             if (left.typeParameters && right.typeParameters) {
53031                 paramMapper = createTypeMapper(right.typeParameters, left.typeParameters);
53032                 // We just use the type parameter defaults from the first signature
53033             }
53034             var declaration = left.declaration;
53035             var params = combineUnionParameters(left, right, paramMapper);
53036             var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter, paramMapper);
53037             var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
53038             var result = createSignature(declaration, typeParams, thisParam, params, 
53039             /*resolvedReturnType*/ undefined, 
53040             /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 39 /* PropagatingFlags */);
53041             result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]);
53042             if (paramMapper) {
53043                 result.mapper = left.mapper && left.unionSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper;
53044             }
53045             return result;
53046         }
53047         function getUnionIndexInfo(types, kind) {
53048             var indexTypes = [];
53049             var isAnyReadonly = false;
53050             for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
53051                 var type = types_4[_i];
53052                 var indexInfo = getIndexInfoOfType(getApparentType(type), kind);
53053                 if (!indexInfo) {
53054                     return undefined;
53055                 }
53056                 indexTypes.push(indexInfo.type);
53057                 isAnyReadonly = isAnyReadonly || indexInfo.isReadonly;
53058             }
53059             return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly);
53060         }
53061         function resolveUnionTypeMembers(type) {
53062             // The members and properties collections are empty for union types. To get all properties of a union
53063             // type use getPropertiesOfType (only the language service uses this).
53064             var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); }));
53065             var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); }));
53066             var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */);
53067             var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */);
53068             setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
53069         }
53070         function intersectTypes(type1, type2) {
53071             return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
53072         }
53073         function intersectIndexInfos(info1, info2) {
53074             return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly);
53075         }
53076         function unionSpreadIndexInfos(info1, info2) {
53077             return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
53078         }
53079         function findMixins(types) {
53080             var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
53081             var mixinFlags = ts.map(types, isMixinConstructorType);
53082             if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
53083                 var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
53084                 mixinFlags[firstMixinIndex] = false;
53085             }
53086             return mixinFlags;
53087         }
53088         function includeMixinType(type, types, mixinFlags, index) {
53089             var mixedTypes = [];
53090             for (var i = 0; i < types.length; i++) {
53091                 if (i === index) {
53092                     mixedTypes.push(type);
53093                 }
53094                 else if (mixinFlags[i]) {
53095                     mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
53096                 }
53097             }
53098             return getIntersectionType(mixedTypes);
53099         }
53100         function resolveIntersectionTypeMembers(type) {
53101             // The members and properties collections are empty for intersection types. To get all properties of an
53102             // intersection type use getPropertiesOfType (only the language service uses this).
53103             var callSignatures;
53104             var constructSignatures;
53105             var stringIndexInfo;
53106             var numberIndexInfo;
53107             var types = type.types;
53108             var mixinFlags = findMixins(types);
53109             var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
53110             var _loop_11 = function (i) {
53111                 var t = type.types[i];
53112                 // When an intersection type contains mixin constructor types, the construct signatures from
53113                 // those types are discarded and their return types are mixed into the return types of all
53114                 // other construct signatures in the intersection type. For example, the intersection type
53115                 // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
53116                 // 'new(s: string) => A & B'.
53117                 if (!mixinFlags[i]) {
53118                     var signatures = getSignaturesOfType(t, 1 /* Construct */);
53119                     if (signatures.length && mixinCount > 0) {
53120                         signatures = ts.map(signatures, function (s) {
53121                             var clone = cloneSignature(s);
53122                             clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
53123                             return clone;
53124                         });
53125                     }
53126                     constructSignatures = appendSignatures(constructSignatures, signatures);
53127                 }
53128                 callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */));
53129                 stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */));
53130                 numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */));
53131             };
53132             for (var i = 0; i < types.length; i++) {
53133                 _loop_11(i);
53134             }
53135             setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo);
53136         }
53137         function appendSignatures(signatures, newSignatures) {
53138             var _loop_12 = function (sig) {
53139                 if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) {
53140                     signatures = ts.append(signatures, sig);
53141                 }
53142             };
53143             for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) {
53144                 var sig = newSignatures_1[_i];
53145                 _loop_12(sig);
53146             }
53147             return signatures;
53148         }
53149         /**
53150          * Converts an AnonymousType to a ResolvedType.
53151          */
53152         function resolveAnonymousTypeMembers(type) {
53153             var symbol = getMergedSymbol(type.symbol);
53154             if (type.target) {
53155                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
53156                 var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false);
53157                 var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
53158                 var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
53159                 var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper);
53160                 var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper);
53161                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
53162             }
53163             else if (symbol.flags & 2048 /* TypeLiteral */) {
53164                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
53165                 var members = getMembersOfSymbol(symbol);
53166                 var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
53167                 var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
53168                 var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
53169                 var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
53170                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
53171             }
53172             else {
53173                 // Combinations of function, class, enum and module
53174                 var members = emptySymbols;
53175                 var stringIndexInfo = void 0;
53176                 if (symbol.exports) {
53177                     members = getExportsOfSymbol(symbol);
53178                     if (symbol === globalThisSymbol) {
53179                         var varsOnly_1 = new ts.Map();
53180                         members.forEach(function (p) {
53181                             if (!(p.flags & 418 /* BlockScoped */)) {
53182                                 varsOnly_1.set(p.escapedName, p);
53183                             }
53184                         });
53185                         members = varsOnly_1;
53186                     }
53187                 }
53188                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
53189                 if (symbol.flags & 32 /* Class */) {
53190                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
53191                     var baseConstructorType = getBaseConstructorTypeOfClass(classType);
53192                     if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) {
53193                         members = ts.createSymbolTable(getNamedMembers(members));
53194                         addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
53195                     }
53196                     else if (baseConstructorType === anyType) {
53197                         stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
53198                     }
53199                 }
53200                 var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ ||
53201                     ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined;
53202                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
53203                 // We resolve the members before computing the signatures because a signature may use
53204                 // typeof with a qualified name expression that circularly references the type we are
53205                 // in the process of resolving (see issue #6072). The temporarily empty signature list
53206                 // will never be observed because a qualified name can't reference signatures.
53207                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
53208                     type.callSignatures = getSignaturesOfSymbol(symbol);
53209                 }
53210                 // And likewise for construct signatures for classes
53211                 if (symbol.flags & 32 /* Class */) {
53212                     var classType_1 = getDeclaredTypeOfClassOrInterface(symbol);
53213                     var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray;
53214                     if (symbol.flags & 16 /* Function */) {
53215                         constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ?
53216                             createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 39 /* PropagatingFlags */) :
53217                             undefined; }));
53218                     }
53219                     if (!constructSignatures.length) {
53220                         constructSignatures = getDefaultConstructSignatures(classType_1);
53221                     }
53222                     type.constructSignatures = constructSignatures;
53223                 }
53224             }
53225         }
53226         function resolveReverseMappedTypeMembers(type) {
53227             var indexInfo = getIndexInfoOfType(type.source, 0 /* String */);
53228             var modifiers = getMappedTypeModifiers(type.mappedType);
53229             var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
53230             var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
53231             var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly);
53232             var members = ts.createSymbolTable();
53233             for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) {
53234                 var prop = _a[_i];
53235                 var checkFlags = 8192 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
53236                 var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
53237                 inferredProp.declarations = prop.declarations;
53238                 inferredProp.nameType = getSymbolLinks(prop).nameType;
53239                 inferredProp.propertyType = getTypeOfSymbol(prop);
53240                 inferredProp.mappedType = type.mappedType;
53241                 inferredProp.constraintType = type.constraintType;
53242                 members.set(prop.escapedName, inferredProp);
53243             }
53244             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
53245         }
53246         // Return the lower bound of the key type in a mapped type. Intuitively, the lower
53247         // bound includes those keys that are known to always be present, for example because
53248         // because of constraints on type parameters (e.g. 'keyof T' for a constrained T).
53249         function getLowerBoundOfKeyType(type) {
53250             if (type.flags & 4194304 /* Index */) {
53251                 var t = getApparentType(type.type);
53252                 return isGenericTupleType(t) ? getKnownKeysOfTupleType(t) : getIndexType(t);
53253             }
53254             if (type.flags & 16777216 /* Conditional */) {
53255                 if (type.root.isDistributive) {
53256                     var checkType = type.checkType;
53257                     var constraint = getLowerBoundOfKeyType(checkType);
53258                     if (constraint !== checkType) {
53259                         return getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
53260                     }
53261                 }
53262                 return type;
53263             }
53264             if (type.flags & 1048576 /* Union */) {
53265                 return mapType(type, getLowerBoundOfKeyType);
53266             }
53267             if (type.flags & 2097152 /* Intersection */) {
53268                 return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
53269             }
53270             return type;
53271         }
53272         function getIsLateCheckFlag(s) {
53273             return ts.getCheckFlags(s) & 4096 /* Late */;
53274         }
53275         /** Resolve the members of a mapped type { [P in K]: T } */
53276         function resolveMappedTypeMembers(type) {
53277             var members = ts.createSymbolTable();
53278             var stringIndexInfo;
53279             var numberIndexInfo;
53280             // Resolve upfront such that recursive references see an empty object type.
53281             setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
53282             // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
53283             // and T as the template type.
53284             var typeParameter = getTypeParameterFromMappedType(type);
53285             var constraintType = getConstraintTypeFromMappedType(type);
53286             var nameType = getNameTypeFromMappedType(type.target || type);
53287             var templateType = getTemplateTypeFromMappedType(type.target || type);
53288             var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
53289             var templateModifiers = getMappedTypeModifiers(type);
53290             var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */;
53291             if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
53292                 // We have a { [P in keyof T]: X }
53293                 for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
53294                     var prop = _a[_i];
53295                     addMemberForKeyType(getLiteralTypeFromProperty(prop, include));
53296                 }
53297                 if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) {
53298                     addMemberForKeyType(stringType);
53299                 }
53300                 if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) {
53301                     addMemberForKeyType(numberType);
53302                 }
53303             }
53304             else {
53305                 forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
53306             }
53307             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
53308             function addMemberForKeyType(keyType) {
53309                 var propNameType = nameType ? instantiateType(nameType, appendTypeMapping(type.mapper, typeParameter, keyType)) : keyType;
53310                 forEachType(propNameType, function (t) { return addMemberForKeyTypeWorker(keyType, t); });
53311             }
53312             function addMemberForKeyTypeWorker(keyType, propNameType) {
53313                 // If the current iteration type constituent is a string literal type, create a property.
53314                 // Otherwise, for type string create a string index signature.
53315                 if (isTypeUsableAsPropertyName(propNameType)) {
53316                     var propName = getPropertyNameFromType(propNameType);
53317                     // String enum members from separate enums with identical values
53318                     // are distinct types with the same property name. Make the resulting
53319                     // property symbol's name type be the union of those enum member types.
53320                     var existingProp = members.get(propName);
53321                     if (existingProp) {
53322                         existingProp.nameType = getUnionType([existingProp.nameType, propNameType]);
53323                         existingProp.keyType = getUnionType([existingProp.keyType, keyType]);
53324                     }
53325                     else {
53326                         var modifiersProp = isTypeUsableAsPropertyName(keyType) ? getPropertyOfType(modifiersType, getPropertyNameFromType(keyType)) : undefined;
53327                         var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
53328                             !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
53329                         var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ ||
53330                             !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
53331                         var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */;
53332                         var lateFlag = modifiersProp ? getIsLateCheckFlag(modifiersProp) : 0;
53333                         var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, lateFlag | 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0));
53334                         prop.mappedType = type;
53335                         prop.nameType = propNameType;
53336                         prop.keyType = keyType;
53337                         if (modifiersProp) {
53338                             prop.syntheticOrigin = modifiersProp;
53339                             prop.declarations = modifiersProp.declarations;
53340                         }
53341                         members.set(propName, prop);
53342                     }
53343                 }
53344                 else if (propNameType.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) {
53345                     var propType = instantiateType(templateType, appendTypeMapping(type.mapper, typeParameter, keyType));
53346                     if (propNameType.flags & (1 /* Any */ | 4 /* String */)) {
53347                         stringIndexInfo = createIndexInfo(stringIndexInfo ? getUnionType([stringIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */));
53348                     }
53349                     else {
53350                         numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */));
53351                     }
53352                 }
53353             }
53354         }
53355         function getTypeOfMappedSymbol(symbol) {
53356             if (!symbol.type) {
53357                 var mappedType = symbol.mappedType;
53358                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
53359                     mappedType.containsError = true;
53360                     return errorType;
53361                 }
53362                 var templateType = getTemplateTypeFromMappedType(mappedType.target || mappedType);
53363                 var mapper = appendTypeMapping(mappedType.mapper, getTypeParameterFromMappedType(mappedType), symbol.keyType);
53364                 var propType = instantiateType(templateType, mapper);
53365                 // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the
53366                 // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks
53367                 // mode, if the underlying property is optional we remove 'undefined' from the type.
53368                 var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
53369                     symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
53370                         propType;
53371                 if (!popTypeResolution()) {
53372                     error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(mappedType));
53373                     type = errorType;
53374                 }
53375                 symbol.type = type;
53376             }
53377             return symbol.type;
53378         }
53379         function getTypeParameterFromMappedType(type) {
53380             return type.typeParameter ||
53381                 (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter)));
53382         }
53383         function getConstraintTypeFromMappedType(type) {
53384             return type.constraintType ||
53385                 (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
53386         }
53387         function getNameTypeFromMappedType(type) {
53388             return type.declaration.nameType ?
53389                 type.nameType || (type.nameType = instantiateType(getTypeFromTypeNode(type.declaration.nameType), type.mapper)) :
53390                 undefined;
53391         }
53392         function getTemplateTypeFromMappedType(type) {
53393             return type.templateType ||
53394                 (type.templateType = type.declaration.type ?
53395                     instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper) :
53396                     errorType);
53397         }
53398         function getConstraintDeclarationForMappedType(type) {
53399             return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
53400         }
53401         function isMappedTypeWithKeyofConstraintDeclaration(type) {
53402             var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217
53403             return constraintDeclaration.kind === 188 /* TypeOperator */ &&
53404                 constraintDeclaration.operator === 138 /* KeyOfKeyword */;
53405         }
53406         function getModifiersTypeFromMappedType(type) {
53407             if (!type.modifiersType) {
53408                 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
53409                     // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
53410                     // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
53411                     // 'keyof T' to a literal union type and we can't recover T from that type.
53412                     type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper);
53413                 }
53414                 else {
53415                     // Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
53416                     // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T',
53417                     // the modifiers type is T. Otherwise, the modifiers type is unknown.
53418                     var declaredType = getTypeFromMappedTypeNode(type.declaration);
53419                     var constraint = getConstraintTypeFromMappedType(declaredType);
53420                     var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
53421                     type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper) : unknownType;
53422                 }
53423             }
53424             return type.modifiersType;
53425         }
53426         function getMappedTypeModifiers(type) {
53427             var declaration = type.declaration;
53428             return (declaration.readonlyToken ? declaration.readonlyToken.kind === 40 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) |
53429                 (declaration.questionToken ? declaration.questionToken.kind === 40 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
53430         }
53431         function getMappedTypeOptionality(type) {
53432             var modifiers = getMappedTypeModifiers(type);
53433             return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
53434         }
53435         function getCombinedMappedTypeOptionality(type) {
53436             var optionality = getMappedTypeOptionality(type);
53437             var modifiersType = getModifiersTypeFromMappedType(type);
53438             return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0);
53439         }
53440         function isPartialMappedType(type) {
53441             return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
53442         }
53443         function isGenericMappedType(type) {
53444             return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type));
53445         }
53446         function resolveStructuredTypeMembers(type) {
53447             if (!type.members) {
53448                 if (type.flags & 524288 /* Object */) {
53449                     if (type.objectFlags & 4 /* Reference */) {
53450                         resolveTypeReferenceMembers(type);
53451                     }
53452                     else if (type.objectFlags & 3 /* ClassOrInterface */) {
53453                         resolveClassOrInterfaceMembers(type);
53454                     }
53455                     else if (type.objectFlags & 2048 /* ReverseMapped */) {
53456                         resolveReverseMappedTypeMembers(type);
53457                     }
53458                     else if (type.objectFlags & 16 /* Anonymous */) {
53459                         resolveAnonymousTypeMembers(type);
53460                     }
53461                     else if (type.objectFlags & 32 /* Mapped */) {
53462                         resolveMappedTypeMembers(type);
53463                     }
53464                 }
53465                 else if (type.flags & 1048576 /* Union */) {
53466                     resolveUnionTypeMembers(type);
53467                 }
53468                 else if (type.flags & 2097152 /* Intersection */) {
53469                     resolveIntersectionTypeMembers(type);
53470                 }
53471             }
53472             return type;
53473         }
53474         /** Return properties of an object type or an empty array for other types */
53475         function getPropertiesOfObjectType(type) {
53476             if (type.flags & 524288 /* Object */) {
53477                 return resolveStructuredTypeMembers(type).properties;
53478             }
53479             return ts.emptyArray;
53480         }
53481         /** If the given type is an object type and that type has a property by the given name,
53482          * return the symbol for that property. Otherwise return undefined.
53483          */
53484         function getPropertyOfObjectType(type, name) {
53485             if (type.flags & 524288 /* Object */) {
53486                 var resolved = resolveStructuredTypeMembers(type);
53487                 var symbol = resolved.members.get(name);
53488                 if (symbol && symbolIsValue(symbol)) {
53489                     return symbol;
53490                 }
53491             }
53492         }
53493         function getPropertiesOfUnionOrIntersectionType(type) {
53494             if (!type.resolvedProperties) {
53495                 var members = ts.createSymbolTable();
53496                 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
53497                     var current = _a[_i];
53498                     for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
53499                         var prop = _c[_b];
53500                         if (!members.has(prop.escapedName)) {
53501                             var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName);
53502                             if (combinedProp) {
53503                                 members.set(prop.escapedName, combinedProp);
53504                             }
53505                         }
53506                     }
53507                     // The properties of a union type are those that are present in all constituent types, so
53508                     // we only need to check the properties of the first type without index signature
53509                     if (type.flags & 1048576 /* Union */ && !getIndexInfoOfType(current, 0 /* String */) && !getIndexInfoOfType(current, 1 /* Number */)) {
53510                         break;
53511                     }
53512                 }
53513                 type.resolvedProperties = getNamedMembers(members);
53514             }
53515             return type.resolvedProperties;
53516         }
53517         function getPropertiesOfType(type) {
53518             type = getReducedApparentType(type);
53519             return type.flags & 3145728 /* UnionOrIntersection */ ?
53520                 getPropertiesOfUnionOrIntersectionType(type) :
53521                 getPropertiesOfObjectType(type);
53522         }
53523         function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
53524             var list = obj.properties;
53525             return list.some(function (property) {
53526                 var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
53527                 var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
53528                 var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
53529                 return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
53530             });
53531         }
53532         function getAllPossiblePropertiesOfTypes(types) {
53533             var unionType = getUnionType(types);
53534             if (!(unionType.flags & 1048576 /* Union */)) {
53535                 return getAugmentedPropertiesOfType(unionType);
53536             }
53537             var props = ts.createSymbolTable();
53538             for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
53539                 var memberType = types_5[_i];
53540                 for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) {
53541                     var escapedName = _b[_a].escapedName;
53542                     if (!props.has(escapedName)) {
53543                         var prop = createUnionOrIntersectionProperty(unionType, escapedName);
53544                         // May be undefined if the property is private
53545                         if (prop)
53546                             props.set(escapedName, prop);
53547                     }
53548                 }
53549             }
53550             return ts.arrayFrom(props.values());
53551         }
53552         function getConstraintOfType(type) {
53553             return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) :
53554                 type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) :
53555                     type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) :
53556                         getBaseConstraintOfType(type);
53557         }
53558         function getConstraintOfTypeParameter(typeParameter) {
53559             return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
53560         }
53561         function getConstraintOfIndexedAccess(type) {
53562             return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
53563         }
53564         function getSimplifiedTypeOrConstraint(type) {
53565             var simplified = getSimplifiedType(type, /*writing*/ false);
53566             return simplified !== type ? simplified : getConstraintOfType(type);
53567         }
53568         function getConstraintFromIndexedAccess(type) {
53569             var indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
53570             if (indexConstraint && indexConstraint !== type.indexType) {
53571                 var indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint, type.noUncheckedIndexedAccessCandidate);
53572                 if (indexedAccess) {
53573                     return indexedAccess;
53574                 }
53575             }
53576             var objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
53577             if (objectConstraint && objectConstraint !== type.objectType) {
53578                 return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType, type.noUncheckedIndexedAccessCandidate);
53579             }
53580             return undefined;
53581         }
53582         function getDefaultConstraintOfConditionalType(type) {
53583             if (!type.resolvedDefaultConstraint) {
53584                 // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
53585                 // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
53586                 // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
53587                 // in effect treating `any` like `never` rather than `unknown` in this location.
53588                 var trueConstraint = getInferredTrueTypeFromConditionalType(type);
53589                 var falseConstraint = getFalseTypeFromConditionalType(type);
53590                 type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
53591             }
53592             return type.resolvedDefaultConstraint;
53593         }
53594         function getConstraintOfDistributiveConditionalType(type) {
53595             // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
53596             // type parameter. If so, create an instantiation of the conditional type where T is replaced
53597             // with its constraint. We do this because if the constraint is a union type it will be distributed
53598             // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
53599             // removes 'undefined' from T.
53600             // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
53601             // as the constraint for all type params (check type included) have been replace with `unknown`, which
53602             // is going to produce even more false positive/negative results than the distribute constraint already does.
53603             // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
53604             // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
53605             // likely doesn't need to exist.
53606             if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
53607                 var simplified = getSimplifiedType(type.checkType, /*writing*/ false);
53608                 var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
53609                 if (constraint && constraint !== type.checkType) {
53610                     var instantiated = getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
53611                     if (!(instantiated.flags & 131072 /* Never */)) {
53612                         return instantiated;
53613                     }
53614                 }
53615             }
53616             return undefined;
53617         }
53618         function getConstraintFromConditionalType(type) {
53619             return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
53620         }
53621         function getConstraintOfConditionalType(type) {
53622             return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
53623         }
53624         function getEffectiveConstraintOfIntersection(types, targetIsUnion) {
53625             var constraints;
53626             var hasDisjointDomainType = false;
53627             for (var _i = 0, types_6 = types; _i < types_6.length; _i++) {
53628                 var t = types_6[_i];
53629                 if (t.flags & 465829888 /* Instantiable */) {
53630                     // We keep following constraints as long as we have an instantiable type that is known
53631                     // not to be circular or infinite (hence we stop on index access types).
53632                     var constraint = getConstraintOfType(t);
53633                     while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) {
53634                         constraint = getConstraintOfType(constraint);
53635                     }
53636                     if (constraint) {
53637                         constraints = ts.append(constraints, constraint);
53638                         if (targetIsUnion) {
53639                             constraints = ts.append(constraints, t);
53640                         }
53641                     }
53642                 }
53643                 else if (t.flags & 469892092 /* DisjointDomains */) {
53644                     hasDisjointDomainType = true;
53645                 }
53646             }
53647             // If the target is a union type or if we are intersecting with types belonging to one of the
53648             // disjoint domains, we may end up producing a constraint that hasn't been examined before.
53649             if (constraints && (targetIsUnion || hasDisjointDomainType)) {
53650                 if (hasDisjointDomainType) {
53651                     // We add any types belong to one of the disjoint domains because they might cause the final
53652                     // intersection operation to reduce the union constraints.
53653                     for (var _a = 0, types_7 = types; _a < types_7.length; _a++) {
53654                         var t = types_7[_a];
53655                         if (t.flags & 469892092 /* DisjointDomains */) {
53656                             constraints = ts.append(constraints, t);
53657                         }
53658                     }
53659                 }
53660                 return getIntersectionType(constraints);
53661             }
53662             return undefined;
53663         }
53664         function getBaseConstraintOfType(type) {
53665             if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) {
53666                 var constraint = getResolvedBaseConstraint(type);
53667                 return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined;
53668             }
53669             return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined;
53670         }
53671         /**
53672          * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
53673          * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
53674          */
53675         function getBaseConstraintOrType(type) {
53676             return getBaseConstraintOfType(type) || type;
53677         }
53678         function hasNonCircularBaseConstraint(type) {
53679             return getResolvedBaseConstraint(type) !== circularConstraintType;
53680         }
53681         /**
53682          * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the
53683          * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint
53684          * circularly references the type variable.
53685          */
53686         function getResolvedBaseConstraint(type) {
53687             if (type.resolvedBaseConstraint) {
53688                 return type.resolvedBaseConstraint;
53689             }
53690             var stack = [];
53691             return type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type);
53692             function getImmediateBaseConstraint(t) {
53693                 if (!t.immediateBaseConstraint) {
53694                     if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
53695                         return circularConstraintType;
53696                     }
53697                     var result = void 0;
53698                     // We always explore at least 10 levels of nested constraints. Thereafter, we continue to explore
53699                     // up to 50 levels of nested constraints provided there are no "deeply nested" types on the stack
53700                     // (i.e. no types for which five instantiations have been recorded on the stack). If we reach 50
53701                     // levels of nesting, we are presumably exploring a repeating pattern with a long cycle that hasn't
53702                     // yet triggered the deeply nested limiter. We have no test cases that actually get to 50 levels of
53703                     // nesting, so it is effectively just a safety stop.
53704                     if (stack.length < 10 || stack.length < 50 && !isDeeplyNestedType(t, stack, stack.length)) {
53705                         stack.push(t);
53706                         result = computeBaseConstraint(getSimplifiedType(t, /*writing*/ false));
53707                         stack.pop();
53708                     }
53709                     if (!popTypeResolution()) {
53710                         if (t.flags & 262144 /* TypeParameter */) {
53711                             var errorNode = getConstraintDeclaration(t);
53712                             if (errorNode) {
53713                                 var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
53714                                 if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
53715                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
53716                                 }
53717                             }
53718                         }
53719                         result = circularConstraintType;
53720                     }
53721                     t.immediateBaseConstraint = result || noConstraintType;
53722                 }
53723                 return t.immediateBaseConstraint;
53724             }
53725             function getBaseConstraint(t) {
53726                 var c = getImmediateBaseConstraint(t);
53727                 return c !== noConstraintType && c !== circularConstraintType ? c : undefined;
53728             }
53729             function computeBaseConstraint(t) {
53730                 if (t.flags & 262144 /* TypeParameter */) {
53731                     var constraint = getConstraintFromTypeParameter(t);
53732                     return t.isThisType || !constraint ?
53733                         constraint :
53734                         getBaseConstraint(constraint);
53735                 }
53736                 if (t.flags & 3145728 /* UnionOrIntersection */) {
53737                     var types = t.types;
53738                     var baseTypes = [];
53739                     var different = false;
53740                     for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
53741                         var type_3 = types_8[_i];
53742                         var baseType = getBaseConstraint(type_3);
53743                         if (baseType) {
53744                             if (baseType !== type_3) {
53745                                 different = true;
53746                             }
53747                             baseTypes.push(baseType);
53748                         }
53749                         else {
53750                             different = true;
53751                         }
53752                     }
53753                     if (!different) {
53754                         return t;
53755                     }
53756                     return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
53757                         t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
53758                             undefined;
53759                 }
53760                 if (t.flags & 4194304 /* Index */) {
53761                     return keyofConstraintType;
53762                 }
53763                 if (t.flags & 134217728 /* TemplateLiteral */) {
53764                     var types = t.types;
53765                     var constraints = ts.mapDefined(types, getBaseConstraint);
53766                     return constraints.length === types.length ? getTemplateLiteralType(t.texts, constraints) : stringType;
53767                 }
53768                 if (t.flags & 268435456 /* StringMapping */) {
53769                     var constraint = getBaseConstraint(t.type);
53770                     return constraint ? getStringMappingType(t.symbol, constraint) : stringType;
53771                 }
53772                 if (t.flags & 8388608 /* IndexedAccess */) {
53773                     var baseObjectType = getBaseConstraint(t.objectType);
53774                     var baseIndexType = getBaseConstraint(t.indexType);
53775                     var baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, t.noUncheckedIndexedAccessCandidate);
53776                     return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
53777                 }
53778                 if (t.flags & 16777216 /* Conditional */) {
53779                     var constraint = getConstraintFromConditionalType(t);
53780                     return constraint && getBaseConstraint(constraint);
53781                 }
53782                 if (t.flags & 33554432 /* Substitution */) {
53783                     return getBaseConstraint(t.substitute);
53784                 }
53785                 return t;
53786             }
53787         }
53788         function getApparentTypeOfIntersectionType(type) {
53789             return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true));
53790         }
53791         function getResolvedTypeParameterDefault(typeParameter) {
53792             if (!typeParameter.default) {
53793                 if (typeParameter.target) {
53794                     var targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
53795                     typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
53796                 }
53797                 else {
53798                     // To block recursion, set the initial value to the resolvingDefaultType.
53799                     typeParameter.default = resolvingDefaultType;
53800                     var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; });
53801                     var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
53802                     if (typeParameter.default === resolvingDefaultType) {
53803                         // If we have not been called recursively, set the correct default type.
53804                         typeParameter.default = defaultType;
53805                     }
53806                 }
53807             }
53808             else if (typeParameter.default === resolvingDefaultType) {
53809                 // If we are called recursively for this type parameter, mark the default as circular.
53810                 typeParameter.default = circularConstraintType;
53811             }
53812             return typeParameter.default;
53813         }
53814         /**
53815          * Gets the default type for a type parameter.
53816          *
53817          * If the type parameter is the result of an instantiation, this gets the instantiated
53818          * default type of its target. If the type parameter has no default type or the default is
53819          * circular, `undefined` is returned.
53820          */
53821         function getDefaultFromTypeParameter(typeParameter) {
53822             var defaultType = getResolvedTypeParameterDefault(typeParameter);
53823             return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined;
53824         }
53825         function hasNonCircularTypeParameterDefault(typeParameter) {
53826             return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
53827         }
53828         /**
53829          * Indicates whether the declaration of a typeParameter has a default type.
53830          */
53831         function hasTypeParameterDefault(typeParameter) {
53832             return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }));
53833         }
53834         function getApparentTypeOfMappedType(type) {
53835             return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
53836         }
53837         function getResolvedApparentTypeOfMappedType(type) {
53838             var typeVariable = getHomomorphicTypeVariable(type);
53839             if (typeVariable && !type.declaration.nameType) {
53840                 var constraint = getConstraintOfTypeParameter(typeVariable);
53841                 if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
53842                     return instantiateType(type, prependTypeMapping(typeVariable, constraint, type.mapper));
53843                 }
53844             }
53845             return type;
53846         }
53847         /**
53848          * For a type parameter, return the base constraint of the type parameter. For the string, number,
53849          * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
53850          * type itself.
53851          */
53852         function getApparentType(type) {
53853             var t = type.flags & 465829888 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type;
53854             return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) :
53855                 t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
53856                     t.flags & 402653316 /* StringLike */ ? globalStringType :
53857                         t.flags & 296 /* NumberLike */ ? globalNumberType :
53858                             t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) :
53859                                 t.flags & 528 /* BooleanLike */ ? globalBooleanType :
53860                                     t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
53861                                         t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
53862                                             t.flags & 4194304 /* Index */ ? keyofConstraintType :
53863                                                 t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType :
53864                                                     t;
53865         }
53866         function getReducedApparentType(type) {
53867             // Since getApparentType may return a non-reduced union or intersection type, we need to perform
53868             // type reduction both before and after obtaining the apparent type. For example, given a type parameter
53869             // 'T extends A | B', the type 'T & X' becomes 'A & X | B & X' after obtaining the apparent type, and
53870             // that type may need further reduction to remove empty intersections.
53871             return getReducedType(getApparentType(getReducedType(type)));
53872         }
53873         function createUnionOrIntersectionProperty(containingType, name, skipObjectFunctionPropertyAugment) {
53874             var singleProp;
53875             var propSet;
53876             var indexTypes;
53877             var isUnion = containingType.flags & 1048576 /* Union */;
53878             // Flags we want to propagate to the result if they exist in all source symbols
53879             var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */;
53880             var syntheticFlag = 4 /* SyntheticMethod */;
53881             var checkFlags = 0;
53882             for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
53883                 var current = _a[_i];
53884                 var type = getApparentType(current);
53885                 if (!(type === errorType || type.flags & 131072 /* Never */)) {
53886                     var prop = getPropertyOfType(type, name, skipObjectFunctionPropertyAugment);
53887                     var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
53888                     if (prop) {
53889                         if (isUnion) {
53890                             optionalFlag |= (prop.flags & 16777216 /* Optional */);
53891                         }
53892                         else {
53893                             optionalFlag &= prop.flags;
53894                         }
53895                         if (!singleProp) {
53896                             singleProp = prop;
53897                         }
53898                         else if (prop !== singleProp) {
53899                             if (!propSet) {
53900                                 propSet = new ts.Map();
53901                                 propSet.set(getSymbolId(singleProp), singleProp);
53902                             }
53903                             var id = getSymbolId(prop);
53904                             if (!propSet.has(id)) {
53905                                 propSet.set(id, prop);
53906                             }
53907                         }
53908                         checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
53909                             (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) |
53910                             (modifiers & 16 /* Protected */ ? 512 /* ContainsProtected */ : 0) |
53911                             (modifiers & 8 /* Private */ ? 1024 /* ContainsPrivate */ : 0) |
53912                             (modifiers & 32 /* Static */ ? 2048 /* ContainsStatic */ : 0);
53913                         if (!isPrototypeProperty(prop)) {
53914                             syntheticFlag = 2 /* SyntheticProperty */;
53915                         }
53916                     }
53917                     else if (isUnion) {
53918                         var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */));
53919                         if (indexInfo) {
53920                             checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0);
53921                             indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
53922                         }
53923                         else if (isObjectLiteralType(type)) {
53924                             checkFlags |= 32 /* WritePartial */;
53925                             indexTypes = ts.append(indexTypes, undefinedType);
53926                         }
53927                         else {
53928                             checkFlags |= 16 /* ReadPartial */;
53929                         }
53930                     }
53931                 }
53932             }
53933             if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) {
53934                 // No property was found, or, in a union, a property has a private or protected declaration in one
53935                 // constituent, but is missing or has a different declaration in another constituent.
53936                 return undefined;
53937             }
53938             if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) {
53939                 return singleProp;
53940             }
53941             var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp];
53942             var declarations;
53943             var firstType;
53944             var nameType;
53945             var propTypes = [];
53946             var firstValueDeclaration;
53947             var hasNonUniformValueDeclaration = false;
53948             for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
53949                 var prop = props_1[_b];
53950                 if (!firstValueDeclaration) {
53951                     firstValueDeclaration = prop.valueDeclaration;
53952                 }
53953                 else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) {
53954                     hasNonUniformValueDeclaration = true;
53955                 }
53956                 declarations = ts.addRange(declarations, prop.declarations);
53957                 var type = getTypeOfSymbol(prop);
53958                 if (!firstType) {
53959                     firstType = type;
53960                     nameType = getSymbolLinks(prop).nameType;
53961                 }
53962                 else if (type !== firstType) {
53963                     checkFlags |= 64 /* HasNonUniformType */;
53964                 }
53965                 if (isLiteralType(type)) {
53966                     checkFlags |= 128 /* HasLiteralType */;
53967                 }
53968                 if (type.flags & 131072 /* Never */) {
53969                     checkFlags |= 131072 /* HasNeverType */;
53970                 }
53971                 propTypes.push(type);
53972             }
53973             ts.addRange(propTypes, indexTypes);
53974             var result = createSymbol(4 /* Property */ | optionalFlag, name, syntheticFlag | checkFlags);
53975             result.containingType = containingType;
53976             if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
53977                 result.valueDeclaration = firstValueDeclaration;
53978                 // Inherit information about parent type.
53979                 if (firstValueDeclaration.symbol.parent) {
53980                     result.parent = firstValueDeclaration.symbol.parent;
53981                 }
53982             }
53983             result.declarations = declarations;
53984             result.nameType = nameType;
53985             if (propTypes.length > 2) {
53986                 // When `propTypes` has the potential to explode in size when normalized, defer normalization until absolutely needed
53987                 result.checkFlags |= 65536 /* DeferredType */;
53988                 result.deferralParent = containingType;
53989                 result.deferralConstituents = propTypes;
53990             }
53991             else {
53992                 result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
53993             }
53994             return result;
53995         }
53996         // Return the symbol for a given property in a union or intersection type, or undefined if the property
53997         // does not exist in any constituent type. Note that the returned property may only be present in some
53998         // constituents, in which case the isPartial flag is set when the containing type is union type. We need
53999         // these partial properties when identifying discriminant properties, but otherwise they are filtered out
54000         // and do not appear to be present in the union type.
54001         function getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment) {
54002             var _a, _b;
54003             var property = ((_a = type.propertyCacheWithoutObjectFunctionPropertyAugment) === null || _a === void 0 ? void 0 : _a.get(name)) ||
54004                 !skipObjectFunctionPropertyAugment ? (_b = type.propertyCache) === null || _b === void 0 ? void 0 : _b.get(name) : undefined;
54005             if (!property) {
54006                 property = createUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment);
54007                 if (property) {
54008                     var properties = skipObjectFunctionPropertyAugment ? type.propertyCacheWithoutObjectFunctionPropertyAugment || (type.propertyCacheWithoutObjectFunctionPropertyAugment = ts.createSymbolTable()) : type.propertyCache || (type.propertyCache = ts.createSymbolTable());
54009                     properties.set(name, property);
54010                 }
54011             }
54012             return property;
54013         }
54014         function getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment) {
54015             var property = getUnionOrIntersectionProperty(type, name, skipObjectFunctionPropertyAugment);
54016             // We need to filter out partial properties in union types
54017             return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined;
54018         }
54019         /**
54020          * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types.
54021          * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'.
54022          * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when
54023          * no constituent property has type 'never', but the intersection of the constituent property types is 'never'.
54024          */
54025         function getReducedType(type) {
54026             if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) {
54027                 return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type));
54028             }
54029             else if (type.flags & 2097152 /* Intersection */) {
54030                 if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) {
54031                     type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ |
54032                         (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0);
54033                 }
54034                 return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type;
54035             }
54036             return type;
54037         }
54038         function getReducedUnionType(unionType) {
54039             var reducedTypes = ts.sameMap(unionType.types, getReducedType);
54040             if (reducedTypes === unionType.types) {
54041                 return unionType;
54042             }
54043             var reduced = getUnionType(reducedTypes);
54044             if (reduced.flags & 1048576 /* Union */) {
54045                 reduced.resolvedReducedType = reduced;
54046             }
54047             return reduced;
54048         }
54049         function isNeverReducedProperty(prop) {
54050             return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop);
54051         }
54052         function isDiscriminantWithNeverType(prop) {
54053             // Return true for a synthetic non-optional property with non-uniform types, where at least one is
54054             // a literal type and none is never, that reduces to never.
54055             return !(prop.flags & 16777216 /* Optional */) &&
54056                 (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ &&
54057                 !!(getTypeOfSymbol(prop).flags & 131072 /* Never */);
54058         }
54059         function isConflictingPrivateProperty(prop) {
54060             // Return true for a synthetic property with multiple declarations, at least one of which is private.
54061             return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */);
54062         }
54063         function elaborateNeverIntersection(errorInfo, type) {
54064             if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) {
54065                 var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType);
54066                 if (neverProp) {
54067                     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));
54068                 }
54069                 var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty);
54070                 if (privateProp) {
54071                     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));
54072                 }
54073             }
54074             return errorInfo;
54075         }
54076         /**
54077          * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when
54078          * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from
54079          * Object and Function as appropriate.
54080          *
54081          * @param type a type to look up property from
54082          * @param name a name of property to look up in a given type
54083          */
54084         function getPropertyOfType(type, name, skipObjectFunctionPropertyAugment) {
54085             type = getReducedApparentType(type);
54086             if (type.flags & 524288 /* Object */) {
54087                 var resolved = resolveStructuredTypeMembers(type);
54088                 var symbol = resolved.members.get(name);
54089                 if (symbol && symbolIsValue(symbol)) {
54090                     return symbol;
54091                 }
54092                 if (skipObjectFunctionPropertyAugment)
54093                     return undefined;
54094                 var functionType = resolved === anyFunctionType ? globalFunctionType :
54095                     resolved.callSignatures.length ? globalCallableFunctionType :
54096                         resolved.constructSignatures.length ? globalNewableFunctionType :
54097                             undefined;
54098                 if (functionType) {
54099                     var symbol_1 = getPropertyOfObjectType(functionType, name);
54100                     if (symbol_1) {
54101                         return symbol_1;
54102                     }
54103                 }
54104                 return getPropertyOfObjectType(globalObjectType, name);
54105             }
54106             if (type.flags & 3145728 /* UnionOrIntersection */) {
54107                 return getPropertyOfUnionOrIntersectionType(type, name, skipObjectFunctionPropertyAugment);
54108             }
54109             return undefined;
54110         }
54111         function getSignaturesOfStructuredType(type, kind) {
54112             if (type.flags & 3670016 /* StructuredType */) {
54113                 var resolved = resolveStructuredTypeMembers(type);
54114                 return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
54115             }
54116             return ts.emptyArray;
54117         }
54118         /**
54119          * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
54120          * maps primitive types and type parameters are to their apparent types.
54121          */
54122         function getSignaturesOfType(type, kind) {
54123             return getSignaturesOfStructuredType(getReducedApparentType(type), kind);
54124         }
54125         function getIndexInfoOfStructuredType(type, kind) {
54126             if (type.flags & 3670016 /* StructuredType */) {
54127                 var resolved = resolveStructuredTypeMembers(type);
54128                 return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo;
54129             }
54130         }
54131         function getIndexTypeOfStructuredType(type, kind) {
54132             var info = getIndexInfoOfStructuredType(type, kind);
54133             return info && info.type;
54134         }
54135         // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and
54136         // maps primitive types and type parameters are to their apparent types.
54137         function getIndexInfoOfType(type, kind) {
54138             return getIndexInfoOfStructuredType(getReducedApparentType(type), kind);
54139         }
54140         // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and
54141         // maps primitive types and type parameters are to their apparent types.
54142         function getIndexTypeOfType(type, kind) {
54143             return getIndexTypeOfStructuredType(getReducedApparentType(type), kind);
54144         }
54145         function getImplicitIndexTypeOfType(type, kind) {
54146             if (isObjectTypeWithInferableIndex(type)) {
54147                 var propTypes = [];
54148                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
54149                     var prop = _a[_i];
54150                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
54151                         propTypes.push(getTypeOfSymbol(prop));
54152                     }
54153                 }
54154                 if (kind === 0 /* String */) {
54155                     ts.append(propTypes, getIndexTypeOfType(type, 1 /* Number */));
54156                 }
54157                 if (propTypes.length) {
54158                     return getUnionType(propTypes);
54159                 }
54160             }
54161             return undefined;
54162         }
54163         // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual
54164         // type checking functions).
54165         function getTypeParametersFromDeclaration(declaration) {
54166             var result;
54167             for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
54168                 var node = _a[_i];
54169                 result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
54170             }
54171             return result;
54172         }
54173         function symbolsToArray(symbols) {
54174             var result = [];
54175             symbols.forEach(function (symbol, id) {
54176                 if (!isReservedMemberName(id)) {
54177                     result.push(symbol);
54178                 }
54179             });
54180             return result;
54181         }
54182         function isJSDocOptionalParameter(node) {
54183             return ts.isInJSFile(node) && (
54184             // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
54185             node.type && node.type.kind === 307 /* JSDocOptionalType */
54186                 || ts.getJSDocParameterTags(node).some(function (_a) {
54187                     var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
54188                     return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */;
54189                 }));
54190         }
54191         function tryFindAmbientModule(moduleName, withAugmentations) {
54192             if (ts.isExternalModuleNameRelative(moduleName)) {
54193                 return undefined;
54194             }
54195             var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
54196             // merged symbol is module declaration symbol combined with all augmentations
54197             return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
54198         }
54199         function isOptionalParameter(node) {
54200             if (ts.hasQuestionToken(node) || isOptionalJSDocPropertyLikeTag(node) || isJSDocOptionalParameter(node)) {
54201                 return true;
54202             }
54203             if (node.initializer) {
54204                 var signature = getSignatureFromDeclaration(node.parent);
54205                 var parameterIndex = node.parent.parameters.indexOf(node);
54206                 ts.Debug.assert(parameterIndex >= 0);
54207                 // Only consider syntactic or instantiated parameters as optional, not `void` parameters as this function is used
54208                 // in grammar checks and checking for `void` too early results in parameter types widening too early
54209                 // and causes some noImplicitAny errors to be lost.
54210                 return parameterIndex >= getMinArgumentCount(signature, 1 /* StrongArityForUntypedJS */ | 2 /* VoidIsNonOptional */);
54211             }
54212             var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent);
54213             if (iife) {
54214                 return !node.type &&
54215                     !node.dotDotDotToken &&
54216                     node.parent.parameters.indexOf(node) >= iife.arguments.length;
54217             }
54218             return false;
54219         }
54220         function isOptionalJSDocPropertyLikeTag(node) {
54221             if (!ts.isJSDocPropertyLikeTag(node)) {
54222                 return false;
54223             }
54224             var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
54225             return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */;
54226         }
54227         function createTypePredicate(kind, parameterName, parameterIndex, type) {
54228             return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
54229         }
54230         /**
54231          * Gets the minimum number of type arguments needed to satisfy all non-optional type
54232          * parameters.
54233          */
54234         function getMinTypeArgumentCount(typeParameters) {
54235             var minTypeArgumentCount = 0;
54236             if (typeParameters) {
54237                 for (var i = 0; i < typeParameters.length; i++) {
54238                     if (!hasTypeParameterDefault(typeParameters[i])) {
54239                         minTypeArgumentCount = i + 1;
54240                     }
54241                 }
54242             }
54243             return minTypeArgumentCount;
54244         }
54245         function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
54246             var numTypeParameters = ts.length(typeParameters);
54247             if (!numTypeParameters) {
54248                 return [];
54249             }
54250             var numTypeArguments = ts.length(typeArguments);
54251             if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) {
54252                 var result = typeArguments ? typeArguments.slice() : [];
54253                 // Map invalid forward references in default types to the error type
54254                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
54255                     result[i] = errorType;
54256                 }
54257                 var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
54258                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
54259                     var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
54260                     if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) {
54261                         defaultType = anyType;
54262                     }
54263                     result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
54264                 }
54265                 result.length = typeParameters.length;
54266                 return result;
54267             }
54268             return typeArguments && typeArguments.slice();
54269         }
54270         function getSignatureFromDeclaration(declaration) {
54271             var links = getNodeLinks(declaration);
54272             if (!links.resolvedSignature) {
54273                 var parameters = [];
54274                 var flags = 0 /* None */;
54275                 var minArgumentCount = 0;
54276                 var thisParameter = void 0;
54277                 var hasThisParameter = false;
54278                 var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
54279                 var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
54280                 var isUntypedSignatureInJSFile = !iife &&
54281                     ts.isInJSFile(declaration) &&
54282                     ts.isValueSignatureDeclaration(declaration) &&
54283                     !ts.hasJSDocParameterTags(declaration) &&
54284                     !ts.getJSDocType(declaration);
54285                 if (isUntypedSignatureInJSFile) {
54286                     flags |= 32 /* IsUntypedSignatureInJSFile */;
54287                 }
54288                 // If this is a JSDoc construct signature, then skip the first parameter in the
54289                 // parameter list.  The first parameter represents the return type of the construct
54290                 // signature.
54291                 for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
54292                     var param = declaration.parameters[i];
54293                     var paramSymbol = param.symbol;
54294                     var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
54295                     // Include parameter symbol instead of property symbol in the signature
54296                     if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
54297                         var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 111551 /* Value */, undefined, undefined, /*isUse*/ false);
54298                         paramSymbol = resolvedSymbol;
54299                     }
54300                     if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
54301                         hasThisParameter = true;
54302                         thisParameter = param.symbol;
54303                     }
54304                     else {
54305                         parameters.push(paramSymbol);
54306                     }
54307                     if (type && type.kind === 191 /* LiteralType */) {
54308                         flags |= 2 /* HasLiteralTypes */;
54309                     }
54310                     // Record a new minimum argument count if this is not an optional parameter
54311                     var isOptionalParameter_1 = isOptionalJSDocPropertyLikeTag(param) ||
54312                         param.initializer || param.questionToken || param.dotDotDotToken ||
54313                         iife && parameters.length > iife.arguments.length && !type ||
54314                         isJSDocOptionalParameter(param);
54315                     if (!isOptionalParameter_1) {
54316                         minArgumentCount = parameters.length;
54317                     }
54318                 }
54319                 // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
54320                 if ((declaration.kind === 167 /* GetAccessor */ || declaration.kind === 168 /* SetAccessor */) &&
54321                     hasBindableName(declaration) &&
54322                     (!hasThisParameter || !thisParameter)) {
54323                     var otherKind = declaration.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */;
54324                     var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind);
54325                     if (other) {
54326                         thisParameter = getAnnotatedAccessorThisParameter(other);
54327                     }
54328                 }
54329                 var classType = declaration.kind === 166 /* Constructor */ ?
54330                     getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol))
54331                     : undefined;
54332                 var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
54333                 if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
54334                     flags |= 1 /* HasRestParameter */;
54335                 }
54336                 if (ts.isConstructorTypeNode(declaration) && ts.hasSyntacticModifier(declaration, 128 /* Abstract */) ||
54337                     ts.isConstructorDeclaration(declaration) && ts.hasSyntacticModifier(declaration.parent, 128 /* Abstract */)) {
54338                     flags |= 4 /* Abstract */;
54339                 }
54340                 links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, 
54341                 /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags);
54342             }
54343             return links.resolvedSignature;
54344         }
54345         /**
54346          * A JS function gets a synthetic rest parameter if it references `arguments` AND:
54347          * 1. It has no parameters but at least one `@param` with a type that starts with `...`
54348          * OR
54349          * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
54350          */
54351         function maybeAddJsSyntheticRestParameter(declaration, parameters) {
54352             if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
54353                 return false;
54354             }
54355             var lastParam = ts.lastOrUndefined(declaration.parameters);
54356             var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag);
54357             var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) {
54358                 return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined;
54359             });
54360             var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */);
54361             syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType;
54362             if (lastParamVariadicType) {
54363                 // Replace the last parameter with a rest parameter.
54364                 parameters.pop();
54365             }
54366             parameters.push(syntheticArgsSymbol);
54367             return true;
54368         }
54369         function getSignatureOfTypeTag(node) {
54370             // should be attached to a function declaration or expression
54371             if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node)))
54372                 return undefined;
54373             var typeTag = ts.getJSDocTypeTag(node);
54374             var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
54375             return signature && getErasedSignature(signature);
54376         }
54377         function getReturnTypeOfTypeTag(node) {
54378             var signature = getSignatureOfTypeTag(node);
54379             return signature && getReturnTypeOfSignature(signature);
54380         }
54381         function containsArgumentsReference(declaration) {
54382             var links = getNodeLinks(declaration);
54383             if (links.containsArgumentsReference === undefined) {
54384                 if (links.flags & 8192 /* CaptureArguments */) {
54385                     links.containsArgumentsReference = true;
54386                 }
54387                 else {
54388                     links.containsArgumentsReference = traverse(declaration.body);
54389                 }
54390             }
54391             return links.containsArgumentsReference;
54392             function traverse(node) {
54393                 if (!node)
54394                     return false;
54395                 switch (node.kind) {
54396                     case 78 /* Identifier */:
54397                         return node.escapedText === argumentsSymbol.escapedName && getResolvedSymbol(node) === argumentsSymbol;
54398                     case 163 /* PropertyDeclaration */:
54399                     case 165 /* MethodDeclaration */:
54400                     case 167 /* GetAccessor */:
54401                     case 168 /* SetAccessor */:
54402                         return node.name.kind === 158 /* ComputedPropertyName */
54403                             && traverse(node.name);
54404                     case 201 /* PropertyAccessExpression */:
54405                     case 202 /* ElementAccessExpression */:
54406                         return traverse(node.expression);
54407                     default:
54408                         return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse);
54409                 }
54410             }
54411         }
54412         function getSignaturesOfSymbol(symbol) {
54413             if (!symbol)
54414                 return ts.emptyArray;
54415             var result = [];
54416             for (var i = 0; i < symbol.declarations.length; i++) {
54417                 var decl = symbol.declarations[i];
54418                 if (!ts.isFunctionLike(decl))
54419                     continue;
54420                 // Don't include signature if node is the implementation of an overloaded function. A node is considered
54421                 // an implementation node if it has a body and the previous node is of the same kind and immediately
54422                 // precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
54423                 if (i > 0 && decl.body) {
54424                     var previous = symbol.declarations[i - 1];
54425                     if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
54426                         continue;
54427                     }
54428                 }
54429                 result.push(getSignatureFromDeclaration(decl));
54430             }
54431             return result;
54432         }
54433         function resolveExternalModuleTypeByLiteral(name) {
54434             var moduleSym = resolveExternalModuleName(name, name);
54435             if (moduleSym) {
54436                 var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
54437                 if (resolvedModuleSymbol) {
54438                     return getTypeOfSymbol(resolvedModuleSymbol);
54439                 }
54440             }
54441             return anyType;
54442         }
54443         function getThisTypeOfSignature(signature) {
54444             if (signature.thisParameter) {
54445                 return getTypeOfSymbol(signature.thisParameter);
54446             }
54447         }
54448         function getTypePredicateOfSignature(signature) {
54449             if (!signature.resolvedTypePredicate) {
54450                 if (signature.target) {
54451                     var targetTypePredicate = getTypePredicateOfSignature(signature.target);
54452                     signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
54453                 }
54454                 else if (signature.unionSignatures) {
54455                     signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate;
54456                 }
54457                 else {
54458                     var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
54459                     var jsdocPredicate = void 0;
54460                     if (!type && ts.isInJSFile(signature.declaration)) {
54461                         var jsdocSignature = getSignatureOfTypeTag(signature.declaration);
54462                         if (jsdocSignature && signature !== jsdocSignature) {
54463                             jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
54464                         }
54465                     }
54466                     signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
54467                         createTypePredicateFromTypePredicateNode(type, signature) :
54468                         jsdocPredicate || noTypePredicate;
54469                 }
54470                 ts.Debug.assert(!!signature.resolvedTypePredicate);
54471             }
54472             return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
54473         }
54474         function createTypePredicateFromTypePredicateNode(node, signature) {
54475             var parameterName = node.parameterName;
54476             var type = node.type && getTypeFromTypeNode(node.type);
54477             return parameterName.kind === 187 /* ThisType */ ?
54478                 createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) :
54479                 createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type);
54480         }
54481         function getReturnTypeOfSignature(signature) {
54482             if (!signature.resolvedReturnType) {
54483                 if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
54484                     return errorType;
54485                 }
54486                 var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) :
54487                     signature.unionSignatures ? instantiateType(getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */), signature.mapper) :
54488                         getReturnTypeFromAnnotation(signature.declaration) ||
54489                             (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
54490                 if (signature.flags & 8 /* IsInnerCallChain */) {
54491                     type = addOptionalTypeMarker(type);
54492                 }
54493                 else if (signature.flags & 16 /* IsOuterCallChain */) {
54494                     type = getOptionalType(type);
54495                 }
54496                 if (!popTypeResolution()) {
54497                     if (signature.declaration) {
54498                         var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration);
54499                         if (typeNode) {
54500                             error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself);
54501                         }
54502                         else if (noImplicitAny) {
54503                             var declaration = signature.declaration;
54504                             var name = ts.getNameOfDeclaration(declaration);
54505                             if (name) {
54506                                 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));
54507                             }
54508                             else {
54509                                 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);
54510                             }
54511                         }
54512                     }
54513                     type = anyType;
54514                 }
54515                 signature.resolvedReturnType = type;
54516             }
54517             return signature.resolvedReturnType;
54518         }
54519         function getReturnTypeFromAnnotation(declaration) {
54520             if (declaration.kind === 166 /* Constructor */) {
54521                 return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
54522             }
54523             if (ts.isJSDocConstructSignature(declaration)) {
54524                 return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217
54525             }
54526             var typeNode = ts.getEffectiveReturnTypeNode(declaration);
54527             if (typeNode) {
54528                 return getTypeFromTypeNode(typeNode);
54529             }
54530             if (declaration.kind === 167 /* GetAccessor */ && hasBindableName(declaration)) {
54531                 var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
54532                 if (jsDocType) {
54533                     return jsDocType;
54534                 }
54535                 var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 168 /* SetAccessor */);
54536                 var setterType = getAnnotatedAccessorType(setter);
54537                 if (setterType) {
54538                     return setterType;
54539                 }
54540             }
54541             return getReturnTypeOfTypeTag(declaration);
54542         }
54543         function isResolvingReturnTypeOfSignature(signature) {
54544             return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
54545         }
54546         function getRestTypeOfSignature(signature) {
54547             return tryGetRestTypeOfSignature(signature) || anyType;
54548         }
54549         function tryGetRestTypeOfSignature(signature) {
54550             if (signatureHasRestParameter(signature)) {
54551                 var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
54552                 var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
54553                 return restType && getIndexTypeOfType(restType, 1 /* Number */);
54554             }
54555             return undefined;
54556         }
54557         function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
54558             var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
54559             if (inferredTypeParameters) {
54560                 var returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature));
54561                 if (returnSignature) {
54562                     var newReturnSignature = cloneSignature(returnSignature);
54563                     newReturnSignature.typeParameters = inferredTypeParameters;
54564                     var newInstantiatedSignature = cloneSignature(instantiatedSignature);
54565                     newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
54566                     return newInstantiatedSignature;
54567                 }
54568             }
54569             return instantiatedSignature;
54570         }
54571         function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
54572             var instantiations = signature.instantiations || (signature.instantiations = new ts.Map());
54573             var id = getTypeListId(typeArguments);
54574             var instantiation = instantiations.get(id);
54575             if (!instantiation) {
54576                 instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
54577             }
54578             return instantiation;
54579         }
54580         function createSignatureInstantiation(signature, typeArguments) {
54581             return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true);
54582         }
54583         function createSignatureTypeMapper(signature, typeArguments) {
54584             return createTypeMapper(signature.typeParameters, typeArguments);
54585         }
54586         function getErasedSignature(signature) {
54587             return signature.typeParameters ?
54588                 signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) :
54589                 signature;
54590         }
54591         function createErasedSignature(signature) {
54592             // Create an instantiation of the signature where all type arguments are the any type.
54593             return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
54594         }
54595         function getCanonicalSignature(signature) {
54596             return signature.typeParameters ?
54597                 signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) :
54598                 signature;
54599         }
54600         function createCanonicalSignature(signature) {
54601             // Create an instantiation of the signature where each unconstrained type parameter is replaced with
54602             // its original. When a generic class or interface is instantiated, each generic method in the class or
54603             // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios
54604             // where different generations of the same type parameter are in scope). This leads to a lot of new type
54605             // identities, and potentially a lot of work comparing those identities, so here we create an instantiation
54606             // that uses the original type identities for all unconstrained type parameters.
54607             return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration));
54608         }
54609         function getBaseSignature(signature) {
54610             var typeParameters = signature.typeParameters;
54611             if (typeParameters) {
54612                 var typeEraser_1 = createTypeEraser(typeParameters);
54613                 var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; });
54614                 return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true);
54615             }
54616             return signature;
54617         }
54618         function getOrCreateTypeFromSignature(signature) {
54619             // There are two ways to declare a construct signature, one is by declaring a class constructor
54620             // using the constructor keyword, and the other is declaring a bare construct signature in an
54621             // object type literal or interface (using the new keyword). Each way of declaring a constructor
54622             // will result in a different declaration kind.
54623             if (!signature.isolatedSignatureType) {
54624                 var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */;
54625                 var isConstructor = kind === 166 /* Constructor */ || kind === 170 /* ConstructSignature */ || kind === 175 /* ConstructorType */;
54626                 var type = createObjectType(16 /* Anonymous */);
54627                 type.members = emptySymbols;
54628                 type.properties = ts.emptyArray;
54629                 type.callSignatures = !isConstructor ? [signature] : ts.emptyArray;
54630                 type.constructSignatures = isConstructor ? [signature] : ts.emptyArray;
54631                 signature.isolatedSignatureType = type;
54632             }
54633             return signature.isolatedSignatureType;
54634         }
54635         function getIndexSymbol(symbol) {
54636             return symbol.members.get("__index" /* Index */);
54637         }
54638         function getIndexDeclarationOfSymbol(symbol, kind) {
54639             var syntaxKind = kind === 1 /* Number */ ? 144 /* NumberKeyword */ : 147 /* StringKeyword */;
54640             var indexSymbol = getIndexSymbol(symbol);
54641             if (indexSymbol) {
54642                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
54643                     var decl = _a[_i];
54644                     var node = ts.cast(decl, ts.isIndexSignatureDeclaration);
54645                     if (node.parameters.length === 1) {
54646                         var parameter = node.parameters[0];
54647                         if (parameter.type && parameter.type.kind === syntaxKind) {
54648                             return node;
54649                         }
54650                     }
54651                 }
54652             }
54653             return undefined;
54654         }
54655         function createIndexInfo(type, isReadonly, declaration) {
54656             return { type: type, isReadonly: isReadonly, declaration: declaration };
54657         }
54658         function getIndexInfoOfSymbol(symbol, kind) {
54659             var declaration = getIndexDeclarationOfSymbol(symbol, kind);
54660             if (declaration) {
54661                 return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasEffectiveModifier(declaration, 64 /* Readonly */), declaration);
54662             }
54663             return undefined;
54664         }
54665         function getConstraintDeclaration(type) {
54666             return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0];
54667         }
54668         function getInferredTypeParameterConstraint(typeParameter) {
54669             var inferences;
54670             if (typeParameter.symbol) {
54671                 for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) {
54672                     var declaration = _a[_i];
54673                     if (declaration.parent.kind === 185 /* InferType */) {
54674                         // When an 'infer T' declaration is immediately contained in a type reference node
54675                         // (such as 'Foo<infer T>'), T's constraint is inferred from the constraint of the
54676                         // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are
54677                         // present, we form an intersection of the inferred constraint types.
54678                         var _b = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _c = _b[0], childTypeParameter = _c === void 0 ? declaration.parent : _c, grandParent = _b[1];
54679                         if (grandParent.kind === 173 /* TypeReference */) {
54680                             var typeReference = grandParent;
54681                             var typeParameters = getTypeParametersForTypeReference(typeReference);
54682                             if (typeParameters) {
54683                                 var index = typeReference.typeArguments.indexOf(childTypeParameter);
54684                                 if (index < typeParameters.length) {
54685                                     var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
54686                                     if (declaredConstraint) {
54687                                         // Type parameter constraints can reference other type parameters so
54688                                         // constraints need to be instantiated. If instantiation produces the
54689                                         // type parameter itself, we discard that inference. For example, in
54690                                         //   type Foo<T extends string, U extends T> = [T, U];
54691                                         //   type Bar<T> = T extends Foo<infer X, infer X> ? Foo<X, X> : T;
54692                                         // the instantiated constraint for U is X, so we discard that inference.
54693                                         var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters));
54694                                         var constraint = instantiateType(declaredConstraint, mapper);
54695                                         if (constraint !== typeParameter) {
54696                                             inferences = ts.append(inferences, constraint);
54697                                         }
54698                                     }
54699                                 }
54700                             }
54701                         }
54702                         // When an 'infer T' declaration is immediately contained in a rest parameter declaration, a rest type
54703                         // or a named rest tuple element, we infer an 'unknown[]' constraint.
54704                         else if (grandParent.kind === 160 /* Parameter */ && grandParent.dotDotDotToken ||
54705                             grandParent.kind === 181 /* RestType */ ||
54706                             grandParent.kind === 192 /* NamedTupleMember */ && grandParent.dotDotDotToken) {
54707                             inferences = ts.append(inferences, createArrayType(unknownType));
54708                         }
54709                         // When an 'infer T' declaration is immediately contained in a string template type, we infer a 'string'
54710                         // constraint.
54711                         else if (grandParent.kind === 194 /* TemplateLiteralTypeSpan */) {
54712                             inferences = ts.append(inferences, stringType);
54713                         }
54714                         // When an 'infer T' declaration is in the constraint position of a mapped type, we infer a 'keyof any'
54715                         // constraint.
54716                         else if (grandParent.kind === 159 /* TypeParameter */ && grandParent.parent.kind === 190 /* MappedType */) {
54717                             inferences = ts.append(inferences, keyofConstraintType);
54718                         }
54719                     }
54720                 }
54721             }
54722             return inferences && getIntersectionType(inferences);
54723         }
54724         /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */
54725         function getConstraintFromTypeParameter(typeParameter) {
54726             if (!typeParameter.constraint) {
54727                 if (typeParameter.target) {
54728                     var targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
54729                     typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
54730                 }
54731                 else {
54732                     var constraintDeclaration = getConstraintDeclaration(typeParameter);
54733                     if (!constraintDeclaration) {
54734                         typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
54735                     }
54736                     else {
54737                         var type = getTypeFromTypeNode(constraintDeclaration);
54738                         if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed
54739                             // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was),
54740                             // use unknown otherwise
54741                             type = constraintDeclaration.parent.parent.kind === 190 /* MappedType */ ? keyofConstraintType : unknownType;
54742                         }
54743                         typeParameter.constraint = type;
54744                     }
54745                 }
54746             }
54747             return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint;
54748         }
54749         function getParentSymbolOfTypeParameter(typeParameter) {
54750             var tp = ts.getDeclarationOfKind(typeParameter.symbol, 159 /* TypeParameter */);
54751             var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent;
54752             return host && getSymbolOfNode(host);
54753         }
54754         function getTypeListId(types) {
54755             var result = "";
54756             if (types) {
54757                 var length_4 = types.length;
54758                 var i = 0;
54759                 while (i < length_4) {
54760                     var startId = types[i].id;
54761                     var count = 1;
54762                     while (i + count < length_4 && types[i + count].id === startId + count) {
54763                         count++;
54764                     }
54765                     if (result.length) {
54766                         result += ",";
54767                     }
54768                     result += startId;
54769                     if (count > 1) {
54770                         result += ":" + count;
54771                     }
54772                     i += count;
54773                 }
54774             }
54775             return result;
54776         }
54777         function getAliasId(aliasSymbol, aliasTypeArguments) {
54778             return aliasSymbol ? "@" + getSymbolId(aliasSymbol) + (aliasTypeArguments ? ":" + getTypeListId(aliasTypeArguments) : "") : "";
54779         }
54780         // This function is used to propagate certain flags when creating new object type references and union types.
54781         // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
54782         // of an object literal or the anyFunctionType. This is because there are operations in the type checker
54783         // that care about the presence of such types at arbitrary depth in a containing type.
54784         function getPropagatingFlagsOfTypes(types, excludeKinds) {
54785             var result = 0;
54786             for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
54787                 var type = types_9[_i];
54788                 if (!(type.flags & excludeKinds)) {
54789                     result |= ts.getObjectFlags(type);
54790                 }
54791             }
54792             return result & 3670016 /* PropagatingFlags */;
54793         }
54794         function createTypeReference(target, typeArguments) {
54795             var id = getTypeListId(typeArguments);
54796             var type = target.instantiations.get(id);
54797             if (!type) {
54798                 type = createObjectType(4 /* Reference */, target.symbol);
54799                 target.instantiations.set(id, type);
54800                 type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
54801                 type.target = target;
54802                 type.resolvedTypeArguments = typeArguments;
54803             }
54804             return type;
54805         }
54806         function cloneTypeReference(source) {
54807             var type = createType(source.flags);
54808             type.symbol = source.symbol;
54809             type.objectFlags = source.objectFlags;
54810             type.target = source.target;
54811             type.resolvedTypeArguments = source.resolvedTypeArguments;
54812             return type;
54813         }
54814         function createDeferredTypeReference(target, node, mapper, aliasSymbol, aliasTypeArguments) {
54815             if (!aliasSymbol) {
54816                 aliasSymbol = getAliasSymbolForTypeNode(node);
54817                 var localAliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
54818                 aliasTypeArguments = mapper ? instantiateTypes(localAliasTypeArguments, mapper) : localAliasTypeArguments;
54819             }
54820             var type = createObjectType(4 /* Reference */, target.symbol);
54821             type.target = target;
54822             type.node = node;
54823             type.mapper = mapper;
54824             type.aliasSymbol = aliasSymbol;
54825             type.aliasTypeArguments = aliasTypeArguments;
54826             return type;
54827         }
54828         function getTypeArguments(type) {
54829             var _a, _b;
54830             if (!type.resolvedTypeArguments) {
54831                 if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */)) {
54832                     return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray;
54833                 }
54834                 var node = type.node;
54835                 var typeArguments = !node ? ts.emptyArray :
54836                     node.kind === 173 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) :
54837                         node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] :
54838                             ts.map(node.elements, getTypeFromTypeNode);
54839                 if (popTypeResolution()) {
54840                     type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments;
54841                 }
54842                 else {
54843                     type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray;
54844                     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));
54845                 }
54846             }
54847             return type.resolvedTypeArguments;
54848         }
54849         function getTypeReferenceArity(type) {
54850             return ts.length(type.target.typeParameters);
54851         }
54852         /**
54853          * Get type from type-reference that reference to class or interface
54854          */
54855         function getTypeFromClassOrInterfaceReference(node, symbol) {
54856             var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
54857             var typeParameters = type.localTypeParameters;
54858             if (typeParameters) {
54859                 var numTypeArguments = ts.length(node.typeArguments);
54860                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
54861                 var isJs = ts.isInJSFile(node);
54862                 var isJsImplicitAny = !noImplicitAny && isJs;
54863                 if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
54864                     var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent);
54865                     var diag = minTypeArgumentCount === typeParameters.length ?
54866                         missingAugmentsTag ?
54867                             ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag :
54868                             ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
54869                         missingAugmentsTag ?
54870                             ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag :
54871                             ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
54872                     var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */);
54873                     error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length);
54874                     if (!isJs) {
54875                         // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments)
54876                         return errorType;
54877                     }
54878                 }
54879                 if (node.kind === 173 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) {
54880                     return createDeferredTypeReference(type, node, /*mapper*/ undefined);
54881                 }
54882                 // In a type reference, the outer type parameters of the referenced class or interface are automatically
54883                 // supplied as type arguments and the type reference only specifies arguments for the local type parameters
54884                 // of the class or interface.
54885                 var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs));
54886                 return createTypeReference(type, typeArguments);
54887             }
54888             return checkNoTypeArguments(node, symbol) ? type : errorType;
54889         }
54890         function getTypeAliasInstantiation(symbol, typeArguments, aliasSymbol, aliasTypeArguments) {
54891             var type = getDeclaredTypeOfSymbol(symbol);
54892             if (type === intrinsicMarkerType && intrinsicTypeKinds.has(symbol.escapedName) && typeArguments && typeArguments.length === 1) {
54893                 return getStringMappingType(symbol, typeArguments[0]);
54894             }
54895             var links = getSymbolLinks(symbol);
54896             var typeParameters = links.typeParameters;
54897             var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments);
54898             var instantiation = links.instantiations.get(id);
54899             if (!instantiation) {
54900                 links.instantiations.set(id, instantiation = instantiateTypeWithAlias(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration))), aliasSymbol, aliasTypeArguments));
54901             }
54902             return instantiation;
54903         }
54904         /**
54905          * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include
54906          * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the
54907          * declared type. Instantiations are cached using the type identities of the type arguments as the key.
54908          */
54909         function getTypeFromTypeAliasReference(node, symbol) {
54910             var type = getDeclaredTypeOfSymbol(symbol);
54911             var typeParameters = getSymbolLinks(symbol).typeParameters;
54912             if (typeParameters) {
54913                 var numTypeArguments = ts.length(node.typeArguments);
54914                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
54915                 if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
54916                     error(node, minTypeArgumentCount === typeParameters.length ?
54917                         ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
54918                         ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
54919                     return errorType;
54920                 }
54921                 var aliasSymbol = getAliasSymbolForTypeNode(node);
54922                 return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
54923             }
54924             return checkNoTypeArguments(node, symbol) ? type : errorType;
54925         }
54926         function getTypeReferenceName(node) {
54927             switch (node.kind) {
54928                 case 173 /* TypeReference */:
54929                     return node.typeName;
54930                 case 223 /* ExpressionWithTypeArguments */:
54931                     // We only support expressions that are simple qualified names. For other
54932                     // expressions this produces undefined.
54933                     var expr = node.expression;
54934                     if (ts.isEntityNameExpression(expr)) {
54935                         return expr;
54936                     }
54937                 // fall through;
54938             }
54939             return undefined;
54940         }
54941         function resolveTypeReferenceName(typeReferenceName, meaning, ignoreErrors) {
54942             if (!typeReferenceName) {
54943                 return unknownSymbol;
54944             }
54945             return resolveEntityName(typeReferenceName, meaning, ignoreErrors) || unknownSymbol;
54946         }
54947         function getTypeReferenceType(node, symbol) {
54948             if (symbol === unknownSymbol) {
54949                 return errorType;
54950             }
54951             symbol = getExpandoSymbol(symbol) || symbol;
54952             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
54953                 return getTypeFromClassOrInterfaceReference(node, symbol);
54954             }
54955             if (symbol.flags & 524288 /* TypeAlias */) {
54956                 return getTypeFromTypeAliasReference(node, symbol);
54957             }
54958             // Get type from reference to named type that cannot be generic (enum or type parameter)
54959             var res = tryGetDeclaredTypeOfSymbol(symbol);
54960             if (res) {
54961                 return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType;
54962             }
54963             if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) {
54964                 var jsdocType = getTypeFromJSDocValueReference(node, symbol);
54965                 if (jsdocType) {
54966                     return jsdocType;
54967                 }
54968                 else {
54969                     // Resolve the type reference as a Type for the purpose of reporting errors.
54970                     resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */);
54971                     return getTypeOfSymbol(symbol);
54972                 }
54973             }
54974             return errorType;
54975         }
54976         /**
54977          * A JSdoc TypeReference may be to a value, but resolve it as a type anyway.
54978          * Example: import('./b').ConstructorFunction
54979          */
54980         function getTypeFromJSDocValueReference(node, symbol) {
54981             var links = getNodeLinks(node);
54982             if (!links.resolvedJSDocType) {
54983                 var valueType = getTypeOfSymbol(symbol);
54984                 var typeType = valueType;
54985                 if (symbol.valueDeclaration) {
54986                     var isImportTypeWithQualifier = node.kind === 195 /* ImportType */ && node.qualifier;
54987                     // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL}
54988                     if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) {
54989                         typeType = getTypeReferenceType(node, valueType.symbol);
54990                     }
54991                 }
54992                 links.resolvedJSDocType = typeType;
54993             }
54994             return links.resolvedJSDocType;
54995         }
54996         function getSubstitutionType(baseType, substitute) {
54997             if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === baseType) {
54998                 return baseType;
54999             }
55000             var id = getTypeId(baseType) + ">" + getTypeId(substitute);
55001             var cached = substitutionTypes.get(id);
55002             if (cached) {
55003                 return cached;
55004             }
55005             var result = createType(33554432 /* Substitution */);
55006             result.baseType = baseType;
55007             result.substitute = substitute;
55008             substitutionTypes.set(id, result);
55009             return result;
55010         }
55011         function isUnaryTupleTypeNode(node) {
55012             return node.kind === 179 /* TupleType */ && node.elements.length === 1;
55013         }
55014         function getImpliedConstraint(type, checkNode, extendsNode) {
55015             return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) :
55016                 getActualTypeVariable(getTypeFromTypeNode(checkNode)) === type ? getTypeFromTypeNode(extendsNode) :
55017                     undefined;
55018         }
55019         function getConditionalFlowTypeOfType(type, node) {
55020             var constraints;
55021             while (node && !ts.isStatement(node) && node.kind !== 311 /* JSDocComment */) {
55022                 var parent = node.parent;
55023                 if (parent.kind === 184 /* ConditionalType */ && node === parent.trueType) {
55024                     var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType);
55025                     if (constraint) {
55026                         constraints = ts.append(constraints, constraint);
55027                     }
55028                 }
55029                 node = parent;
55030             }
55031             return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type;
55032         }
55033         function isJSDocTypeReference(node) {
55034             return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 173 /* TypeReference */ || node.kind === 195 /* ImportType */);
55035         }
55036         function checkNoTypeArguments(node, symbol) {
55037             if (node.typeArguments) {
55038                 error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : anon);
55039                 return false;
55040             }
55041             return true;
55042         }
55043         function getIntendedTypeFromJSDocTypeReference(node) {
55044             if (ts.isIdentifier(node.typeName)) {
55045                 var typeArgs = node.typeArguments;
55046                 switch (node.typeName.escapedText) {
55047                     case "String":
55048                         checkNoTypeArguments(node);
55049                         return stringType;
55050                     case "Number":
55051                         checkNoTypeArguments(node);
55052                         return numberType;
55053                     case "Boolean":
55054                         checkNoTypeArguments(node);
55055                         return booleanType;
55056                     case "Void":
55057                         checkNoTypeArguments(node);
55058                         return voidType;
55059                     case "Undefined":
55060                         checkNoTypeArguments(node);
55061                         return undefinedType;
55062                     case "Null":
55063                         checkNoTypeArguments(node);
55064                         return nullType;
55065                     case "Function":
55066                     case "function":
55067                         checkNoTypeArguments(node);
55068                         return globalFunctionType;
55069                     case "array":
55070                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : undefined;
55071                     case "promise":
55072                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : undefined;
55073                     case "Object":
55074                         if (typeArgs && typeArgs.length === 2) {
55075                             if (ts.isJSDocIndexSignature(node)) {
55076                                 var indexed = getTypeFromTypeNode(typeArgs[0]);
55077                                 var target = getTypeFromTypeNode(typeArgs[1]);
55078                                 var index = createIndexInfo(target, /*isReadonly*/ false);
55079                                 return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined);
55080                             }
55081                             return anyType;
55082                         }
55083                         checkNoTypeArguments(node);
55084                         return !noImplicitAny ? anyType : undefined;
55085                 }
55086             }
55087         }
55088         function getTypeFromJSDocNullableTypeNode(node) {
55089             var type = getTypeFromTypeNode(node.type);
55090             return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type;
55091         }
55092         function getTypeFromTypeReference(node) {
55093             var links = getNodeLinks(node);
55094             if (!links.resolvedType) {
55095                 // handle LS queries on the `const` in `x as const` by resolving to the type of `x`
55096                 if (ts.isConstTypeReference(node) && ts.isAssertionExpression(node.parent)) {
55097                     links.resolvedSymbol = unknownSymbol;
55098                     return links.resolvedType = checkExpressionCached(node.parent.expression);
55099                 }
55100                 var symbol = void 0;
55101                 var type = void 0;
55102                 var meaning = 788968 /* Type */;
55103                 if (isJSDocTypeReference(node)) {
55104                     type = getIntendedTypeFromJSDocTypeReference(node);
55105                     if (!type) {
55106                         symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning, /*ignoreErrors*/ true);
55107                         if (symbol === unknownSymbol) {
55108                             symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning | 111551 /* Value */);
55109                         }
55110                         else {
55111                             resolveTypeReferenceName(getTypeReferenceName(node), meaning); // Resolve again to mark errors, if any
55112                         }
55113                         type = getTypeReferenceType(node, symbol);
55114                     }
55115                 }
55116                 if (!type) {
55117                     symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning);
55118                     type = getTypeReferenceType(node, symbol);
55119                 }
55120                 // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the
55121                 // type reference in checkTypeReferenceNode.
55122                 links.resolvedSymbol = symbol;
55123                 links.resolvedType = type;
55124             }
55125             return links.resolvedType;
55126         }
55127         function typeArgumentsFromTypeReferenceNode(node) {
55128             return ts.map(node.typeArguments, getTypeFromTypeNode);
55129         }
55130         function getTypeFromTypeQueryNode(node) {
55131             var links = getNodeLinks(node);
55132             if (!links.resolvedType) {
55133                 // TypeScript 1.0 spec (April 2014): 3.6.3
55134                 // The expression is processed as an identifier expression (section 4.3)
55135                 // or property access expression(section 4.10),
55136                 // the widened type(section 3.9) of which becomes the result.
55137                 links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName)));
55138             }
55139             return links.resolvedType;
55140         }
55141         function getTypeOfGlobalSymbol(symbol, arity) {
55142             function getTypeDeclaration(symbol) {
55143                 var declarations = symbol.declarations;
55144                 for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
55145                     var declaration = declarations_3[_i];
55146                     switch (declaration.kind) {
55147                         case 252 /* ClassDeclaration */:
55148                         case 253 /* InterfaceDeclaration */:
55149                         case 255 /* EnumDeclaration */:
55150                             return declaration;
55151                     }
55152                 }
55153             }
55154             if (!symbol) {
55155                 return arity ? emptyGenericType : emptyObjectType;
55156             }
55157             var type = getDeclaredTypeOfSymbol(symbol);
55158             if (!(type.flags & 524288 /* Object */)) {
55159                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol));
55160                 return arity ? emptyGenericType : emptyObjectType;
55161             }
55162             if (ts.length(type.typeParameters) !== arity) {
55163                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity);
55164                 return arity ? emptyGenericType : emptyObjectType;
55165             }
55166             return type;
55167         }
55168         function getGlobalValueSymbol(name, reportErrors) {
55169             return getGlobalSymbol(name, 111551 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
55170         }
55171         function getGlobalTypeSymbol(name, reportErrors) {
55172             return getGlobalSymbol(name, 788968 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
55173         }
55174         function getGlobalSymbol(name, meaning, diagnostic) {
55175             // Don't track references for global symbols anyway, so value if `isReference` is arbitrary
55176             return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false);
55177         }
55178         function getGlobalType(name, arity, reportErrors) {
55179             var symbol = getGlobalTypeSymbol(name, reportErrors);
55180             return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined;
55181         }
55182         function getGlobalTypedPropertyDescriptorType() {
55183             return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType;
55184         }
55185         function getGlobalTemplateStringsArrayType() {
55186             return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
55187         }
55188         function getGlobalImportMetaType() {
55189             return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
55190         }
55191         function getGlobalESSymbolConstructorSymbol(reportErrors) {
55192             return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors));
55193         }
55194         function getGlobalESSymbolType(reportErrors) {
55195             return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType;
55196         }
55197         function getGlobalPromiseType(reportErrors) {
55198             return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType;
55199         }
55200         function getGlobalPromiseLikeType(reportErrors) {
55201             return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType;
55202         }
55203         function getGlobalPromiseConstructorSymbol(reportErrors) {
55204             return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors));
55205         }
55206         function getGlobalPromiseConstructorLikeType(reportErrors) {
55207             return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType;
55208         }
55209         function getGlobalAsyncIterableType(reportErrors) {
55210             return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
55211         }
55212         function getGlobalAsyncIteratorType(reportErrors) {
55213             return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
55214         }
55215         function getGlobalAsyncIterableIteratorType(reportErrors) {
55216             return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
55217         }
55218         function getGlobalAsyncGeneratorType(reportErrors) {
55219             return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType("AsyncGenerator", /*arity*/ 3, reportErrors)) || emptyGenericType;
55220         }
55221         function getGlobalIterableType(reportErrors) {
55222             return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
55223         }
55224         function getGlobalIteratorType(reportErrors) {
55225             return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
55226         }
55227         function getGlobalIterableIteratorType(reportErrors) {
55228             return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
55229         }
55230         function getGlobalGeneratorType(reportErrors) {
55231             return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType("Generator", /*arity*/ 3, reportErrors)) || emptyGenericType;
55232         }
55233         function getGlobalIteratorYieldResultType(reportErrors) {
55234             return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType("IteratorYieldResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
55235         }
55236         function getGlobalIteratorReturnResultType(reportErrors) {
55237             return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType("IteratorReturnResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
55238         }
55239         function getGlobalTypeOrUndefined(name, arity) {
55240             if (arity === void 0) { arity = 0; }
55241             var symbol = getGlobalSymbol(name, 788968 /* Type */, /*diagnostic*/ undefined);
55242             return symbol && getTypeOfGlobalSymbol(symbol, arity);
55243         }
55244         function getGlobalExtractSymbol() {
55245             return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
55246         }
55247         function getGlobalOmitSymbol() {
55248             return deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalSymbol("Omit", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
55249         }
55250         function getGlobalBigIntType(reportErrors) {
55251             return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType;
55252         }
55253         /**
55254          * Instantiates a global type that is generic with some element type, and returns that instantiation.
55255          */
55256         function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
55257             return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
55258         }
55259         function createTypedPropertyDescriptorType(propertyType) {
55260             return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
55261         }
55262         function createIterableType(iteratedType) {
55263             return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]);
55264         }
55265         function createArrayType(elementType, readonly) {
55266             return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
55267         }
55268         function getTupleElementFlags(node) {
55269             switch (node.kind) {
55270                 case 180 /* OptionalType */:
55271                     return 2 /* Optional */;
55272                 case 181 /* RestType */:
55273                     return getRestTypeElementFlags(node);
55274                 case 192 /* NamedTupleMember */:
55275                     return node.questionToken ? 2 /* Optional */ :
55276                         node.dotDotDotToken ? getRestTypeElementFlags(node) :
55277                             1 /* Required */;
55278                 default:
55279                     return 1 /* Required */;
55280             }
55281         }
55282         function getRestTypeElementFlags(node) {
55283             return getArrayElementTypeNode(node.type) ? 4 /* Rest */ : 8 /* Variadic */;
55284         }
55285         function getArrayOrTupleTargetType(node) {
55286             var readonly = isReadonlyTypeOperator(node.parent);
55287             var elementType = getArrayElementTypeNode(node);
55288             if (elementType) {
55289                 return readonly ? globalReadonlyArrayType : globalArrayType;
55290             }
55291             var elementFlags = ts.map(node.elements, getTupleElementFlags);
55292             var missingName = ts.some(node.elements, function (e) { return e.kind !== 192 /* NamedTupleMember */; });
55293             return getTupleTargetType(elementFlags, readonly, /*associatedNames*/ missingName ? undefined : node.elements);
55294         }
55295         // Return true if the given type reference node is directly aliased or if it needs to be deferred
55296         // because it is possibly contained in a circular chain of eagerly resolved types.
55297         function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) {
55298             return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 178 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) :
55299                 node.kind === 179 /* TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) :
55300                     hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias));
55301         }
55302         // Return true when the given node is transitively contained in type constructs that eagerly
55303         // resolve their constituent types. We include SyntaxKind.TypeReference because type arguments
55304         // of type aliases are eagerly resolved.
55305         function isResolvedByTypeAlias(node) {
55306             var parent = node.parent;
55307             switch (parent.kind) {
55308                 case 186 /* ParenthesizedType */:
55309                 case 192 /* NamedTupleMember */:
55310                 case 173 /* TypeReference */:
55311                 case 182 /* UnionType */:
55312                 case 183 /* IntersectionType */:
55313                 case 189 /* IndexedAccessType */:
55314                 case 184 /* ConditionalType */:
55315                 case 188 /* TypeOperator */:
55316                 case 178 /* ArrayType */:
55317                 case 179 /* TupleType */:
55318                     return isResolvedByTypeAlias(parent);
55319                 case 254 /* TypeAliasDeclaration */:
55320                     return true;
55321             }
55322             return false;
55323         }
55324         // Return true if resolving the given node (i.e. getTypeFromTypeNode) possibly causes resolution
55325         // of a type alias.
55326         function mayResolveTypeAlias(node) {
55327             switch (node.kind) {
55328                 case 173 /* TypeReference */:
55329                     return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */);
55330                 case 176 /* TypeQuery */:
55331                     return true;
55332                 case 188 /* TypeOperator */:
55333                     return node.operator !== 151 /* UniqueKeyword */ && mayResolveTypeAlias(node.type);
55334                 case 186 /* ParenthesizedType */:
55335                 case 180 /* OptionalType */:
55336                 case 192 /* NamedTupleMember */:
55337                 case 307 /* JSDocOptionalType */:
55338                 case 305 /* JSDocNullableType */:
55339                 case 306 /* JSDocNonNullableType */:
55340                 case 301 /* JSDocTypeExpression */:
55341                     return mayResolveTypeAlias(node.type);
55342                 case 181 /* RestType */:
55343                     return node.type.kind !== 178 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType);
55344                 case 182 /* UnionType */:
55345                 case 183 /* IntersectionType */:
55346                     return ts.some(node.types, mayResolveTypeAlias);
55347                 case 189 /* IndexedAccessType */:
55348                     return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType);
55349                 case 184 /* ConditionalType */:
55350                     return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) ||
55351                         mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType);
55352             }
55353             return false;
55354         }
55355         function getTypeFromArrayOrTupleTypeNode(node) {
55356             var links = getNodeLinks(node);
55357             if (!links.resolvedType) {
55358                 var target = getArrayOrTupleTargetType(node);
55359                 if (target === emptyGenericType) {
55360                     links.resolvedType = emptyObjectType;
55361                 }
55362                 else if (!(node.kind === 179 /* TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* Variadic */); })) && isDeferredTypeReferenceNode(node)) {
55363                     links.resolvedType = node.kind === 179 /* TupleType */ && node.elements.length === 0 ? target :
55364                         createDeferredTypeReference(target, node, /*mapper*/ undefined);
55365                 }
55366                 else {
55367                     var elementTypes = node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode);
55368                     links.resolvedType = createNormalizedTypeReference(target, elementTypes);
55369                 }
55370             }
55371             return links.resolvedType;
55372         }
55373         function isReadonlyTypeOperator(node) {
55374             return ts.isTypeOperatorNode(node) && node.operator === 142 /* ReadonlyKeyword */;
55375         }
55376         function createTupleType(elementTypes, elementFlags, readonly, namedMemberDeclarations) {
55377             if (readonly === void 0) { readonly = false; }
55378             var tupleTarget = getTupleTargetType(elementFlags || ts.map(elementTypes, function (_) { return 1 /* Required */; }), readonly, namedMemberDeclarations);
55379             return tupleTarget === emptyGenericType ? emptyObjectType :
55380                 elementTypes.length ? createNormalizedTypeReference(tupleTarget, elementTypes) :
55381                     tupleTarget;
55382         }
55383         function getTupleTargetType(elementFlags, readonly, namedMemberDeclarations) {
55384             if (elementFlags.length === 1 && elementFlags[0] & 4 /* Rest */) {
55385                 // [...X[]] is equivalent to just X[]
55386                 return readonly ? globalReadonlyArrayType : globalArrayType;
55387             }
55388             var key = ts.map(elementFlags, function (f) { return f & 1 /* Required */ ? "#" : f & 2 /* Optional */ ? "?" : f & 4 /* Rest */ ? "." : "*"; }).join() +
55389                 (readonly ? "R" : "") +
55390                 (namedMemberDeclarations && namedMemberDeclarations.length ? "," + ts.map(namedMemberDeclarations, getNodeId).join(",") : "");
55391             var type = tupleTypes.get(key);
55392             if (!type) {
55393                 tupleTypes.set(key, type = createTupleTargetType(elementFlags, readonly, namedMemberDeclarations));
55394             }
55395             return type;
55396         }
55397         // We represent tuple types as type references to synthesized generic interface types created by
55398         // this function. The types are of the form:
55399         //
55400         //   interface Tuple<T0, T1, T2, ...> extends Array<T0 | T1 | T2 | ...> { 0: T0, 1: T1, 2: T2, ... }
55401         //
55402         // Note that the generic type created by this function has no symbol associated with it. The same
55403         // is true for each of the synthesized type parameters.
55404         function createTupleTargetType(elementFlags, readonly, namedMemberDeclarations) {
55405             var arity = elementFlags.length;
55406             var minLength = ts.countWhere(elementFlags, function (f) { return !!(f & (1 /* Required */ | 8 /* Variadic */)); });
55407             var typeParameters;
55408             var properties = [];
55409             var combinedFlags = 0;
55410             if (arity) {
55411                 typeParameters = new Array(arity);
55412                 for (var i = 0; i < arity; i++) {
55413                     var typeParameter = typeParameters[i] = createTypeParameter();
55414                     var flags = elementFlags[i];
55415                     combinedFlags |= flags;
55416                     if (!(combinedFlags & 12 /* Variable */)) {
55417                         var property = createSymbol(4 /* Property */ | (flags & 2 /* Optional */ ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
55418                         property.tupleLabelDeclaration = namedMemberDeclarations === null || namedMemberDeclarations === void 0 ? void 0 : namedMemberDeclarations[i];
55419                         property.type = typeParameter;
55420                         properties.push(property);
55421                     }
55422                 }
55423             }
55424             var fixedLength = properties.length;
55425             var lengthSymbol = createSymbol(4 /* Property */, "length");
55426             if (combinedFlags & 12 /* Variable */) {
55427                 lengthSymbol.type = numberType;
55428             }
55429             else {
55430                 var literalTypes_1 = [];
55431                 for (var i = minLength; i <= arity; i++)
55432                     literalTypes_1.push(getLiteralType(i));
55433                 lengthSymbol.type = getUnionType(literalTypes_1);
55434             }
55435             properties.push(lengthSymbol);
55436             var type = createObjectType(8 /* Tuple */ | 4 /* Reference */);
55437             type.typeParameters = typeParameters;
55438             type.outerTypeParameters = undefined;
55439             type.localTypeParameters = typeParameters;
55440             type.instantiations = new ts.Map();
55441             type.instantiations.set(getTypeListId(type.typeParameters), type);
55442             type.target = type;
55443             type.resolvedTypeArguments = type.typeParameters;
55444             type.thisType = createTypeParameter();
55445             type.thisType.isThisType = true;
55446             type.thisType.constraint = type;
55447             type.declaredProperties = properties;
55448             type.declaredCallSignatures = ts.emptyArray;
55449             type.declaredConstructSignatures = ts.emptyArray;
55450             type.declaredStringIndexInfo = undefined;
55451             type.declaredNumberIndexInfo = undefined;
55452             type.elementFlags = elementFlags;
55453             type.minLength = minLength;
55454             type.fixedLength = fixedLength;
55455             type.hasRestElement = !!(combinedFlags & 12 /* Variable */);
55456             type.combinedFlags = combinedFlags;
55457             type.readonly = readonly;
55458             type.labeledElementDeclarations = namedMemberDeclarations;
55459             return type;
55460         }
55461         function createNormalizedTypeReference(target, typeArguments) {
55462             return target.objectFlags & 8 /* Tuple */ ? createNormalizedTupleType(target, typeArguments) : createTypeReference(target, typeArguments);
55463         }
55464         function createNormalizedTupleType(target, elementTypes) {
55465             var _a, _b, _c;
55466             if (!(target.combinedFlags & 14 /* NonRequired */)) {
55467                 // No need to normalize when we only have regular required elements
55468                 return createTypeReference(target, elementTypes);
55469             }
55470             if (target.combinedFlags & 8 /* Variadic */) {
55471                 // Transform [A, ...(X | Y | Z)] into [A, ...X] | [A, ...Y] | [A, ...Z]
55472                 var unionIndex_1 = ts.findIndex(elementTypes, function (t, i) { return !!(target.elementFlags[i] & 8 /* Variadic */ && t.flags & (131072 /* Never */ | 1048576 /* Union */)); });
55473                 if (unionIndex_1 >= 0) {
55474                     return checkCrossProductUnion(ts.map(elementTypes, function (t, i) { return target.elementFlags[i] & 8 /* Variadic */ ? t : unknownType; })) ?
55475                         mapType(elementTypes[unionIndex_1], function (t) { return createNormalizedTupleType(target, ts.replaceElement(elementTypes, unionIndex_1, t)); }) :
55476                         errorType;
55477                 }
55478             }
55479             // We have optional, rest, or variadic elements that may need normalizing. Normalization ensures that all variadic
55480             // elements are generic and that the tuple type has one of the following layouts, disregarding variadic elements:
55481             // (1) Zero or more required elements, followed by zero or more optional elements, followed by zero or one rest element.
55482             // (2) Zero or more required elements, followed by a rest element, followed by zero or more required elements.
55483             // In either layout, zero or more generic variadic elements may be present at any location.
55484             var expandedTypes = [];
55485             var expandedFlags = [];
55486             var expandedDeclarations = [];
55487             var lastRequiredIndex = -1;
55488             var firstRestIndex = -1;
55489             var lastOptionalOrRestIndex = -1;
55490             var _loop_13 = function (i) {
55491                 var type = elementTypes[i];
55492                 var flags = target.elementFlags[i];
55493                 if (flags & 8 /* Variadic */) {
55494                     if (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type)) {
55495                         // Generic variadic elements stay as they are.
55496                         addElement(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]);
55497                     }
55498                     else if (isTupleType(type)) {
55499                         var elements = getTypeArguments(type);
55500                         if (elements.length + expandedTypes.length >= 10000) {
55501                             error(currentNode, ts.isPartOfTypeNode(currentNode)
55502                                 ? ts.Diagnostics.Type_produces_a_tuple_type_that_is_too_large_to_represent
55503                                 : ts.Diagnostics.Expression_produces_a_tuple_type_that_is_too_large_to_represent);
55504                             return { value: errorType };
55505                         }
55506                         // Spread variadic elements with tuple types into the resulting tuple.
55507                         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]); });
55508                     }
55509                     else {
55510                         // Treat everything else as an array type and create a rest element.
55511                         addElement(isArrayLikeType(type) && getIndexTypeOfType(type, 1 /* Number */) || errorType, 4 /* Rest */, (_b = target.labeledElementDeclarations) === null || _b === void 0 ? void 0 : _b[i]);
55512                     }
55513                 }
55514                 else {
55515                     // Copy other element kinds with no change.
55516                     addElement(type, flags, (_c = target.labeledElementDeclarations) === null || _c === void 0 ? void 0 : _c[i]);
55517                 }
55518             };
55519             for (var i = 0; i < elementTypes.length; i++) {
55520                 var state_4 = _loop_13(i);
55521                 if (typeof state_4 === "object")
55522                     return state_4.value;
55523             }
55524             // Turn optional elements preceding the last required element into required elements
55525             for (var i = 0; i < lastRequiredIndex; i++) {
55526                 if (expandedFlags[i] & 2 /* Optional */)
55527                     expandedFlags[i] = 1 /* Required */;
55528             }
55529             if (firstRestIndex >= 0 && firstRestIndex < lastOptionalOrRestIndex) {
55530                 // Turn elements between first rest and last optional/rest into a single rest element
55531                 expandedTypes[firstRestIndex] = getUnionType(ts.sameMap(expandedTypes.slice(firstRestIndex, lastOptionalOrRestIndex + 1), function (t, i) { return expandedFlags[firstRestIndex + i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t; }));
55532                 expandedTypes.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex);
55533                 expandedFlags.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex);
55534                 expandedDeclarations === null || expandedDeclarations === void 0 ? void 0 : expandedDeclarations.splice(firstRestIndex + 1, lastOptionalOrRestIndex - firstRestIndex);
55535             }
55536             var tupleTarget = getTupleTargetType(expandedFlags, target.readonly, expandedDeclarations);
55537             return tupleTarget === emptyGenericType ? emptyObjectType :
55538                 expandedFlags.length ? createTypeReference(tupleTarget, expandedTypes) :
55539                     tupleTarget;
55540             function addElement(type, flags, declaration) {
55541                 if (flags & 1 /* Required */) {
55542                     lastRequiredIndex = expandedFlags.length;
55543                 }
55544                 if (flags & 4 /* Rest */ && firstRestIndex < 0) {
55545                     firstRestIndex = expandedFlags.length;
55546                 }
55547                 if (flags & (2 /* Optional */ | 4 /* Rest */)) {
55548                     lastOptionalOrRestIndex = expandedFlags.length;
55549                 }
55550                 expandedTypes.push(type);
55551                 expandedFlags.push(flags);
55552                 if (expandedDeclarations && declaration) {
55553                     expandedDeclarations.push(declaration);
55554                 }
55555                 else {
55556                     expandedDeclarations = undefined;
55557                 }
55558             }
55559         }
55560         function sliceTupleType(type, index, endSkipCount) {
55561             if (endSkipCount === void 0) { endSkipCount = 0; }
55562             var target = type.target;
55563             var endIndex = getTypeReferenceArity(type) - endSkipCount;
55564             return index > target.fixedLength ? getRestArrayTypeOfTupleType(type) || createTupleType(ts.emptyArray) :
55565                 createTupleType(getTypeArguments(type).slice(index, endIndex), target.elementFlags.slice(index, endIndex), 
55566                 /*readonly*/ false, target.labeledElementDeclarations && target.labeledElementDeclarations.slice(index, endIndex));
55567         }
55568         function getKnownKeysOfTupleType(type) {
55569             return getUnionType(ts.append(ts.arrayOf(type.target.fixedLength, function (i) { return getLiteralType("" + i); }), getIndexType(type.target.readonly ? globalReadonlyArrayType : globalArrayType)));
55570         }
55571         // Return count of starting consecutive tuple elements of the given kind(s)
55572         function getStartElementCount(type, flags) {
55573             var index = ts.findIndex(type.elementFlags, function (f) { return !(f & flags); });
55574             return index >= 0 ? index : type.elementFlags.length;
55575         }
55576         // Return count of ending consecutive tuple elements of the given kind(s)
55577         function getEndElementCount(type, flags) {
55578             return type.elementFlags.length - ts.findLastIndex(type.elementFlags, function (f) { return !(f & flags); }) - 1;
55579         }
55580         function getTypeFromOptionalTypeNode(node) {
55581             var type = getTypeFromTypeNode(node.type);
55582             return strictNullChecks ? getOptionalType(type) : type;
55583         }
55584         function getTypeId(type) {
55585             return type.id;
55586         }
55587         function containsType(types, type) {
55588             return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0;
55589         }
55590         function insertType(types, type) {
55591             var index = ts.binarySearch(types, type, getTypeId, ts.compareValues);
55592             if (index < 0) {
55593                 types.splice(~index, 0, type);
55594                 return true;
55595             }
55596             return false;
55597         }
55598         function addTypeToUnion(typeSet, includes, type) {
55599             var flags = type.flags;
55600             if (flags & 1048576 /* Union */) {
55601                 return addTypesToUnion(typeSet, includes | (isNamedUnionType(type) ? 1048576 /* Union */ : 0), type.types);
55602             }
55603             // We ignore 'never' types in unions
55604             if (!(flags & 131072 /* Never */)) {
55605                 includes |= flags & 205258751 /* IncludesMask */;
55606                 if (flags & 469499904 /* StructuredOrInstantiable */)
55607                     includes |= 262144 /* IncludesStructuredOrInstantiable */;
55608                 if (type === wildcardType)
55609                     includes |= 8388608 /* IncludesWildcard */;
55610                 if (!strictNullChecks && flags & 98304 /* Nullable */) {
55611                     if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */))
55612                         includes |= 4194304 /* IncludesNonWideningType */;
55613                 }
55614                 else {
55615                     var len = typeSet.length;
55616                     var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues);
55617                     if (index < 0) {
55618                         typeSet.splice(~index, 0, type);
55619                     }
55620                 }
55621             }
55622             return includes;
55623         }
55624         // Add the given types to the given type set. Order is preserved, duplicates are removed,
55625         // and nested types of the given kind are flattened into the set.
55626         function addTypesToUnion(typeSet, includes, types) {
55627             for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
55628                 var type = types_10[_i];
55629                 includes = addTypeToUnion(typeSet, includes, type);
55630             }
55631             return includes;
55632         }
55633         function removeSubtypes(types, hasObjectTypes) {
55634             // We assume that redundant primitive types have already been removed from the types array and that there
55635             // are no any and unknown types in the array. Thus, the only possible supertypes for primitive types are empty
55636             // object types, and if none of those are present we can exclude primitive types from the subtype check.
55637             var hasEmptyObject = hasObjectTypes && ts.some(types, function (t) { return !!(t.flags & 524288 /* Object */) && !isGenericMappedType(t) && isEmptyResolvedType(resolveStructuredTypeMembers(t)); });
55638             var len = types.length;
55639             var i = len;
55640             var count = 0;
55641             while (i > 0) {
55642                 i--;
55643                 var source = types[i];
55644                 if (hasEmptyObject || source.flags & 469499904 /* StructuredOrInstantiable */) {
55645                     for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
55646                         var target = types_11[_i];
55647                         if (source !== target) {
55648                             if (count === 100000) {
55649                                 // After 100000 subtype checks we estimate the remaining amount of work by assuming the
55650                                 // same ratio of checks per element. If the estimated number of remaining type checks is
55651                                 // greater than 1M we deem the union type too complex to represent. This for example
55652                                 // caps union types at 1000 unique object types.
55653                                 var estimatedCount = (count / (len - i)) * len;
55654                                 if (estimatedCount > 1000000) {
55655                                     ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) });
55656                                     error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
55657                                     return false;
55658                                 }
55659                             }
55660                             count++;
55661                             if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
55662                                 !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
55663                                 isTypeDerivedFrom(source, target))) {
55664                                 ts.orderedRemoveItemAt(types, i);
55665                                 break;
55666                             }
55667                         }
55668                     }
55669                 }
55670             }
55671             return true;
55672         }
55673         function removeRedundantLiteralTypes(types, includes, reduceVoidUndefined) {
55674             var i = types.length;
55675             while (i > 0) {
55676                 i--;
55677                 var t = types[i];
55678                 var flags = t.flags;
55679                 var remove = flags & 128 /* StringLiteral */ && includes & 4 /* String */ ||
55680                     flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ ||
55681                     flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ ||
55682                     flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ ||
55683                     reduceVoidUndefined && flags & 32768 /* Undefined */ && includes & 16384 /* Void */ ||
55684                     isFreshLiteralType(t) && containsType(types, t.regularType);
55685                 if (remove) {
55686                     ts.orderedRemoveItemAt(types, i);
55687                 }
55688             }
55689         }
55690         function removeStringLiteralsMatchedByTemplateLiterals(types) {
55691             var templates = ts.filter(types, isPatternLiteralType);
55692             if (templates.length) {
55693                 var i = types.length;
55694                 var _loop_14 = function () {
55695                     i--;
55696                     var t = types[i];
55697                     if (t.flags & 128 /* StringLiteral */ && ts.some(templates, function (template) { return isTypeSubtypeOf(t, template); })) {
55698                         ts.orderedRemoveItemAt(types, i);
55699                     }
55700                 };
55701                 while (i > 0) {
55702                     _loop_14();
55703                 }
55704             }
55705         }
55706         function isNamedUnionType(type) {
55707             return !!(type.flags & 1048576 /* Union */ && (type.aliasSymbol || type.origin));
55708         }
55709         function addNamedUnions(namedUnions, types) {
55710             for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
55711                 var t = types_12[_i];
55712                 if (t.flags & 1048576 /* Union */) {
55713                     var origin = t.origin;
55714                     if (t.aliasSymbol || origin && !(origin.flags & 1048576 /* Union */)) {
55715                         ts.pushIfUnique(namedUnions, t);
55716                     }
55717                     else if (origin && origin.flags & 1048576 /* Union */) {
55718                         addNamedUnions(namedUnions, origin.types);
55719                     }
55720                 }
55721             }
55722         }
55723         function createOriginUnionOrIntersectionType(flags, types) {
55724             var result = createOriginType(flags);
55725             result.types = types;
55726             return result;
55727         }
55728         // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction
55729         // flag is specified we also reduce the constituent type set to only include types that aren't subtypes
55730         // of other types. Subtype reduction is expensive for large union types and is possible only when union
55731         // types are known not to circularly reference themselves (as is the case with union types created by
55732         // expression constructs such as array literals and the || and ?: operators). Named types can
55733         // circularly reference themselves and therefore cannot be subtype reduced during their declaration.
55734         // For example, "type Item = string | (() => Item" is a named type that circularly references itself.
55735         function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments, origin) {
55736             if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
55737             if (types.length === 0) {
55738                 return neverType;
55739             }
55740             if (types.length === 1) {
55741                 return types[0];
55742             }
55743             var typeSet = [];
55744             var includes = addTypesToUnion(typeSet, 0, types);
55745             if (unionReduction !== 0 /* None */) {
55746                 if (includes & 3 /* AnyOrUnknown */) {
55747                     return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
55748                 }
55749                 if (unionReduction & (1 /* Literal */ | 2 /* Subtype */)) {
55750                     if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */) || includes & 16384 /* Void */ && includes & 32768 /* Undefined */) {
55751                         removeRedundantLiteralTypes(typeSet, includes, !!(unionReduction & 2 /* Subtype */));
55752                     }
55753                     if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) {
55754                         removeStringLiteralsMatchedByTemplateLiterals(typeSet);
55755                     }
55756                 }
55757                 if (unionReduction & 2 /* Subtype */) {
55758                     if (!removeSubtypes(typeSet, !!(includes & 524288 /* Object */))) {
55759                         return errorType;
55760                     }
55761                 }
55762                 if (typeSet.length === 0) {
55763                     return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType :
55764                         includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
55765                             neverType;
55766                 }
55767             }
55768             if (!origin && includes & 1048576 /* Union */) {
55769                 var namedUnions = [];
55770                 addNamedUnions(namedUnions, types);
55771                 var reducedTypes = [];
55772                 var _loop_15 = function (t) {
55773                     if (!ts.some(namedUnions, function (union) { return containsType(union.types, t); })) {
55774                         reducedTypes.push(t);
55775                     }
55776                 };
55777                 for (var _i = 0, typeSet_1 = typeSet; _i < typeSet_1.length; _i++) {
55778                     var t = typeSet_1[_i];
55779                     _loop_15(t);
55780                 }
55781                 if (!aliasSymbol && namedUnions.length === 1 && reducedTypes.length === 0) {
55782                     return namedUnions[0];
55783                 }
55784                 // We create a denormalized origin type only when the union was created from one or more named unions
55785                 // (unions with alias symbols or origins) and when there is no overlap between those named unions.
55786                 var namedTypesCount = ts.reduceLeft(namedUnions, function (sum, union) { return sum + union.types.length; }, 0);
55787                 if (namedTypesCount + reducedTypes.length === typeSet.length) {
55788                     for (var _a = 0, namedUnions_1 = namedUnions; _a < namedUnions_1.length; _a++) {
55789                         var t = namedUnions_1[_a];
55790                         insertType(reducedTypes, t);
55791                     }
55792                     origin = createOriginUnionOrIntersectionType(1048576 /* Union */, reducedTypes);
55793                 }
55794             }
55795             var objectFlags = (includes & 468598819 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) |
55796                 (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0);
55797             return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments, origin);
55798         }
55799         function getUnionTypePredicate(signatures) {
55800             var first;
55801             var types = [];
55802             for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) {
55803                 var sig = signatures_6[_i];
55804                 var pred = getTypePredicateOfSignature(sig);
55805                 if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) {
55806                     continue;
55807                 }
55808                 if (first) {
55809                     if (!typePredicateKindsMatch(first, pred)) {
55810                         // No common type predicate.
55811                         return undefined;
55812                     }
55813                 }
55814                 else {
55815                     first = pred;
55816                 }
55817                 types.push(pred.type);
55818             }
55819             if (!first) {
55820                 // No union signatures had a type predicate.
55821                 return undefined;
55822             }
55823             var unionType = getUnionType(types);
55824             return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType);
55825         }
55826         function typePredicateKindsMatch(a, b) {
55827             return a.kind === b.kind && a.parameterIndex === b.parameterIndex;
55828         }
55829         function createUnionType(types, aliasSymbol, aliasTypeArguments, origin) {
55830             var result = createType(1048576 /* Union */);
55831             result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
55832             result.types = types;
55833             result.origin = origin;
55834             result.aliasSymbol = aliasSymbol;
55835             result.aliasTypeArguments = aliasTypeArguments;
55836             return result;
55837         }
55838         // This function assumes the constituent type list is sorted and deduplicated.
55839         function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments, origin) {
55840             if (types.length === 0) {
55841                 return neverType;
55842             }
55843             if (types.length === 1) {
55844                 return types[0];
55845             }
55846             var typeKey = !origin ? getTypeListId(types) :
55847                 origin.flags & 1048576 /* Union */ ? "|" + getTypeListId(origin.types) :
55848                     origin.flags & 2097152 /* Intersection */ ? "&" + getTypeListId(origin.types) :
55849                         "#" + origin.type.id;
55850             var id = typeKey + getAliasId(aliasSymbol, aliasTypeArguments);
55851             var type = unionTypes.get(id);
55852             if (!type) {
55853                 type = createUnionType(types, aliasSymbol, aliasTypeArguments, origin);
55854                 type.objectFlags |= objectFlags;
55855                 unionTypes.set(id, type);
55856             }
55857             return type;
55858         }
55859         function getTypeFromUnionTypeNode(node) {
55860             var links = getNodeLinks(node);
55861             if (!links.resolvedType) {
55862                 var aliasSymbol = getAliasSymbolForTypeNode(node);
55863                 links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
55864             }
55865             return links.resolvedType;
55866         }
55867         function addTypeToIntersection(typeSet, includes, type) {
55868             var flags = type.flags;
55869             if (flags & 2097152 /* Intersection */) {
55870                 return addTypesToIntersection(typeSet, includes, type.types);
55871             }
55872             if (isEmptyAnonymousObjectType(type)) {
55873                 if (!(includes & 16777216 /* IncludesEmptyObject */)) {
55874                     includes |= 16777216 /* IncludesEmptyObject */;
55875                     typeSet.set(type.id.toString(), type);
55876                 }
55877             }
55878             else {
55879                 if (flags & 3 /* AnyOrUnknown */) {
55880                     if (type === wildcardType)
55881                         includes |= 8388608 /* IncludesWildcard */;
55882                 }
55883                 else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) {
55884                     if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) {
55885                         // We have seen two distinct unit types which means we should reduce to an
55886                         // empty intersection. Adding TypeFlags.NonPrimitive causes that to happen.
55887                         includes |= 67108864 /* NonPrimitive */;
55888                     }
55889                     typeSet.set(type.id.toString(), type);
55890                 }
55891                 includes |= flags & 205258751 /* IncludesMask */;
55892             }
55893             return includes;
55894         }
55895         // Add the given types to the given type set. Order is preserved, freshness is removed from literal
55896         // types, duplicates are removed, and nested types of the given kind are flattened into the set.
55897         function addTypesToIntersection(typeSet, includes, types) {
55898             for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
55899                 var type = types_13[_i];
55900                 includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
55901             }
55902             return includes;
55903         }
55904         function removeRedundantPrimitiveTypes(types, includes) {
55905             var i = types.length;
55906             while (i > 0) {
55907                 i--;
55908                 var t = types[i];
55909                 var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ ||
55910                     t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
55911                     t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
55912                     t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */;
55913                 if (remove) {
55914                     ts.orderedRemoveItemAt(types, i);
55915                 }
55916             }
55917         }
55918         // Check that the given type has a match in every union. A given type is matched by
55919         // an identical type, and a literal type is additionally matched by its corresponding
55920         // primitive type.
55921         function eachUnionContains(unionTypes, type) {
55922             for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) {
55923                 var u = unionTypes_1[_i];
55924                 if (!containsType(u.types, type)) {
55925                     var primitive = type.flags & 128 /* StringLiteral */ ? stringType :
55926                         type.flags & 256 /* NumberLiteral */ ? numberType :
55927                             type.flags & 2048 /* BigIntLiteral */ ? bigintType :
55928                                 type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
55929                                     undefined;
55930                     if (!primitive || !containsType(u.types, primitive)) {
55931                         return false;
55932                     }
55933                 }
55934             }
55935             return true;
55936         }
55937         /**
55938          * 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`
55939          */
55940         function extractRedundantTemplateLiterals(types) {
55941             var i = types.length;
55942             var literals = ts.filter(types, function (t) { return !!(t.flags & 128 /* StringLiteral */); });
55943             while (i > 0) {
55944                 i--;
55945                 var t = types[i];
55946                 if (!(t.flags & 134217728 /* TemplateLiteral */))
55947                     continue;
55948                 for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) {
55949                     var t2 = literals_1[_i];
55950                     if (isTypeSubtypeOf(t2, t)) {
55951                         // eg, ``get${T}` & "getX"` is just `"getX"`
55952                         ts.orderedRemoveItemAt(types, i);
55953                         break;
55954                     }
55955                     else if (isPatternLiteralType(t)) {
55956                         return true;
55957                     }
55958                 }
55959             }
55960             return false;
55961         }
55962         function extractIrreducible(types, flag) {
55963             if (ts.every(types, function (t) { return !!(t.flags & 1048576 /* Union */) && ts.some(t.types, function (tt) { return !!(tt.flags & flag); }); })) {
55964                 for (var i = 0; i < types.length; i++) {
55965                     types[i] = filterType(types[i], function (t) { return !(t.flags & flag); });
55966                 }
55967                 return true;
55968             }
55969             return false;
55970         }
55971         // If the given list of types contains more than one union of primitive types, replace the
55972         // first with a union containing an intersection of those primitive types, then remove the
55973         // other unions and return true. Otherwise, do nothing and return false.
55974         function intersectUnionsOfPrimitiveTypes(types) {
55975             var unionTypes;
55976             var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); });
55977             if (index < 0) {
55978                 return false;
55979             }
55980             var i = index + 1;
55981             // Remove all but the first union of primitive types and collect them in
55982             // the unionTypes array.
55983             while (i < types.length) {
55984                 var t = types[i];
55985                 if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) {
55986                     (unionTypes || (unionTypes = [types[index]])).push(t);
55987                     ts.orderedRemoveItemAt(types, i);
55988                 }
55989                 else {
55990                     i++;
55991                 }
55992             }
55993             // Return false if there was only one union of primitive types
55994             if (!unionTypes) {
55995                 return false;
55996             }
55997             // We have more than one union of primitive types, now intersect them. For each
55998             // type in each union we check if the type is matched in every union and if so
55999             // we include it in the result.
56000             var checked = [];
56001             var result = [];
56002             for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) {
56003                 var u = unionTypes_2[_i];
56004                 for (var _a = 0, _b = u.types; _a < _b.length; _a++) {
56005                     var t = _b[_a];
56006                     if (insertType(checked, t)) {
56007                         if (eachUnionContains(unionTypes, t)) {
56008                             insertType(result, t);
56009                         }
56010                     }
56011                 }
56012             }
56013             // Finally replace the first union with the result
56014             types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */);
56015             return true;
56016         }
56017         function createIntersectionType(types, aliasSymbol, aliasTypeArguments) {
56018             var result = createType(2097152 /* Intersection */);
56019             result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
56020             result.types = types;
56021             result.aliasSymbol = aliasSymbol;
56022             result.aliasTypeArguments = aliasTypeArguments;
56023             return result;
56024         }
56025         // We normalize combinations of intersection and union types based on the distributive property of the '&'
56026         // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
56027         // types with union type constituents into equivalent union types with intersection type constituents and
56028         // effectively ensure that union types are always at the top level in type representations.
56029         //
56030         // We do not perform structural deduplication on intersection types. Intersection types are created only by the &
56031         // type operator and we can't reduce those because we want to support recursive intersection types. For example,
56032         // a type alias of the form "type List<T> = T & { next: List<T> }" cannot be reduced during its declaration.
56033         // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution
56034         // for intersections of types with signatures can be deterministic.
56035         function getIntersectionType(types, aliasSymbol, aliasTypeArguments) {
56036             var typeMembershipMap = new ts.Map();
56037             var includes = addTypesToIntersection(typeMembershipMap, 0, types);
56038             var typeSet = ts.arrayFrom(typeMembershipMap.values());
56039             // An intersection type is considered empty if it contains
56040             // the type never, or
56041             // more than one unit type or,
56042             // an object type and a nullable type (null or undefined), or
56043             // a string-like type and a type known to be non-string-like, or
56044             // a number-like type and a type known to be non-number-like, or
56045             // a symbol-like type and a type known to be non-symbol-like, or
56046             // a void-like type and a type known to be non-void-like, or
56047             // a non-primitive type and a type known to be primitive.
56048             if (includes & 131072 /* Never */ ||
56049                 strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) ||
56050                 includes & 67108864 /* NonPrimitive */ && includes & (469892092 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) ||
56051                 includes & 402653316 /* StringLike */ && includes & (469892092 /* DisjointDomains */ & ~402653316 /* StringLike */) ||
56052                 includes & 296 /* NumberLike */ && includes & (469892092 /* DisjointDomains */ & ~296 /* NumberLike */) ||
56053                 includes & 2112 /* BigIntLike */ && includes & (469892092 /* DisjointDomains */ & ~2112 /* BigIntLike */) ||
56054                 includes & 12288 /* ESSymbolLike */ && includes & (469892092 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) ||
56055                 includes & 49152 /* VoidLike */ && includes & (469892092 /* DisjointDomains */ & ~49152 /* VoidLike */)) {
56056                 return neverType;
56057             }
56058             if (includes & 134217728 /* TemplateLiteral */ && includes & 128 /* StringLiteral */ && extractRedundantTemplateLiterals(typeSet)) {
56059                 return neverType;
56060             }
56061             if (includes & 1 /* Any */) {
56062                 return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType;
56063             }
56064             if (!strictNullChecks && includes & 98304 /* Nullable */) {
56065                 return includes & 32768 /* Undefined */ ? undefinedType : nullType;
56066             }
56067             if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ ||
56068                 includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
56069                 includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
56070                 includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
56071                 removeRedundantPrimitiveTypes(typeSet, includes);
56072             }
56073             if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
56074                 ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
56075             }
56076             if (typeSet.length === 0) {
56077                 return unknownType;
56078             }
56079             if (typeSet.length === 1) {
56080                 return typeSet[0];
56081             }
56082             var id = getTypeListId(typeSet) + getAliasId(aliasSymbol, aliasTypeArguments);
56083             var result = intersectionTypes.get(id);
56084             if (!result) {
56085                 if (includes & 1048576 /* Union */) {
56086                     if (intersectUnionsOfPrimitiveTypes(typeSet)) {
56087                         // When the intersection creates a reduced set (which might mean that *all* union types have
56088                         // disappeared), we restart the operation to get a new set of combined flags. Once we have
56089                         // reduced we'll never reduce again, so this occurs at most once.
56090                         result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
56091                     }
56092                     else if (extractIrreducible(typeSet, 32768 /* Undefined */)) {
56093                         result = getUnionType([getIntersectionType(typeSet), undefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
56094                     }
56095                     else if (extractIrreducible(typeSet, 65536 /* Null */)) {
56096                         result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
56097                     }
56098                     else {
56099                         // We are attempting to construct a type of the form X & (A | B) & (C | D). Transform this into a type of
56100                         // the form X & A & C | X & A & D | X & B & C | X & B & D. If the estimated size of the resulting union type
56101                         // exceeds 100000 constituents, report an error.
56102                         if (!checkCrossProductUnion(typeSet)) {
56103                             return errorType;
56104                         }
56105                         var constituents = getCrossProductIntersections(typeSet);
56106                         // We attach a denormalized origin type when at least one constituent of the cross-product union is an
56107                         // intersection (i.e. when the intersection didn't just reduce one or more unions to smaller unions).
56108                         var origin = ts.some(constituents, function (t) { return !!(t.flags & 2097152 /* Intersection */); }) ? createOriginUnionOrIntersectionType(2097152 /* Intersection */, typeSet) : undefined;
56109                         result = getUnionType(constituents, 1 /* Literal */, aliasSymbol, aliasTypeArguments, origin);
56110                     }
56111                 }
56112                 else {
56113                     result = createIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
56114                 }
56115                 intersectionTypes.set(id, result);
56116             }
56117             return result;
56118         }
56119         function getCrossProductUnionSize(types) {
56120             return ts.reduceLeft(types, function (n, t) { return t.flags & 1048576 /* Union */ ? n * t.types.length : t.flags & 131072 /* Never */ ? 0 : n; }, 1);
56121         }
56122         function checkCrossProductUnion(types) {
56123             var size = getCrossProductUnionSize(types);
56124             if (size >= 100000) {
56125                 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 });
56126                 error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
56127                 return false;
56128             }
56129             return true;
56130         }
56131         function getCrossProductIntersections(types) {
56132             var count = getCrossProductUnionSize(types);
56133             var intersections = [];
56134             for (var i = 0; i < count; i++) {
56135                 var constituents = types.slice();
56136                 var n = i;
56137                 for (var j = types.length - 1; j >= 0; j--) {
56138                     if (types[j].flags & 1048576 /* Union */) {
56139                         var sourceTypes = types[j].types;
56140                         var length_5 = sourceTypes.length;
56141                         constituents[j] = sourceTypes[n % length_5];
56142                         n = Math.floor(n / length_5);
56143                     }
56144                 }
56145                 var t = getIntersectionType(constituents);
56146                 if (!(t.flags & 131072 /* Never */))
56147                     intersections.push(t);
56148             }
56149             return intersections;
56150         }
56151         function getTypeFromIntersectionTypeNode(node) {
56152             var links = getNodeLinks(node);
56153             if (!links.resolvedType) {
56154                 var aliasSymbol = getAliasSymbolForTypeNode(node);
56155                 links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
56156             }
56157             return links.resolvedType;
56158         }
56159         function createIndexType(type, stringsOnly) {
56160             var result = createType(4194304 /* Index */);
56161             result.type = type;
56162             result.stringsOnly = stringsOnly;
56163             return result;
56164         }
56165         function createOriginIndexType(type) {
56166             var result = createOriginType(4194304 /* Index */);
56167             result.type = type;
56168             return result;
56169         }
56170         function getIndexTypeForGenericType(type, stringsOnly) {
56171             return stringsOnly ?
56172                 type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) :
56173                 type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false));
56174         }
56175         function instantiateTypeAsMappedNameType(nameType, type, t) {
56176             return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t));
56177         }
56178         function getIndexTypeForMappedType(type, noIndexSignatures) {
56179             var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); });
56180             var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType);
56181             // If the constraint is exclusively string/number/never type(s), we need to pull the property names from the modified type and run them through the `nameType` mapper as well
56182             // since they won't appear in the constraint, due to subtype reducing with the string/number index types
56183             var properties = nameType && everyType(constraint, function (t) { return !!(t.flags & (4 /* String */ | 8 /* Number */ | 131072 /* Never */)); }) && getPropertiesOfType(getApparentType(getModifiersTypeFromMappedType(type)));
56184             return nameType ?
56185                 getUnionType([mapType(constraint, function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); }), mapType(getUnionType(ts.map(properties || ts.emptyArray, function (p) { return getLiteralTypeFromProperty(p, 8576 /* StringOrNumberLiteralOrUnique */); })), function (t) { return instantiateTypeAsMappedNameType(nameType, type, t); })]) :
56186                 constraint;
56187         }
56188         // 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
56189         // that N distributes over union types, i.e. that N<A | B | C> is equivalent to N<A> | N<B> | N<C>. That presumption may not
56190         // be true when N is a non-distributive conditional type or an instantiable type with a non-distributive conditional type as
56191         // a constituent. In those cases, we cannot reduce keyof M and need to preserve it as is.
56192         function maybeNonDistributiveNameType(type) {
56193             return !!(type && (type.flags & 16777216 /* Conditional */ && (!type.root.isDistributive || maybeNonDistributiveNameType(type.checkType)) ||
56194                 type.flags & (3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */) && ts.some(type.types, maybeNonDistributiveNameType) ||
56195                 type.flags & (4194304 /* Index */ | 268435456 /* StringMapping */) && maybeNonDistributiveNameType(type.type) ||
56196                 type.flags & 8388608 /* IndexedAccess */ && maybeNonDistributiveNameType(type.indexType) ||
56197                 type.flags & 33554432 /* Substitution */ && maybeNonDistributiveNameType(type.substitute)));
56198         }
56199         function getLiteralTypeFromPropertyName(name) {
56200             if (ts.isPrivateIdentifier(name)) {
56201                 return neverType;
56202             }
56203             return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) :
56204                 getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name));
56205         }
56206         function getBigIntLiteralType(node) {
56207             return getLiteralType({
56208                 negative: false,
56209                 base10Value: ts.parsePseudoBigInt(node.text)
56210             });
56211         }
56212         function getLiteralTypeFromProperty(prop, include) {
56213             if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) {
56214                 var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType;
56215                 if (!type && !ts.isKnownSymbol(prop)) {
56216                     if (prop.escapedName === "default" /* Default */) {
56217                         type = getLiteralType("default");
56218                     }
56219                     else {
56220                         var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration);
56221                         type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop));
56222                     }
56223                 }
56224                 if (type && type.flags & include) {
56225                     return type;
56226                 }
56227             }
56228             return neverType;
56229         }
56230         function getLiteralTypeFromProperties(type, include, includeOrigin) {
56231             var origin = includeOrigin && (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */) || type.aliasSymbol) ? createOriginIndexType(type) : undefined;
56232             return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }), 1 /* Literal */, 
56233             /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, origin);
56234         }
56235         function getNonEnumNumberIndexInfo(type) {
56236             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
56237             return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined;
56238         }
56239         function getIndexType(type, stringsOnly, noIndexSignatures) {
56240             if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; }
56241             var includeOrigin = stringsOnly === keyofStringsOnly && !noIndexSignatures;
56242             type = getReducedType(type);
56243             return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
56244                 type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
56245                     type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && maybeNonDistributiveNameType(getNameTypeFromMappedType(type)) ? getIndexTypeForGenericType(type, stringsOnly) :
56246                         ts.getObjectFlags(type) & 32 /* Mapped */ ? getIndexTypeForMappedType(type, noIndexSignatures) :
56247                             type === wildcardType ? wildcardType :
56248                                 type.flags & 2 /* Unknown */ ? neverType :
56249                                     type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType :
56250                                         stringsOnly ? !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */, includeOrigin) :
56251                                             !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */, includeOrigin)]) :
56252                                                 getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */, includeOrigin)]) :
56253                                                     getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */, includeOrigin);
56254         }
56255         function getExtractStringType(type) {
56256             if (keyofStringsOnly) {
56257                 return type;
56258             }
56259             var extractTypeAlias = getGlobalExtractSymbol();
56260             return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType;
56261         }
56262         function getIndexTypeOrString(type) {
56263             var indexType = getExtractStringType(getIndexType(type));
56264             return indexType.flags & 131072 /* Never */ ? stringType : indexType;
56265         }
56266         function getTypeFromTypeOperatorNode(node) {
56267             var links = getNodeLinks(node);
56268             if (!links.resolvedType) {
56269                 switch (node.operator) {
56270                     case 138 /* KeyOfKeyword */:
56271                         links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
56272                         break;
56273                     case 151 /* UniqueKeyword */:
56274                         links.resolvedType = node.type.kind === 148 /* SymbolKeyword */
56275                             ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
56276                             : errorType;
56277                         break;
56278                     case 142 /* ReadonlyKeyword */:
56279                         links.resolvedType = getTypeFromTypeNode(node.type);
56280                         break;
56281                     default:
56282                         throw ts.Debug.assertNever(node.operator);
56283                 }
56284             }
56285             return links.resolvedType;
56286         }
56287         function getTypeFromTemplateTypeNode(node) {
56288             var links = getNodeLinks(node);
56289             if (!links.resolvedType) {
56290                 links.resolvedType = getTemplateLiteralType(__spreadArray([node.head.text], ts.map(node.templateSpans, function (span) { return span.literal.text; })), ts.map(node.templateSpans, function (span) { return getTypeFromTypeNode(span.type); }));
56291             }
56292             return links.resolvedType;
56293         }
56294         function getTemplateLiteralType(texts, types) {
56295             var unionIndex = ts.findIndex(types, function (t) { return !!(t.flags & (131072 /* Never */ | 1048576 /* Union */)); });
56296             if (unionIndex >= 0) {
56297                 return checkCrossProductUnion(types) ?
56298                     mapType(types[unionIndex], function (t) { return getTemplateLiteralType(texts, ts.replaceElement(types, unionIndex, t)); }) :
56299                     errorType;
56300             }
56301             if (ts.contains(types, wildcardType)) {
56302                 return wildcardType;
56303             }
56304             var newTypes = [];
56305             var newTexts = [];
56306             var text = texts[0];
56307             if (!addSpans(texts, types)) {
56308                 return stringType;
56309             }
56310             if (newTypes.length === 0) {
56311                 return getLiteralType(text);
56312             }
56313             newTexts.push(text);
56314             if (ts.every(newTexts, function (t) { return t === ""; }) && ts.every(newTypes, function (t) { return !!(t.flags & 4 /* String */); })) {
56315                 return stringType;
56316             }
56317             var id = getTypeListId(newTypes) + "|" + ts.map(newTexts, function (t) { return t.length; }).join(",") + "|" + newTexts.join("");
56318             var type = templateLiteralTypes.get(id);
56319             if (!type) {
56320                 templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes));
56321             }
56322             return type;
56323             function addSpans(texts, types) {
56324                 for (var i = 0; i < types.length; i++) {
56325                     var t = types[i];
56326                     if (t.flags & (2944 /* Literal */ | 65536 /* Null */ | 32768 /* Undefined */)) {
56327                         text += getTemplateStringForType(t) || "";
56328                         text += texts[i + 1];
56329                     }
56330                     else if (t.flags & 134217728 /* TemplateLiteral */) {
56331                         text += t.texts[0];
56332                         if (!addSpans(t.texts, t.types))
56333                             return false;
56334                         text += texts[i + 1];
56335                     }
56336                     else if (isGenericIndexType(t) || isPatternLiteralPlaceholderType(t)) {
56337                         newTypes.push(t);
56338                         newTexts.push(text);
56339                         text = texts[i + 1];
56340                     }
56341                     else {
56342                         return false;
56343                     }
56344                 }
56345                 return true;
56346             }
56347         }
56348         function getTemplateStringForType(type) {
56349             return type.flags & 128 /* StringLiteral */ ? type.value :
56350                 type.flags & 256 /* NumberLiteral */ ? "" + type.value :
56351                     type.flags & 2048 /* BigIntLiteral */ ? ts.pseudoBigIntToString(type.value) :
56352                         type.flags & 512 /* BooleanLiteral */ ? type.intrinsicName :
56353                             type.flags & 65536 /* Null */ ? "null" :
56354                                 type.flags & 32768 /* Undefined */ ? "undefined" :
56355                                     undefined;
56356         }
56357         function createTemplateLiteralType(texts, types) {
56358             var type = createType(134217728 /* TemplateLiteral */);
56359             type.texts = texts;
56360             type.types = types;
56361             return type;
56362         }
56363         function getStringMappingType(symbol, type) {
56364             return type.flags & (1048576 /* Union */ | 131072 /* Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) :
56365                 isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) :
56366                     type.flags & 128 /* StringLiteral */ ? getLiteralType(applyStringMapping(symbol, type.value)) :
56367                         type;
56368         }
56369         function applyStringMapping(symbol, str) {
56370             switch (intrinsicTypeKinds.get(symbol.escapedName)) {
56371                 case 0 /* Uppercase */: return str.toUpperCase();
56372                 case 1 /* Lowercase */: return str.toLowerCase();
56373                 case 2 /* Capitalize */: return str.charAt(0).toUpperCase() + str.slice(1);
56374                 case 3 /* Uncapitalize */: return str.charAt(0).toLowerCase() + str.slice(1);
56375             }
56376             return str;
56377         }
56378         function getStringMappingTypeForGenericType(symbol, type) {
56379             var id = getSymbolId(symbol) + "," + getTypeId(type);
56380             var result = stringMappingTypes.get(id);
56381             if (!result) {
56382                 stringMappingTypes.set(id, result = createStringMappingType(symbol, type));
56383             }
56384             return result;
56385         }
56386         function createStringMappingType(symbol, type) {
56387             var result = createType(268435456 /* StringMapping */);
56388             result.symbol = symbol;
56389             result.type = type;
56390             return result;
56391         }
56392         function createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined) {
56393             var type = createType(8388608 /* IndexedAccess */);
56394             type.objectType = objectType;
56395             type.indexType = indexType;
56396             type.aliasSymbol = aliasSymbol;
56397             type.aliasTypeArguments = aliasTypeArguments;
56398             type.noUncheckedIndexedAccessCandidate = shouldIncludeUndefined;
56399             return type;
56400         }
56401         /**
56402          * Returns if a type is or consists of a JSLiteral object type
56403          * In addition to objects which are directly literals,
56404          * * unions where every element is a jsliteral
56405          * * intersections where at least one element is a jsliteral
56406          * * and instantiable types constrained to a jsliteral
56407          * Should all count as literals and not print errors on access or assignment of possibly existing properties.
56408          * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference).
56409          */
56410         function isJSLiteralType(type) {
56411             if (noImplicitAny) {
56412                 return false; // Flag is meaningless under `noImplicitAny` mode
56413             }
56414             if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) {
56415                 return true;
56416             }
56417             if (type.flags & 1048576 /* Union */) {
56418                 return ts.every(type.types, isJSLiteralType);
56419             }
56420             if (type.flags & 2097152 /* Intersection */) {
56421                 return ts.some(type.types, isJSLiteralType);
56422             }
56423             if (type.flags & 465829888 /* Instantiable */) {
56424                 var constraint = getResolvedBaseConstraint(type);
56425                 return constraint !== type && isJSLiteralType(constraint);
56426             }
56427             return false;
56428         }
56429         function getPropertyNameFromIndex(indexType, accessNode) {
56430             var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined;
56431             return isTypeUsableAsPropertyName(indexType) ?
56432                 getPropertyNameFromType(indexType) :
56433                 accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
56434                     ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) :
56435                     accessNode && ts.isPropertyName(accessNode) ?
56436                         // late bound names are handled in the first branch, so here we only need to handle normal names
56437                         ts.getPropertyNameForPropertyNameNode(accessNode) :
56438                         undefined;
56439         }
56440         function isUncalledFunctionReference(node, symbol) {
56441             if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
56442                 var parent = ts.findAncestor(node.parent, function (n) { return !ts.isAccessExpression(n); }) || node.parent;
56443                 if (ts.isCallLikeExpression(parent)) {
56444                     return ts.isCallOrNewExpression(parent) && ts.isIdentifier(node) && hasMatchingArgument(parent, node);
56445                 }
56446                 return ts.every(symbol.declarations, function (d) { return !ts.isFunctionLike(d) || !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); });
56447             }
56448             return true;
56449         }
56450         function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags, noUncheckedIndexedAccessCandidate, reportDeprecated) {
56451             var _a;
56452             var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined;
56453             var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode);
56454             if (propName !== undefined) {
56455                 var prop = getPropertyOfType(objectType, propName);
56456                 if (prop) {
56457                     if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) {
56458                         var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode);
56459                         addDeprecatedSuggestion(deprecatedNode, prop.declarations, propName);
56460                     }
56461                     if (accessExpression) {
56462                         markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 107 /* ThisKeyword */);
56463                         if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) {
56464                             error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
56465                             return undefined;
56466                         }
56467                         if (accessFlags & 4 /* CacheSymbol */) {
56468                             getNodeLinks(accessNode).resolvedSymbol = prop;
56469                         }
56470                         if (isThisPropertyAccessInConstructor(accessExpression, prop)) {
56471                             return autoType;
56472                         }
56473                     }
56474                     var propType = getTypeOfSymbol(prop);
56475                     return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ?
56476                         getFlowTypeOfReference(accessExpression, propType) :
56477                         propType;
56478                 }
56479                 if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) {
56480                     if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 8 /* NoTupleBoundsCheck */)) {
56481                         var indexNode = getIndexNodeForAccessExpression(accessNode);
56482                         if (isTupleType(objectType)) {
56483                             error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName));
56484                         }
56485                         else {
56486                             error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
56487                         }
56488                     }
56489                     errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, 1 /* Number */));
56490                     return mapType(objectType, function (t) {
56491                         var restType = getRestTypeOfTupleType(t) || undefinedType;
56492                         return noUncheckedIndexedAccessCandidate ? getUnionType([restType, undefinedType]) : restType;
56493                     });
56494                 }
56495             }
56496             if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) {
56497                 if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) {
56498                     return objectType;
56499                 }
56500                 var stringIndexInfo = getIndexInfoOfType(objectType, 0 /* String */);
56501                 var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || stringIndexInfo;
56502                 if (indexInfo) {
56503                     if (accessFlags & 1 /* NoIndexSignatures */ && indexInfo === stringIndexInfo) {
56504                         if (accessExpression) {
56505                             error(accessExpression, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType));
56506                         }
56507                         return undefined;
56508                     }
56509                     if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
56510                         var indexNode = getIndexNodeForAccessExpression(accessNode);
56511                         error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
56512                         return noUncheckedIndexedAccessCandidate ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type;
56513                     }
56514                     errorIfWritingToReadonlyIndex(indexInfo);
56515                     return noUncheckedIndexedAccessCandidate ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type;
56516                 }
56517                 if (indexType.flags & 131072 /* Never */) {
56518                     return neverType;
56519                 }
56520                 if (isJSLiteralType(objectType)) {
56521                     return anyType;
56522                 }
56523                 if (accessExpression && !isConstEnumObjectType(objectType)) {
56524                     if (isObjectLiteralType(objectType)) {
56525                         if (noImplicitAny && indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
56526                             diagnostics.add(ts.createDiagnosticForNode(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType)));
56527                             return undefinedType;
56528                         }
56529                         else if (indexType.flags & (8 /* Number */ | 4 /* String */)) {
56530                             var types = ts.map(objectType.properties, function (property) {
56531                                 return getTypeOfSymbol(property);
56532                             });
56533                             return getUnionType(ts.append(types, undefinedType));
56534                         }
56535                     }
56536                     if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
56537                         error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
56538                     }
56539                     else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !suppressNoImplicitAnyError) {
56540                         if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
56541                             var typeName = typeToString(objectType);
56542                             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) + "]");
56543                         }
56544                         else if (getIndexTypeOfType(objectType, 1 /* Number */)) {
56545                             error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
56546                         }
56547                         else {
56548                             var suggestion = void 0;
56549                             if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
56550                                 if (suggestion !== undefined) {
56551                                     error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
56552                                 }
56553                             }
56554                             else {
56555                                 var suggestion_1 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType);
56556                                 if (suggestion_1 !== undefined) {
56557                                     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);
56558                                 }
56559                                 else {
56560                                     var errorInfo = void 0;
56561                                     if (indexType.flags & 1024 /* EnumLiteral */) {
56562                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType));
56563                                     }
56564                                     else if (indexType.flags & 8192 /* UniqueESSymbol */) {
56565                                         var symbolName_2 = getFullyQualifiedName(indexType.symbol, accessExpression);
56566                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName_2 + "]", typeToString(objectType));
56567                                     }
56568                                     else if (indexType.flags & 128 /* StringLiteral */) {
56569                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
56570                                     }
56571                                     else if (indexType.flags & 256 /* NumberLiteral */) {
56572                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
56573                                     }
56574                                     else if (indexType.flags & (8 /* Number */ | 4 /* String */)) {
56575                                         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));
56576                                     }
56577                                     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));
56578                                     diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(accessExpression, errorInfo));
56579                                 }
56580                             }
56581                         }
56582                     }
56583                     return undefined;
56584                 }
56585             }
56586             if (isJSLiteralType(objectType)) {
56587                 return anyType;
56588             }
56589             if (accessNode) {
56590                 var indexNode = getIndexNodeForAccessExpression(accessNode);
56591                 if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
56592                     error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
56593                 }
56594                 else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
56595                     error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
56596                 }
56597                 else {
56598                     error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
56599                 }
56600             }
56601             if (isTypeAny(indexType)) {
56602                 return indexType;
56603             }
56604             return undefined;
56605             function errorIfWritingToReadonlyIndex(indexInfo) {
56606                 if (indexInfo && indexInfo.isReadonly && accessExpression && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) {
56607                     error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
56608                 }
56609             }
56610         }
56611         function getIndexNodeForAccessExpression(accessNode) {
56612             return accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode.argumentExpression :
56613                 accessNode.kind === 189 /* IndexedAccessType */ ? accessNode.indexType :
56614                     accessNode.kind === 158 /* ComputedPropertyName */ ? accessNode.expression :
56615                         accessNode;
56616         }
56617         function isPatternLiteralPlaceholderType(type) {
56618             return templateConstraintType.types.indexOf(type) !== -1 || !!(type.flags & 1 /* Any */);
56619         }
56620         function isPatternLiteralType(type) {
56621             return !!(type.flags & 134217728 /* TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType);
56622         }
56623         function isGenericObjectType(type) {
56624             if (type.flags & 3145728 /* UnionOrIntersection */) {
56625                 if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) {
56626                     type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ |
56627                         (ts.some(type.types, isGenericObjectType) ? 8388608 /* IsGenericObjectType */ : 0);
56628                 }
56629                 return !!(type.objectFlags & 8388608 /* IsGenericObjectType */);
56630             }
56631             return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type) || isGenericTupleType(type);
56632         }
56633         function isGenericIndexType(type) {
56634             if (type.flags & 3145728 /* UnionOrIntersection */) {
56635                 if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) {
56636                     type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ |
56637                         (ts.some(type.types, isGenericIndexType) ? 33554432 /* IsGenericIndexType */ : 0);
56638                 }
56639                 return !!(type.objectFlags & 33554432 /* IsGenericIndexType */);
56640             }
56641             return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) && !isPatternLiteralType(type);
56642         }
56643         function isThisTypeParameter(type) {
56644             return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType);
56645         }
56646         function getSimplifiedType(type, writing) {
56647             return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) :
56648                 type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) :
56649                     type;
56650         }
56651         function distributeIndexOverObjectType(objectType, indexType, writing) {
56652             // (T | U)[K] -> T[K] | U[K] (reading)
56653             // (T | U)[K] -> T[K] & U[K] (writing)
56654             // (T & U)[K] -> T[K] & U[K]
56655             if (objectType.flags & 3145728 /* UnionOrIntersection */) {
56656                 var types = ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType), writing); });
56657                 return objectType.flags & 2097152 /* Intersection */ || writing ? getIntersectionType(types) : getUnionType(types);
56658             }
56659         }
56660         function distributeObjectOverIndexType(objectType, indexType, writing) {
56661             // T[A | B] -> T[A] | T[B] (reading)
56662             // T[A | B] -> T[A] & T[B] (writing)
56663             if (indexType.flags & 1048576 /* Union */) {
56664                 var types = ts.map(indexType.types, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t), writing); });
56665                 return writing ? getIntersectionType(types) : getUnionType(types);
56666             }
56667         }
56668         // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
56669         // the type itself if no transformation is possible. The writing flag indicates that the type is
56670         // the target of an assignment.
56671         function getSimplifiedIndexedAccessType(type, writing) {
56672             var cache = writing ? "simplifiedForWriting" : "simplifiedForReading";
56673             if (type[cache]) {
56674                 return type[cache] === circularConstraintType ? type : type[cache];
56675             }
56676             type[cache] = circularConstraintType;
56677             // We recursively simplify the object type as it may in turn be an indexed access type. For example, with
56678             // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
56679             var objectType = getSimplifiedType(type.objectType, writing);
56680             var indexType = getSimplifiedType(type.indexType, writing);
56681             // T[A | B] -> T[A] | T[B] (reading)
56682             // T[A | B] -> T[A] & T[B] (writing)
56683             var distributedOverIndex = distributeObjectOverIndexType(objectType, indexType, writing);
56684             if (distributedOverIndex) {
56685                 return type[cache] = distributedOverIndex;
56686             }
56687             // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again
56688             if (!(indexType.flags & 465829888 /* Instantiable */)) {
56689                 // (T | U)[K] -> T[K] | U[K] (reading)
56690                 // (T | U)[K] -> T[K] & U[K] (writing)
56691                 // (T & U)[K] -> T[K] & U[K]
56692                 var distributedOverObject = distributeIndexOverObjectType(objectType, indexType, writing);
56693                 if (distributedOverObject) {
56694                     return type[cache] = distributedOverObject;
56695                 }
56696             }
56697             // So ultimately (reading):
56698             // ((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]
56699             // A generic tuple type indexed by a number exists only when the index type doesn't select a
56700             // fixed element. We simplify to either the combined type of all elements (when the index type
56701             // the actual number type) or to the combined type of all non-fixed elements.
56702             if (isGenericTupleType(objectType) && indexType.flags & 296 /* NumberLike */) {
56703                 var elementType = getElementTypeOfSliceOfTupleType(objectType, indexType.flags & 8 /* Number */ ? 0 : objectType.target.fixedLength, /*endSkipCount*/ 0, writing);
56704                 if (elementType) {
56705                     return type[cache] = elementType;
56706                 }
56707             }
56708             // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
56709             // that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
56710             // construct the type Box<T[X]>.
56711             if (isGenericMappedType(objectType)) {
56712                 return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), function (t) { return getSimplifiedType(t, writing); });
56713             }
56714             return type[cache] = type;
56715         }
56716         function getSimplifiedConditionalType(type, writing) {
56717             var checkType = type.checkType;
56718             var extendsType = type.extendsType;
56719             var trueType = getTrueTypeFromConditionalType(type);
56720             var falseType = getFalseTypeFromConditionalType(type);
56721             // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
56722             if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
56723                 if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
56724                     return getSimplifiedType(trueType, writing);
56725                 }
56726                 else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
56727                     return neverType;
56728                 }
56729             }
56730             else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
56731                 if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
56732                     return neverType;
56733                 }
56734                 else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
56735                     return getSimplifiedType(falseType, writing);
56736                 }
56737             }
56738             return type;
56739         }
56740         /**
56741          * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
56742          */
56743         function isIntersectionEmpty(type1, type2) {
56744             return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
56745         }
56746         function substituteIndexedMappedType(objectType, index) {
56747             var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
56748             var templateMapper = combineTypeMappers(objectType.mapper, mapper);
56749             return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
56750         }
56751         function getIndexedAccessType(objectType, indexType, noUncheckedIndexedAccessCandidate, accessNode, aliasSymbol, aliasTypeArguments, accessFlags) {
56752             if (accessFlags === void 0) { accessFlags = 0 /* None */; }
56753             return getIndexedAccessTypeOrUndefined(objectType, indexType, noUncheckedIndexedAccessCandidate, accessNode, accessFlags, aliasSymbol, aliasTypeArguments) || (accessNode ? errorType : unknownType);
56754         }
56755         function indexTypeLessThan(indexType, limit) {
56756             return everyType(indexType, function (t) {
56757                 if (t.flags & 384 /* StringOrNumberLiteral */) {
56758                     var propName = getPropertyNameFromType(t);
56759                     if (isNumericLiteralName(propName)) {
56760                         var index = +propName;
56761                         return index >= 0 && index < limit;
56762                     }
56763                 }
56764                 return false;
56765             });
56766         }
56767         function getIndexedAccessTypeOrUndefined(objectType, indexType, noUncheckedIndexedAccessCandidate, accessNode, accessFlags, aliasSymbol, aliasTypeArguments) {
56768             if (accessFlags === void 0) { accessFlags = 0 /* None */; }
56769             if (objectType === wildcardType || indexType === wildcardType) {
56770                 return wildcardType;
56771             }
56772             var shouldIncludeUndefined = noUncheckedIndexedAccessCandidate ||
56773                 (!!compilerOptions.noUncheckedIndexedAccess &&
56774                     (accessFlags & (2 /* Writing */ | 16 /* ExpressionPosition */)) === 16 /* ExpressionPosition */);
56775             // If the object type has a string index signature and no other members we know that the result will
56776             // always be the type of that index signature and we can simplify accordingly.
56777             if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
56778                 indexType = stringType;
56779             }
56780             // If the index type is generic, or if the object type is generic and doesn't originate in an expression and
56781             // the operation isn't exclusively indexing the fixed (non-variadic) portion of a tuple type, we are performing
56782             // a higher-order index access where we cannot meaningfully access the properties of the object type. Note that
56783             // for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to
56784             // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved
56785             // eagerly using the constraint type of 'this' at the given location.
56786             if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 189 /* IndexedAccessType */ ?
56787                 isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) :
56788                 isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)))) {
56789                 if (objectType.flags & 3 /* AnyOrUnknown */) {
56790                     return objectType;
56791                 }
56792                 // Defer the operation by creating an indexed access type.
56793                 var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "") + getAliasId(aliasSymbol, aliasTypeArguments);
56794                 var type = indexedAccessTypes.get(id);
56795                 if (!type) {
56796                     indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined));
56797                 }
56798                 return type;
56799             }
56800             // In the following we resolve T[K] to the type of the property in T selected by K.
56801             // We treat boolean as different from other unions to improve errors;
56802             // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'.
56803             var apparentObjectType = getReducedApparentType(objectType);
56804             if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
56805                 var propTypes = [];
56806                 var wasMissingProp = false;
56807                 for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) {
56808                     var t = _a[_i];
56809                     var propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, wasMissingProp, accessNode, accessFlags, shouldIncludeUndefined);
56810                     if (propType) {
56811                         propTypes.push(propType);
56812                     }
56813                     else if (!accessNode) {
56814                         // If there's no error node, we can immeditely stop, since error reporting is off
56815                         return undefined;
56816                     }
56817                     else {
56818                         // Otherwise we set a flag and return at the end of the loop so we still mark all errors
56819                         wasMissingProp = true;
56820                     }
56821                 }
56822                 if (wasMissingProp) {
56823                     return undefined;
56824                 }
56825                 return accessFlags & 2 /* Writing */
56826                     ? getIntersectionType(propTypes, aliasSymbol, aliasTypeArguments)
56827                     : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments);
56828             }
56829             return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, /* supressNoImplicitAnyError */ false, accessNode, accessFlags | 4 /* CacheSymbol */, shouldIncludeUndefined, /* reportDeprecated */ true);
56830         }
56831         function getTypeFromIndexedAccessTypeNode(node) {
56832             var links = getNodeLinks(node);
56833             if (!links.resolvedType) {
56834                 var objectType = getTypeFromTypeNode(node.objectType);
56835                 var indexType = getTypeFromTypeNode(node.indexType);
56836                 var potentialAlias = getAliasSymbolForTypeNode(node);
56837                 var resolved = getIndexedAccessType(objectType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias));
56838                 links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ &&
56839                     resolved.objectType === objectType &&
56840                     resolved.indexType === indexType ?
56841                     getConditionalFlowTypeOfType(resolved, node) : resolved;
56842             }
56843             return links.resolvedType;
56844         }
56845         function getTypeFromMappedTypeNode(node) {
56846             var links = getNodeLinks(node);
56847             if (!links.resolvedType) {
56848                 var type = createObjectType(32 /* Mapped */, node.symbol);
56849                 type.declaration = node;
56850                 type.aliasSymbol = getAliasSymbolForTypeNode(node);
56851                 type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
56852                 links.resolvedType = type;
56853                 // Eagerly resolve the constraint type which forces an error if the constraint type circularly
56854                 // references itself through one or more type aliases.
56855                 getConstraintTypeFromMappedType(type);
56856             }
56857             return links.resolvedType;
56858         }
56859         function getActualTypeVariable(type) {
56860             if (type.flags & 33554432 /* Substitution */) {
56861                 return type.baseType;
56862             }
56863             if (type.flags & 8388608 /* IndexedAccess */ && (type.objectType.flags & 33554432 /* Substitution */ ||
56864                 type.indexType.flags & 33554432 /* Substitution */)) {
56865                 return getIndexedAccessType(getActualTypeVariable(type.objectType), getActualTypeVariable(type.indexType));
56866             }
56867             return type;
56868         }
56869         function isTypicalNondistributiveConditional(root) {
56870             return !root.isDistributive
56871                 && root.node.checkType.kind === 179 /* TupleType */
56872                 && ts.length(root.node.checkType.elements) === 1
56873                 && root.node.extendsType.kind === 179 /* TupleType */
56874                 && ts.length(root.node.extendsType.elements) === 1;
56875         }
56876         /**
56877          * We syntactually check for common nondistributive conditional shapes and unwrap them into
56878          * the intended comparison - we do this so we can check if the unwrapped types are generic or
56879          * not and appropriately defer condition calculation
56880          */
56881         function unwrapNondistributiveConditionalTuple(root, type) {
56882             return isTypicalNondistributiveConditional(root) && isTupleType(type) ? getTypeArguments(type)[0] : type;
56883         }
56884         function getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) {
56885             var result;
56886             var extraTypes;
56887             // We loop here for an immediately nested conditional type in the false position, effectively treating
56888             // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for
56889             // purposes of resolution. This means such types aren't subject to the instatiation depth limiter.
56890             while (true) {
56891                 var isUnwrapped = isTypicalNondistributiveConditional(root);
56892                 var checkType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.checkType), mapper);
56893                 var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType);
56894                 var extendsType = instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), mapper);
56895                 if (checkType === wildcardType || extendsType === wildcardType) {
56896                     return wildcardType;
56897                 }
56898                 var combinedMapper = void 0;
56899                 if (root.inferTypeParameters) {
56900                     var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
56901                     if (!checkTypeInstantiable) {
56902                         // We don't want inferences from constraints as they may cause us to eagerly resolve the
56903                         // conditional type instead of deferring resolution. Also, we always want strict function
56904                         // types rules (i.e. proper contravariance) for inferences.
56905                         inferTypes(context.inferences, checkType, extendsType, 256 /* NoConstraints */ | 512 /* AlwaysStrict */);
56906                     }
56907                     combinedMapper = mergeTypeMappers(mapper, context.mapper);
56908                 }
56909                 // Instantiate the extends type including inferences for 'infer T' type parameters
56910                 var inferredExtendsType = combinedMapper ? instantiateType(unwrapNondistributiveConditionalTuple(root, root.extendsType), combinedMapper) : extendsType;
56911                 // We attempt to resolve the conditional type only when the check and extends types are non-generic
56912                 if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) {
56913                     // Return falseType for a definitely false extends check. We check an instantiations of the two
56914                     // types with type parameters mapped to the wildcard type, the most permissive instantiations
56915                     // possible (the wildcard type is assignable to and from all types). If those are not related,
56916                     // then no instantiations will be and we can just return the false branch type.
56917                     if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && ((checkType.flags & 1 /* Any */ && !isUnwrapped) || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) {
56918                         // Return union of trueType and falseType for 'any' since it matches anything
56919                         if (checkType.flags & 1 /* Any */ && !isUnwrapped) {
56920                             (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper));
56921                         }
56922                         // If falseType is an immediately nested conditional type that isn't distributive or has an
56923                         // identical checkType, switch to that type and loop.
56924                         var falseType_1 = getTypeFromTypeNode(root.node.falseType);
56925                         if (falseType_1.flags & 16777216 /* Conditional */) {
56926                             var newRoot = falseType_1.root;
56927                             if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) {
56928                                 root = newRoot;
56929                                 continue;
56930                             }
56931                         }
56932                         result = instantiateType(falseType_1, mapper);
56933                         break;
56934                     }
56935                     // Return trueType for a definitely true extends check. We check instantiations of the two
56936                     // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
56937                     // that has no constraint. This ensures that, for example, the type
56938                     //   type Foo<T extends { x: any }> = T extends { x: string } ? string : number
56939                     // doesn't immediately resolve to 'string' instead of being deferred.
56940                     if (inferredExtendsType.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
56941                         result = instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper);
56942                         break;
56943                     }
56944                 }
56945                 // Return a deferred type for a check that is neither definitely true nor definitely false
56946                 result = createType(16777216 /* Conditional */);
56947                 result.root = root;
56948                 result.checkType = instantiateType(root.checkType, mapper);
56949                 result.extendsType = instantiateType(root.extendsType, mapper);
56950                 result.mapper = mapper;
56951                 result.combinedMapper = combinedMapper;
56952                 result.aliasSymbol = aliasSymbol || root.aliasSymbol;
56953                 result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
56954                 break;
56955             }
56956             return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result;
56957         }
56958         function getTrueTypeFromConditionalType(type) {
56959             return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(getTypeFromTypeNode(type.root.node.trueType), type.mapper));
56960         }
56961         function getFalseTypeFromConditionalType(type) {
56962             return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(getTypeFromTypeNode(type.root.node.falseType), type.mapper));
56963         }
56964         function getInferredTrueTypeFromConditionalType(type) {
56965             return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = type.combinedMapper ? instantiateType(getTypeFromTypeNode(type.root.node.trueType), type.combinedMapper) : getTrueTypeFromConditionalType(type));
56966         }
56967         function getInferTypeParameters(node) {
56968             var result;
56969             if (node.locals) {
56970                 node.locals.forEach(function (symbol) {
56971                     if (symbol.flags & 262144 /* TypeParameter */) {
56972                         result = ts.append(result, getDeclaredTypeOfSymbol(symbol));
56973                     }
56974                 });
56975             }
56976             return result;
56977         }
56978         function getTypeFromConditionalTypeNode(node) {
56979             var links = getNodeLinks(node);
56980             if (!links.resolvedType) {
56981                 var checkType = getTypeFromTypeNode(node.checkType);
56982                 var aliasSymbol = getAliasSymbolForTypeNode(node);
56983                 var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
56984                 var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
56985                 var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
56986                 var root = {
56987                     node: node,
56988                     checkType: checkType,
56989                     extendsType: getTypeFromTypeNode(node.extendsType),
56990                     isDistributive: !!(checkType.flags & 262144 /* TypeParameter */),
56991                     inferTypeParameters: getInferTypeParameters(node),
56992                     outerTypeParameters: outerTypeParameters,
56993                     instantiations: undefined,
56994                     aliasSymbol: aliasSymbol,
56995                     aliasTypeArguments: aliasTypeArguments
56996                 };
56997                 links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
56998                 if (outerTypeParameters) {
56999                     root.instantiations = new ts.Map();
57000                     root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
57001                 }
57002             }
57003             return links.resolvedType;
57004         }
57005         function getTypeFromInferTypeNode(node) {
57006             var links = getNodeLinks(node);
57007             if (!links.resolvedType) {
57008                 links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter));
57009             }
57010             return links.resolvedType;
57011         }
57012         function getIdentifierChain(node) {
57013             if (ts.isIdentifier(node)) {
57014                 return [node];
57015             }
57016             else {
57017                 return ts.append(getIdentifierChain(node.left), node.right);
57018             }
57019         }
57020         function getTypeFromImportTypeNode(node) {
57021             var links = getNodeLinks(node);
57022             if (!links.resolvedType) {
57023                 if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments
57024                     error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here);
57025                     links.resolvedSymbol = unknownSymbol;
57026                     return links.resolvedType = errorType;
57027                 }
57028                 if (!ts.isLiteralImportTypeNode(node)) {
57029                     error(node.argument, ts.Diagnostics.String_literal_expected);
57030                     links.resolvedSymbol = unknownSymbol;
57031                     return links.resolvedType = errorType;
57032                 }
57033                 var targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 4194304 /* JSDoc */ ? 111551 /* Value */ | 788968 /* Type */ : 788968 /* Type */;
57034                 // TODO: Future work: support unions/generics/whatever via a deferred import-type
57035                 var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
57036                 if (!innerModuleSymbol) {
57037                     links.resolvedSymbol = unknownSymbol;
57038                     return links.resolvedType = errorType;
57039                 }
57040                 var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false);
57041                 if (!ts.nodeIsMissing(node.qualifier)) {
57042                     var nameStack = getIdentifierChain(node.qualifier);
57043                     var currentNamespace = moduleSymbol;
57044                     var current = void 0;
57045                     while (current = nameStack.shift()) {
57046                         var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning;
57047                         // typeof a.b.c is normally resolved using `checkExpression` which in turn defers to `checkQualifiedName`
57048                         // That, in turn, ultimately uses `getPropertyOfType` on the type of the symbol, which differs slightly from
57049                         // the `exports` lookup process that only looks up namespace members which is used for most type references
57050                         var mergedResolvedSymbol = getMergedSymbol(resolveSymbol(currentNamespace));
57051                         var next = node.isTypeOf
57052                             ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText)
57053                             : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning);
57054                         if (!next) {
57055                             error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current));
57056                             return links.resolvedType = errorType;
57057                         }
57058                         getNodeLinks(current).resolvedSymbol = next;
57059                         getNodeLinks(current.parent).resolvedSymbol = next;
57060                         currentNamespace = next;
57061                     }
57062                     links.resolvedType = resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
57063                 }
57064                 else {
57065                     if (moduleSymbol.flags & targetMeaning) {
57066                         links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
57067                     }
57068                     else {
57069                         var errorMessage = targetMeaning === 111551 /* Value */
57070                             ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here
57071                             : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
57072                         error(node, errorMessage, node.argument.literal.text);
57073                         links.resolvedSymbol = unknownSymbol;
57074                         links.resolvedType = errorType;
57075                     }
57076                 }
57077             }
57078             return links.resolvedType;
57079         }
57080         function resolveImportSymbolType(node, links, symbol, meaning) {
57081             var resolvedSymbol = resolveSymbol(symbol);
57082             links.resolvedSymbol = resolvedSymbol;
57083             if (meaning === 111551 /* Value */) {
57084                 return getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias
57085             }
57086             else {
57087                 return getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol
57088             }
57089         }
57090         function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) {
57091             var links = getNodeLinks(node);
57092             if (!links.resolvedType) {
57093                 // Deferred resolution of members is handled by resolveObjectTypeMembers
57094                 var aliasSymbol = getAliasSymbolForTypeNode(node);
57095                 if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
57096                     links.resolvedType = emptyTypeLiteralType;
57097                 }
57098                 else {
57099                     var type = createObjectType(16 /* Anonymous */, node.symbol);
57100                     type.aliasSymbol = aliasSymbol;
57101                     type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
57102                     if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
57103                         type = createArrayType(type);
57104                     }
57105                     links.resolvedType = type;
57106                 }
57107             }
57108             return links.resolvedType;
57109         }
57110         function getAliasSymbolForTypeNode(node) {
57111             var host = node.parent;
57112             while (ts.isParenthesizedTypeNode(host) || ts.isJSDocTypeExpression(host) || ts.isTypeOperatorNode(host) && host.operator === 142 /* ReadonlyKeyword */) {
57113                 host = host.parent;
57114             }
57115             return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined;
57116         }
57117         function getTypeArgumentsForAliasSymbol(symbol) {
57118             return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
57119         }
57120         function isNonGenericObjectType(type) {
57121             return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type);
57122         }
57123         function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) {
57124             return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */));
57125         }
57126         function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) {
57127             if (ts.every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) {
57128                 return ts.find(type.types, isEmptyObjectType) || emptyObjectType;
57129             }
57130             var firstType = ts.find(type.types, function (t) { return !isEmptyObjectTypeOrSpreadsIntoEmptyObject(t); });
57131             if (!firstType) {
57132                 return undefined;
57133             }
57134             var secondType = firstType && ts.find(type.types, function (t) { return t !== firstType && !isEmptyObjectTypeOrSpreadsIntoEmptyObject(t); });
57135             if (secondType) {
57136                 return undefined;
57137             }
57138             return getAnonymousPartialType(firstType);
57139             function getAnonymousPartialType(type) {
57140                 // gets the type as if it had been spread, but where everything in the spread is made optional
57141                 var members = ts.createSymbolTable();
57142                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
57143                     var prop = _a[_i];
57144                     if (ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) {
57145                         // do nothing, skip privates
57146                     }
57147                     else if (isSpreadableProperty(prop)) {
57148                         var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
57149                         var flags = 4 /* Property */ | 16777216 /* Optional */;
57150                         var result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? 8 /* Readonly */ : 0));
57151                         result.type = isSetonlyAccessor ? undefinedType : getUnionType([getTypeOfSymbol(prop), undefinedType]);
57152                         result.declarations = prop.declarations;
57153                         result.nameType = getSymbolLinks(prop).nameType;
57154                         result.syntheticOrigin = prop;
57155                         members.set(prop.escapedName, result);
57156                     }
57157                 }
57158                 var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */));
57159                 spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
57160                 return spread;
57161             }
57162         }
57163         /**
57164          * Since the source of spread types are object literals, which are not binary,
57165          * this function should be called in a left folding style, with left = previous result of getSpreadType
57166          * and right = the new element to be spread.
57167          */
57168         function getSpreadType(left, right, symbol, objectFlags, readonly) {
57169             if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
57170                 return anyType;
57171             }
57172             if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) {
57173                 return unknownType;
57174             }
57175             if (left.flags & 131072 /* Never */) {
57176                 return right;
57177             }
57178             if (right.flags & 131072 /* Never */) {
57179                 return left;
57180             }
57181             if (left.flags & 1048576 /* Union */) {
57182                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly);
57183                 if (merged) {
57184                     return getSpreadType(merged, right, symbol, objectFlags, readonly);
57185                 }
57186                 return checkCrossProductUnion([left, right])
57187                     ? mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); })
57188                     : errorType;
57189             }
57190             if (right.flags & 1048576 /* Union */) {
57191                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly);
57192                 if (merged) {
57193                     return getSpreadType(left, merged, symbol, objectFlags, readonly);
57194                 }
57195                 return checkCrossProductUnion([left, right])
57196                     ? mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); })
57197                     : errorType;
57198             }
57199             if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
57200                 return left;
57201             }
57202             if (isGenericObjectType(left) || isGenericObjectType(right)) {
57203                 if (isEmptyObjectType(left)) {
57204                     return right;
57205                 }
57206                 // When the left type is an intersection, we may need to merge the last constituent of the
57207                 // intersection with the right type. For example when the left type is 'T & { a: string }'
57208                 // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'.
57209                 if (left.flags & 2097152 /* Intersection */) {
57210                     var types = left.types;
57211                     var lastLeft = types[types.length - 1];
57212                     if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
57213                         return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
57214                     }
57215                 }
57216                 return getIntersectionType([left, right]);
57217             }
57218             var members = ts.createSymbolTable();
57219             var skippedPrivateMembers = new ts.Set();
57220             var stringIndexInfo;
57221             var numberIndexInfo;
57222             if (left === emptyObjectType) {
57223                 // for the first spread element, left === emptyObjectType, so take the right's string indexer
57224                 stringIndexInfo = getIndexInfoOfType(right, 0 /* String */);
57225                 numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */);
57226             }
57227             else {
57228                 stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */));
57229                 numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */));
57230             }
57231             for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) {
57232                 var rightProp = _a[_i];
57233                 if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) {
57234                     skippedPrivateMembers.add(rightProp.escapedName);
57235                 }
57236                 else if (isSpreadableProperty(rightProp)) {
57237                     members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
57238                 }
57239             }
57240             for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
57241                 var leftProp = _c[_b];
57242                 if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) {
57243                     continue;
57244                 }
57245                 if (members.has(leftProp.escapedName)) {
57246                     var rightProp = members.get(leftProp.escapedName);
57247                     var rightType = getTypeOfSymbol(rightProp);
57248                     if (rightProp.flags & 16777216 /* Optional */) {
57249                         var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations);
57250                         var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */);
57251                         var result = createSymbol(flags, leftProp.escapedName);
57252                         result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]);
57253                         result.leftSpread = leftProp;
57254                         result.rightSpread = rightProp;
57255                         result.declarations = declarations;
57256                         result.nameType = getSymbolLinks(leftProp).nameType;
57257                         members.set(leftProp.escapedName, result);
57258                     }
57259                 }
57260                 else {
57261                     members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
57262                 }
57263             }
57264             var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
57265             spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
57266             return spread;
57267         }
57268         /** We approximate own properties as non-methods plus methods that are inside the object literal */
57269         function isSpreadableProperty(prop) {
57270             return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) &&
57271                 (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
57272                     !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }));
57273         }
57274         function getSpreadSymbol(prop, readonly) {
57275             var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
57276             if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
57277                 return prop;
57278             }
57279             var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
57280             var result = createSymbol(flags, prop.escapedName, getIsLateCheckFlag(prop) | (readonly ? 8 /* Readonly */ : 0));
57281             result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
57282             result.declarations = prop.declarations;
57283             result.nameType = getSymbolLinks(prop).nameType;
57284             result.syntheticOrigin = prop;
57285             return result;
57286         }
57287         function getIndexInfoWithReadonly(info, readonly) {
57288             return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
57289         }
57290         function createLiteralType(flags, value, symbol) {
57291             var type = createType(flags);
57292             type.symbol = symbol;
57293             type.value = value;
57294             return type;
57295         }
57296         function getFreshTypeOfLiteralType(type) {
57297             if (type.flags & 2944 /* Literal */) {
57298                 if (!type.freshType) {
57299                     var freshType = createLiteralType(type.flags, type.value, type.symbol);
57300                     freshType.regularType = type;
57301                     freshType.freshType = freshType;
57302                     type.freshType = freshType;
57303                 }
57304                 return type.freshType;
57305             }
57306             return type;
57307         }
57308         function getRegularTypeOfLiteralType(type) {
57309             return type.flags & 2944 /* Literal */ ? type.regularType :
57310                 type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = mapType(type, getRegularTypeOfLiteralType))) :
57311                     type;
57312         }
57313         function isFreshLiteralType(type) {
57314             return !!(type.flags & 2944 /* Literal */) && type.freshType === type;
57315         }
57316         function getLiteralType(value, enumId, symbol) {
57317             // We store all literal types in a single map with keys of the form '#NNN' and '@SSS',
57318             // where NNN is the text representation of a numeric literal and SSS are the characters
57319             // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where
57320             // EEE is a unique id for the containing enum type.
57321             var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n";
57322             var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value);
57323             var type = literalTypes.get(key);
57324             if (!type) {
57325                 var flags = (typeof value === "number" ? 256 /* NumberLiteral */ :
57326                     typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) |
57327                     (enumId ? 1024 /* EnumLiteral */ : 0);
57328                 literalTypes.set(key, type = createLiteralType(flags, value, symbol));
57329                 type.regularType = type;
57330             }
57331             return type;
57332         }
57333         function getTypeFromLiteralTypeNode(node) {
57334             if (node.literal.kind === 103 /* NullKeyword */) {
57335                 return nullType;
57336             }
57337             var links = getNodeLinks(node);
57338             if (!links.resolvedType) {
57339                 links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal));
57340             }
57341             return links.resolvedType;
57342         }
57343         function createUniqueESSymbolType(symbol) {
57344             var type = createType(8192 /* UniqueESSymbol */);
57345             type.symbol = symbol;
57346             type.escapedName = "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol);
57347             return type;
57348         }
57349         function getESSymbolLikeTypeForNode(node) {
57350             if (ts.isValidESSymbolDeclaration(node)) {
57351                 var symbol = getSymbolOfNode(node);
57352                 var links = getSymbolLinks(symbol);
57353                 return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol));
57354             }
57355             return esSymbolType;
57356         }
57357         function getThisType(node) {
57358             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
57359             var parent = container && container.parent;
57360             if (parent && (ts.isClassLike(parent) || parent.kind === 253 /* InterfaceDeclaration */)) {
57361                 if (!ts.hasSyntacticModifier(container, 32 /* Static */) &&
57362                     (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) {
57363                     return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
57364                 }
57365             }
57366             // inside x.prototype = { ... }
57367             if (parent && ts.isObjectLiteralExpression(parent) && ts.isBinaryExpression(parent.parent) && ts.getAssignmentDeclarationKind(parent.parent) === 6 /* Prototype */) {
57368                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent.parent.left).parent).thisType;
57369             }
57370             // /** @return {this} */
57371             // x.prototype.m = function() { ... }
57372             var host = node.flags & 4194304 /* JSDoc */ ? ts.getHostSignatureFromJSDoc(node) : undefined;
57373             if (host && ts.isFunctionExpression(host) && ts.isBinaryExpression(host.parent) && ts.getAssignmentDeclarationKind(host.parent) === 3 /* PrototypeProperty */) {
57374                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host.parent.left).parent).thisType;
57375             }
57376             // inside constructor function C() { ... }
57377             if (isJSConstructor(container) && ts.isNodeDescendantOf(node, container.body)) {
57378                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(container)).thisType;
57379             }
57380             error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
57381             return errorType;
57382         }
57383         function getTypeFromThisTypeNode(node) {
57384             var links = getNodeLinks(node);
57385             if (!links.resolvedType) {
57386                 links.resolvedType = getThisType(node);
57387             }
57388             return links.resolvedType;
57389         }
57390         function getTypeFromRestTypeNode(node) {
57391             return getTypeFromTypeNode(getArrayElementTypeNode(node.type) || node.type);
57392         }
57393         function getArrayElementTypeNode(node) {
57394             switch (node.kind) {
57395                 case 186 /* ParenthesizedType */:
57396                     return getArrayElementTypeNode(node.type);
57397                 case 179 /* TupleType */:
57398                     if (node.elements.length === 1) {
57399                         node = node.elements[0];
57400                         if (node.kind === 181 /* RestType */ || node.kind === 192 /* NamedTupleMember */ && node.dotDotDotToken) {
57401                             return getArrayElementTypeNode(node.type);
57402                         }
57403                     }
57404                     break;
57405                 case 178 /* ArrayType */:
57406                     return node.elementType;
57407             }
57408             return undefined;
57409         }
57410         function getTypeFromNamedTupleTypeNode(node) {
57411             var links = getNodeLinks(node);
57412             return links.resolvedType || (links.resolvedType =
57413                 node.dotDotDotToken ? getTypeFromRestTypeNode(node) :
57414                     node.questionToken && strictNullChecks ? getOptionalType(getTypeFromTypeNode(node.type)) :
57415                         getTypeFromTypeNode(node.type));
57416         }
57417         function getTypeFromTypeNode(node) {
57418             return getConditionalFlowTypeOfType(getTypeFromTypeNodeWorker(node), node);
57419         }
57420         function getTypeFromTypeNodeWorker(node) {
57421             switch (node.kind) {
57422                 case 128 /* AnyKeyword */:
57423                 case 303 /* JSDocAllType */:
57424                 case 304 /* JSDocUnknownType */:
57425                     return anyType;
57426                 case 152 /* UnknownKeyword */:
57427                     return unknownType;
57428                 case 147 /* StringKeyword */:
57429                     return stringType;
57430                 case 144 /* NumberKeyword */:
57431                     return numberType;
57432                 case 155 /* BigIntKeyword */:
57433                     return bigintType;
57434                 case 131 /* BooleanKeyword */:
57435                     return booleanType;
57436                 case 148 /* SymbolKeyword */:
57437                     return esSymbolType;
57438                 case 113 /* VoidKeyword */:
57439                     return voidType;
57440                 case 150 /* UndefinedKeyword */:
57441                     return undefinedType;
57442                 case 103 /* NullKeyword */:
57443                     // TODO(rbuckton): `NullKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service.
57444                     return nullType;
57445                 case 141 /* NeverKeyword */:
57446                     return neverType;
57447                 case 145 /* ObjectKeyword */:
57448                     return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType;
57449                 case 136 /* IntrinsicKeyword */:
57450                     return intrinsicMarkerType;
57451                 case 187 /* ThisType */:
57452                 case 107 /* ThisKeyword */:
57453                     // 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`.
57454                     return getTypeFromThisTypeNode(node);
57455                 case 191 /* LiteralType */:
57456                     return getTypeFromLiteralTypeNode(node);
57457                 case 173 /* TypeReference */:
57458                     return getTypeFromTypeReference(node);
57459                 case 172 /* TypePredicate */:
57460                     return node.assertsModifier ? voidType : booleanType;
57461                 case 223 /* ExpressionWithTypeArguments */:
57462                     return getTypeFromTypeReference(node);
57463                 case 176 /* TypeQuery */:
57464                     return getTypeFromTypeQueryNode(node);
57465                 case 178 /* ArrayType */:
57466                 case 179 /* TupleType */:
57467                     return getTypeFromArrayOrTupleTypeNode(node);
57468                 case 180 /* OptionalType */:
57469                     return getTypeFromOptionalTypeNode(node);
57470                 case 182 /* UnionType */:
57471                     return getTypeFromUnionTypeNode(node);
57472                 case 183 /* IntersectionType */:
57473                     return getTypeFromIntersectionTypeNode(node);
57474                 case 305 /* JSDocNullableType */:
57475                     return getTypeFromJSDocNullableTypeNode(node);
57476                 case 307 /* JSDocOptionalType */:
57477                     return addOptionality(getTypeFromTypeNode(node.type));
57478                 case 192 /* NamedTupleMember */:
57479                     return getTypeFromNamedTupleTypeNode(node);
57480                 case 186 /* ParenthesizedType */:
57481                 case 306 /* JSDocNonNullableType */:
57482                 case 301 /* JSDocTypeExpression */:
57483                     return getTypeFromTypeNode(node.type);
57484                 case 181 /* RestType */:
57485                     return getTypeFromRestTypeNode(node);
57486                 case 309 /* JSDocVariadicType */:
57487                     return getTypeFromJSDocVariadicType(node);
57488                 case 174 /* FunctionType */:
57489                 case 175 /* ConstructorType */:
57490                 case 177 /* TypeLiteral */:
57491                 case 312 /* JSDocTypeLiteral */:
57492                 case 308 /* JSDocFunctionType */:
57493                 case 313 /* JSDocSignature */:
57494                     return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
57495                 case 188 /* TypeOperator */:
57496                     return getTypeFromTypeOperatorNode(node);
57497                 case 189 /* IndexedAccessType */:
57498                     return getTypeFromIndexedAccessTypeNode(node);
57499                 case 190 /* MappedType */:
57500                     return getTypeFromMappedTypeNode(node);
57501                 case 184 /* ConditionalType */:
57502                     return getTypeFromConditionalTypeNode(node);
57503                 case 185 /* InferType */:
57504                     return getTypeFromInferTypeNode(node);
57505                 case 193 /* TemplateLiteralType */:
57506                     return getTypeFromTemplateTypeNode(node);
57507                 case 195 /* ImportType */:
57508                     return getTypeFromImportTypeNode(node);
57509                 // This function assumes that an identifier, qualified name, or property access expression is a type expression
57510                 // Callers should first ensure this by calling `isPartOfTypeNode`
57511                 // 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.
57512                 case 78 /* Identifier */:
57513                 case 157 /* QualifiedName */:
57514                 case 201 /* PropertyAccessExpression */:
57515                     var symbol = getSymbolAtLocation(node);
57516                     return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
57517                 default:
57518                     return errorType;
57519             }
57520         }
57521         function instantiateList(items, mapper, instantiator) {
57522             if (items && items.length) {
57523                 for (var i = 0; i < items.length; i++) {
57524                     var item = items[i];
57525                     var mapped = instantiator(item, mapper);
57526                     if (item !== mapped) {
57527                         var result = i === 0 ? [] : items.slice(0, i);
57528                         result.push(mapped);
57529                         for (i++; i < items.length; i++) {
57530                             result.push(instantiator(items[i], mapper));
57531                         }
57532                         return result;
57533                     }
57534                 }
57535             }
57536             return items;
57537         }
57538         function instantiateTypes(types, mapper) {
57539             return instantiateList(types, mapper, instantiateType);
57540         }
57541         function instantiateSignatures(signatures, mapper) {
57542             return instantiateList(signatures, mapper, instantiateSignature);
57543         }
57544         function createTypeMapper(sources, targets) {
57545             return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : makeArrayTypeMapper(sources, targets);
57546         }
57547         function getMappedType(type, mapper) {
57548             switch (mapper.kind) {
57549                 case 0 /* Simple */:
57550                     return type === mapper.source ? mapper.target : type;
57551                 case 1 /* Array */:
57552                     var sources = mapper.sources;
57553                     var targets = mapper.targets;
57554                     for (var i = 0; i < sources.length; i++) {
57555                         if (type === sources[i]) {
57556                             return targets ? targets[i] : anyType;
57557                         }
57558                     }
57559                     return type;
57560                 case 2 /* Function */:
57561                     return mapper.func(type);
57562                 case 3 /* Composite */:
57563                 case 4 /* Merged */:
57564                     var t1 = getMappedType(type, mapper.mapper1);
57565                     return t1 !== type && mapper.kind === 3 /* Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2);
57566             }
57567         }
57568         function makeUnaryTypeMapper(source, target) {
57569             return { kind: 0 /* Simple */, source: source, target: target };
57570         }
57571         function makeArrayTypeMapper(sources, targets) {
57572             return { kind: 1 /* Array */, sources: sources, targets: targets };
57573         }
57574         function makeFunctionTypeMapper(func) {
57575             return { kind: 2 /* Function */, func: func };
57576         }
57577         function makeCompositeTypeMapper(kind, mapper1, mapper2) {
57578             return { kind: kind, mapper1: mapper1, mapper2: mapper2 };
57579         }
57580         function createTypeEraser(sources) {
57581             return createTypeMapper(sources, /*targets*/ undefined);
57582         }
57583         /**
57584          * Maps forward-references to later types parameters to the empty object type.
57585          * This is used during inference when instantiating type parameter defaults.
57586          */
57587         function createBackreferenceMapper(context, index) {
57588             return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; });
57589         }
57590         function combineTypeMappers(mapper1, mapper2) {
57591             return mapper1 ? makeCompositeTypeMapper(3 /* Composite */, mapper1, mapper2) : mapper2;
57592         }
57593         function mergeTypeMappers(mapper1, mapper2) {
57594             return mapper1 ? makeCompositeTypeMapper(4 /* Merged */, mapper1, mapper2) : mapper2;
57595         }
57596         function prependTypeMapping(source, target, mapper) {
57597             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, makeUnaryTypeMapper(source, target), mapper);
57598         }
57599         function appendTypeMapping(mapper, source, target) {
57600             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, mapper, makeUnaryTypeMapper(source, target));
57601         }
57602         function getRestrictiveTypeParameter(tp) {
57603             return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol),
57604                 tp.restrictiveInstantiation.constraint = unknownType,
57605                 tp.restrictiveInstantiation);
57606         }
57607         function cloneTypeParameter(typeParameter) {
57608             var result = createTypeParameter(typeParameter.symbol);
57609             result.target = typeParameter;
57610             return result;
57611         }
57612         function instantiateTypePredicate(predicate, mapper) {
57613             return createTypePredicate(predicate.kind, predicate.parameterName, predicate.parameterIndex, instantiateType(predicate.type, mapper));
57614         }
57615         function instantiateSignature(signature, mapper, eraseTypeParameters) {
57616             var freshTypeParameters;
57617             if (signature.typeParameters && !eraseTypeParameters) {
57618                 // First create a fresh set of type parameters, then include a mapping from the old to the
57619                 // new type parameters in the mapper function. Finally store this mapper in the new type
57620                 // parameters such that we can use it when instantiating constraints.
57621                 freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter);
57622                 mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper);
57623                 for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) {
57624                     var tp = freshTypeParameters_1[_i];
57625                     tp.mapper = mapper;
57626                 }
57627             }
57628             // Don't compute resolvedReturnType and resolvedTypePredicate now,
57629             // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.)
57630             // See GH#17600.
57631             var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), 
57632             /*resolvedReturnType*/ undefined, 
57633             /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 39 /* PropagatingFlags */);
57634             result.target = signature;
57635             result.mapper = mapper;
57636             return result;
57637         }
57638         function instantiateSymbol(symbol, mapper) {
57639             var links = getSymbolLinks(symbol);
57640             if (links.type && !couldContainTypeVariables(links.type)) {
57641                 // If the type of the symbol is already resolved, and if that type could not possibly
57642                 // be affected by instantiation, simply return the symbol itself.
57643                 return symbol;
57644             }
57645             if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
57646                 // If symbol being instantiated is itself a instantiation, fetch the original target and combine the
57647                 // type mappers. This ensures that original type identities are properly preserved and that aliases
57648                 // always reference a non-aliases.
57649                 symbol = links.target;
57650                 mapper = combineTypeMappers(links.mapper, mapper);
57651             }
57652             // Keep the flags from the symbol we're instantiating.  Mark that is instantiated, and
57653             // also transient so that we can just store data on it directly.
57654             var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 4096 /* Late */ | 16384 /* OptionalParameter */ | 32768 /* RestParameter */));
57655             result.declarations = symbol.declarations;
57656             result.parent = symbol.parent;
57657             result.target = symbol;
57658             result.mapper = mapper;
57659             if (symbol.valueDeclaration) {
57660                 result.valueDeclaration = symbol.valueDeclaration;
57661             }
57662             if (links.nameType) {
57663                 result.nameType = links.nameType;
57664             }
57665             return result;
57666         }
57667         function getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) {
57668             var declaration = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0];
57669             var links = getNodeLinks(declaration);
57670             var target = type.objectFlags & 4 /* Reference */ ? links.resolvedType :
57671                 type.objectFlags & 64 /* Instantiated */ ? type.target : type;
57672             var typeParameters = links.outerTypeParameters;
57673             if (!typeParameters) {
57674                 // The first time an anonymous type is instantiated we compute and store a list of the type
57675                 // parameters that are in scope (and therefore potentially referenced). For type literals that
57676                 // aren't the right hand side of a generic type alias declaration we optimize by reducing the
57677                 // set of type parameters to those that are possibly referenced in the literal.
57678                 var outerTypeParameters = getOuterTypeParameters(declaration, /*includeThisTypes*/ true);
57679                 if (isJSConstructor(declaration)) {
57680                     var templateTagParameters = getTypeParametersFromDeclaration(declaration);
57681                     outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters);
57682                 }
57683                 typeParameters = outerTypeParameters || ts.emptyArray;
57684                 typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ?
57685                     ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) :
57686                     typeParameters;
57687                 links.outerTypeParameters = typeParameters;
57688             }
57689             if (typeParameters.length) {
57690                 // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the
57691                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
57692                 // instantiation cache key from the type IDs of the type arguments.
57693                 var combinedMapper_1 = combineTypeMappers(type.mapper, mapper);
57694                 var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); });
57695                 var newAliasSymbol = aliasSymbol || type.aliasSymbol;
57696                 var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
57697                 var id = getTypeListId(typeArguments) + getAliasId(newAliasSymbol, newAliasTypeArguments);
57698                 if (!target.instantiations) {
57699                     target.instantiations = new ts.Map();
57700                     target.instantiations.set(getTypeListId(typeParameters) + getAliasId(target.aliasSymbol, target.aliasTypeArguments), target);
57701                 }
57702                 var result = target.instantiations.get(id);
57703                 if (!result) {
57704                     var newMapper = createTypeMapper(typeParameters, typeArguments);
57705                     result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper, newAliasSymbol, newAliasTypeArguments) :
57706                         target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper, newAliasSymbol, newAliasTypeArguments) :
57707                             instantiateAnonymousType(target, newMapper, newAliasSymbol, newAliasTypeArguments);
57708                     target.instantiations.set(id, result);
57709                 }
57710                 return result;
57711             }
57712             return type;
57713         }
57714         function maybeTypeParameterReference(node) {
57715             return !(node.kind === 157 /* QualifiedName */ ||
57716                 node.parent.kind === 173 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName ||
57717                 node.parent.kind === 195 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier);
57718         }
57719         function isTypeParameterPossiblyReferenced(tp, node) {
57720             // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks
57721             // between the node and the type parameter declaration, if the node contains actual references to the
57722             // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
57723             if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
57724                 var container = tp.symbol.declarations[0].parent;
57725                 for (var n = node; n !== container; n = n.parent) {
57726                     if (!n || n.kind === 230 /* Block */ || n.kind === 184 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) {
57727                         return true;
57728                     }
57729                 }
57730                 return !!ts.forEachChild(node, containsReference);
57731             }
57732             return true;
57733             function containsReference(node) {
57734                 switch (node.kind) {
57735                     case 187 /* ThisType */:
57736                         return !!tp.isThisType;
57737                     case 78 /* Identifier */:
57738                         return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) &&
57739                             getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality
57740                     case 176 /* TypeQuery */:
57741                         return true;
57742                 }
57743                 return !!ts.forEachChild(node, containsReference);
57744             }
57745         }
57746         function getHomomorphicTypeVariable(type) {
57747             var constraintType = getConstraintTypeFromMappedType(type);
57748             if (constraintType.flags & 4194304 /* Index */) {
57749                 var typeVariable = getActualTypeVariable(constraintType.type);
57750                 if (typeVariable.flags & 262144 /* TypeParameter */) {
57751                     return typeVariable;
57752                 }
57753             }
57754             return undefined;
57755         }
57756         function instantiateMappedType(type, mapper, aliasSymbol, aliasTypeArguments) {
57757             // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
57758             // operation depends on T as follows:
57759             // * If T is a primitive type no mapping is performed and the result is simply T.
57760             // * If T is a union type we distribute the mapped type over the union.
57761             // * If T is an array we map to an array where the element type has been transformed.
57762             // * If T is a tuple we map to a tuple where the element types have been transformed.
57763             // * Otherwise we map to an object type where the type of each property has been transformed.
57764             // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } |
57765             // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce
57766             // { [P in keyof A]: X } | undefined.
57767             var typeVariable = getHomomorphicTypeVariable(type);
57768             if (typeVariable) {
57769                 var mappedTypeVariable = instantiateType(typeVariable, mapper);
57770                 if (typeVariable !== mappedTypeVariable) {
57771                     return mapTypeWithAlias(getReducedType(mappedTypeVariable), function (t) {
57772                         if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
57773                             if (!type.declaration.nameType) {
57774                                 if (isArrayType(t)) {
57775                                     return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper));
57776                                 }
57777                                 if (isGenericTupleType(t)) {
57778                                     return instantiateMappedGenericTupleType(t, type, typeVariable, mapper);
57779                                 }
57780                                 if (isTupleType(t)) {
57781                                     return instantiateMappedTupleType(t, type, prependTypeMapping(typeVariable, t, mapper));
57782                                 }
57783                             }
57784                             return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper));
57785                         }
57786                         return t;
57787                     }, aliasSymbol, aliasTypeArguments);
57788                 }
57789             }
57790             // If the constraint type of the instantiation is the wildcard type, return the wildcard type.
57791             return instantiateType(getConstraintTypeFromMappedType(type), mapper) === wildcardType ? wildcardType : instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments);
57792         }
57793         function getModifiedReadonlyState(state, modifiers) {
57794             return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
57795         }
57796         function instantiateMappedGenericTupleType(tupleType, mappedType, typeVariable, mapper) {
57797             // When a tuple type is generic (i.e. when it contains variadic elements), we want to eagerly map the
57798             // non-generic elements and defer mapping the generic elements. In order to facilitate this, we transform
57799             // M<[A, B?, ...T, ...C[]] into [...M<[A]>, ...M<[B?]>, ...M<T>, ...M<C[]>] and then rely on tuple type
57800             // normalization to resolve the non-generic parts of the resulting tuple.
57801             var elementFlags = tupleType.target.elementFlags;
57802             var elementTypes = ts.map(getTypeArguments(tupleType), function (t, i) {
57803                 var singleton = elementFlags[i] & 8 /* Variadic */ ? t :
57804                     elementFlags[i] & 4 /* Rest */ ? createArrayType(t) :
57805                         createTupleType([t], [elementFlags[i]]);
57806                 // The singleton is never a generic tuple type, so it is safe to recurse here.
57807                 return instantiateMappedType(mappedType, prependTypeMapping(typeVariable, singleton, mapper));
57808             });
57809             var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, getMappedTypeModifiers(mappedType));
57810             return createTupleType(elementTypes, ts.map(elementTypes, function (_) { return 8 /* Variadic */; }), newReadonly);
57811         }
57812         function instantiateMappedArrayType(arrayType, mappedType, mapper) {
57813             var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
57814             return elementType === errorType ? errorType :
57815                 createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
57816         }
57817         function instantiateMappedTupleType(tupleType, mappedType, mapper) {
57818             var elementFlags = tupleType.target.elementFlags;
57819             var elementTypes = ts.map(getTypeArguments(tupleType), function (_, i) {
57820                 return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */), mapper);
57821             });
57822             var modifiers = getMappedTypeModifiers(mappedType);
57823             var newTupleModifiers = modifiers & 4 /* IncludeOptional */ ? ts.map(elementFlags, function (f) { return f & 1 /* Required */ ? 2 /* Optional */ : f; }) :
57824                 modifiers & 8 /* ExcludeOptional */ ? ts.map(elementFlags, function (f) { return f & 2 /* Optional */ ? 1 /* Required */ : f; }) :
57825                     elementFlags;
57826             var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
57827             return ts.contains(elementTypes, errorType) ? errorType :
57828                 createTupleType(elementTypes, newTupleModifiers, newReadonly, tupleType.target.labeledElementDeclarations);
57829         }
57830         function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
57831             var templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key);
57832             var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper);
57833             var modifiers = getMappedTypeModifiers(type);
57834             return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
57835                 strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
57836                     propType;
57837         }
57838         function instantiateAnonymousType(type, mapper, aliasSymbol, aliasTypeArguments) {
57839             var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol);
57840             if (type.objectFlags & 32 /* Mapped */) {
57841                 result.declaration = type.declaration;
57842                 // C.f. instantiateSignature
57843                 var origTypeParameter = getTypeParameterFromMappedType(type);
57844                 var freshTypeParameter = cloneTypeParameter(origTypeParameter);
57845                 result.typeParameter = freshTypeParameter;
57846                 mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper);
57847                 freshTypeParameter.mapper = mapper;
57848             }
57849             result.target = type;
57850             result.mapper = mapper;
57851             result.aliasSymbol = aliasSymbol || type.aliasSymbol;
57852             result.aliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
57853             return result;
57854         }
57855         function getConditionalTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments) {
57856             var root = type.root;
57857             if (root.outerTypeParameters) {
57858                 // We are instantiating a conditional type that has one or more type parameters in scope. Apply the
57859                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
57860                 // instantiation cache key from the type IDs of the type arguments.
57861                 var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); });
57862                 var id = getTypeListId(typeArguments) + getAliasId(aliasSymbol, aliasTypeArguments);
57863                 var result = root.instantiations.get(id);
57864                 if (!result) {
57865                     var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
57866                     result = instantiateConditionalType(root, newMapper, aliasSymbol, aliasTypeArguments);
57867                     root.instantiations.set(id, result);
57868                 }
57869                 return result;
57870             }
57871             return type;
57872         }
57873         function instantiateConditionalType(root, mapper, aliasSymbol, aliasTypeArguments) {
57874             // Check if we have a conditional type where the check type is a naked type parameter. If so,
57875             // the conditional type is distributive over union types and when T is instantiated to a union
57876             // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y).
57877             if (root.isDistributive) {
57878                 var checkType_1 = root.checkType;
57879                 var instantiatedType = getMappedType(checkType_1, mapper);
57880                 if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) {
57881                     return mapTypeWithAlias(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); }, aliasSymbol, aliasTypeArguments);
57882                 }
57883             }
57884             return getConditionalType(root, mapper, aliasSymbol, aliasTypeArguments);
57885         }
57886         function instantiateType(type, mapper) {
57887             return type && mapper ? instantiateTypeWithAlias(type, mapper, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined) : type;
57888         }
57889         function instantiateTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) {
57890             if (!couldContainTypeVariables(type)) {
57891                 return type;
57892             }
57893             if (instantiationDepth === 50 || instantiationCount >= 5000000) {
57894                 // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
57895                 // with a combination of infinite generic types that perpetually generate new type identities. We stop
57896                 // the recursion here by yielding the error type.
57897                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount });
57898                 error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
57899                 return errorType;
57900             }
57901             totalInstantiationCount++;
57902             instantiationCount++;
57903             instantiationDepth++;
57904             var result = instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments);
57905             instantiationDepth--;
57906             return result;
57907         }
57908         function instantiateTypeWorker(type, mapper, aliasSymbol, aliasTypeArguments) {
57909             var flags = type.flags;
57910             if (flags & 262144 /* TypeParameter */) {
57911                 return getMappedType(type, mapper);
57912             }
57913             if (flags & 524288 /* Object */) {
57914                 var objectFlags = type.objectFlags;
57915                 if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) {
57916                     if (objectFlags & 4 /* Reference */ && !type.node) {
57917                         var resolvedTypeArguments = type.resolvedTypeArguments;
57918                         var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper);
57919                         return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type;
57920                     }
57921                     return getObjectTypeInstantiation(type, mapper, aliasSymbol, aliasTypeArguments);
57922                 }
57923                 return type;
57924             }
57925             if (flags & 3145728 /* UnionOrIntersection */) {
57926                 var origin = type.flags & 1048576 /* Union */ ? type.origin : undefined;
57927                 var types = origin && origin.flags & 3145728 /* UnionOrIntersection */ ? origin.types : type.types;
57928                 var newTypes = instantiateTypes(types, mapper);
57929                 if (newTypes === types && aliasSymbol === type.aliasSymbol) {
57930                     return type;
57931                 }
57932                 var newAliasSymbol = aliasSymbol || type.aliasSymbol;
57933                 var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
57934                 return flags & 2097152 /* Intersection */ || origin && origin.flags & 2097152 /* Intersection */ ?
57935                     getIntersectionType(newTypes, newAliasSymbol, newAliasTypeArguments) :
57936                     getUnionType(newTypes, 1 /* Literal */, newAliasSymbol, newAliasTypeArguments);
57937             }
57938             if (flags & 4194304 /* Index */) {
57939                 return getIndexType(instantiateType(type.type, mapper));
57940             }
57941             if (flags & 134217728 /* TemplateLiteral */) {
57942                 return getTemplateLiteralType(type.texts, instantiateTypes(type.types, mapper));
57943             }
57944             if (flags & 268435456 /* StringMapping */) {
57945                 return getStringMappingType(type.symbol, instantiateType(type.type, mapper));
57946             }
57947             if (flags & 8388608 /* IndexedAccess */) {
57948                 var newAliasSymbol = aliasSymbol || type.aliasSymbol;
57949                 var newAliasTypeArguments = aliasSymbol ? aliasTypeArguments : instantiateTypes(type.aliasTypeArguments, mapper);
57950                 return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, newAliasSymbol, newAliasTypeArguments);
57951             }
57952             if (flags & 16777216 /* Conditional */) {
57953                 return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper), aliasSymbol, aliasTypeArguments);
57954             }
57955             if (flags & 33554432 /* Substitution */) {
57956                 var maybeVariable = instantiateType(type.baseType, mapper);
57957                 if (maybeVariable.flags & 8650752 /* TypeVariable */) {
57958                     return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
57959                 }
57960                 else {
57961                     var sub = instantiateType(type.substitute, mapper);
57962                     if (sub.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
57963                         return maybeVariable;
57964                     }
57965                     return sub;
57966                 }
57967             }
57968             return type;
57969         }
57970         function getPermissiveInstantiation(type) {
57971             return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
57972                 type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
57973         }
57974         function getRestrictiveInstantiation(type) {
57975             if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
57976                 return type;
57977             }
57978             if (type.restrictiveInstantiation) {
57979                 return type.restrictiveInstantiation;
57980             }
57981             type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
57982             // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
57983             // which is redundant - we'll produce new type identities, but all type params have already been mapped.
57984             // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
57985             // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
57986             // are constrained to `unknown` and produce tons of false positives/negatives!
57987             type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
57988             return type.restrictiveInstantiation;
57989         }
57990         function instantiateIndexInfo(info, mapper) {
57991             return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
57992         }
57993         // Returns true if the given expression contains (at any level of nesting) a function or arrow expression
57994         // that is subject to contextual typing.
57995         function isContextSensitive(node) {
57996             ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
57997             switch (node.kind) {
57998                 case 208 /* FunctionExpression */:
57999                 case 209 /* ArrowFunction */:
58000                 case 165 /* MethodDeclaration */:
58001                 case 251 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type
58002                     return isContextSensitiveFunctionLikeDeclaration(node);
58003                 case 200 /* ObjectLiteralExpression */:
58004                     return ts.some(node.properties, isContextSensitive);
58005                 case 199 /* ArrayLiteralExpression */:
58006                     return ts.some(node.elements, isContextSensitive);
58007                 case 217 /* ConditionalExpression */:
58008                     return isContextSensitive(node.whenTrue) ||
58009                         isContextSensitive(node.whenFalse);
58010                 case 216 /* BinaryExpression */:
58011                     return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
58012                         (isContextSensitive(node.left) || isContextSensitive(node.right));
58013                 case 288 /* PropertyAssignment */:
58014                     return isContextSensitive(node.initializer);
58015                 case 207 /* ParenthesizedExpression */:
58016                     return isContextSensitive(node.expression);
58017                 case 281 /* JsxAttributes */:
58018                     return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive);
58019                 case 280 /* JsxAttribute */: {
58020                     // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive.
58021                     var initializer = node.initializer;
58022                     return !!initializer && isContextSensitive(initializer);
58023                 }
58024                 case 283 /* JsxExpression */: {
58025                     // It is possible to that node.expression is undefined (e.g <div x={} />)
58026                     var expression = node.expression;
58027                     return !!expression && isContextSensitive(expression);
58028                 }
58029             }
58030             return false;
58031         }
58032         function isContextSensitiveFunctionLikeDeclaration(node) {
58033             return (!ts.isFunctionDeclaration(node) || ts.isInJSFile(node) && !!getTypeForDeclarationFromJSDocComment(node)) &&
58034                 (hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node));
58035         }
58036         function hasContextSensitiveParameters(node) {
58037             // Functions with type parameters are not context sensitive.
58038             if (!node.typeParameters) {
58039                 // Functions with any parameters that lack type annotations are context sensitive.
58040                 if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) {
58041                     return true;
58042                 }
58043                 if (node.kind !== 209 /* ArrowFunction */) {
58044                     // If the first parameter is not an explicit 'this' parameter, then the function has
58045                     // an implicit 'this' parameter which is subject to contextual typing.
58046                     var parameter = ts.firstOrUndefined(node.parameters);
58047                     if (!(parameter && ts.parameterIsThisKeyword(parameter))) {
58048                         return true;
58049                     }
58050                 }
58051             }
58052             return false;
58053         }
58054         function hasContextSensitiveReturnExpression(node) {
58055             // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value.
58056             return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 230 /* Block */ && isContextSensitive(node.body);
58057         }
58058         function isContextSensitiveFunctionOrObjectLiteralMethod(func) {
58059             return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) &&
58060                 isContextSensitiveFunctionLikeDeclaration(func);
58061         }
58062         function getTypeWithoutSignatures(type) {
58063             if (type.flags & 524288 /* Object */) {
58064                 var resolved = resolveStructuredTypeMembers(type);
58065                 if (resolved.constructSignatures.length || resolved.callSignatures.length) {
58066                     var result = createObjectType(16 /* Anonymous */, type.symbol);
58067                     result.members = resolved.members;
58068                     result.properties = resolved.properties;
58069                     result.callSignatures = ts.emptyArray;
58070                     result.constructSignatures = ts.emptyArray;
58071                     return result;
58072                 }
58073             }
58074             else if (type.flags & 2097152 /* Intersection */) {
58075                 return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures));
58076             }
58077             return type;
58078         }
58079         // TYPE CHECKING
58080         function isTypeIdenticalTo(source, target) {
58081             return isTypeRelatedTo(source, target, identityRelation);
58082         }
58083         function compareTypesIdentical(source, target) {
58084             return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */;
58085         }
58086         function compareTypesAssignable(source, target) {
58087             return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */;
58088         }
58089         function compareTypesSubtypeOf(source, target) {
58090             return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */;
58091         }
58092         function isTypeSubtypeOf(source, target) {
58093             return isTypeRelatedTo(source, target, subtypeRelation);
58094         }
58095         function isTypeAssignableTo(source, target) {
58096             return isTypeRelatedTo(source, target, assignableRelation);
58097         }
58098         // An object type S is considered to be derived from an object type T if
58099         // S is a union type and every constituent of S is derived from T,
58100         // T is a union type and S is derived from at least one constituent of T, or
58101         // S is a type variable with a base constraint that is derived from T,
58102         // T is one of the global types Object and Function and S is a subtype of T, or
58103         // T occurs directly or indirectly in an 'extends' clause of S.
58104         // Note that this check ignores type parameters and only considers the
58105         // inheritance hierarchy.
58106         function isTypeDerivedFrom(source, target) {
58107             return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) :
58108                 target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) :
58109                     source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) :
58110                         target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) :
58111                             target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) :
58112                                 hasBaseType(source, getTargetType(target)) || (isArrayType(target) && !isReadonlyArrayType(target) && isTypeDerivedFrom(source, globalReadonlyArrayType));
58113         }
58114         /**
58115          * This is *not* a bi-directional relationship.
58116          * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
58117          *
58118          * 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.
58119          * It is used to check following cases:
58120          *   - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`).
58121          *   - the types of `case` clause expressions and their respective `switch` expressions.
58122          *   - the type of an expression in a type assertion with the type being asserted.
58123          */
58124         function isTypeComparableTo(source, target) {
58125             return isTypeRelatedTo(source, target, comparableRelation);
58126         }
58127         function areTypesComparable(type1, type2) {
58128             return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1);
58129         }
58130         function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) {
58131             return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject);
58132         }
58133         /**
58134          * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to
58135          * attempt to issue more specific errors on, for example, specific object literal properties or tuple members.
58136          */
58137         function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
58138             return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain, /*errorOutputContainer*/ undefined);
58139         }
58140         function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) {
58141             if (isTypeRelatedTo(source, target, relation))
58142                 return true;
58143             if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
58144                 return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer);
58145             }
58146             return false;
58147         }
58148         function isOrHasGenericConditional(type) {
58149             return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional)));
58150         }
58151         function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
58152             if (!node || isOrHasGenericConditional(target))
58153                 return false;
58154             if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined)
58155                 && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
58156                 return true;
58157             }
58158             switch (node.kind) {
58159                 case 283 /* JsxExpression */:
58160                 case 207 /* ParenthesizedExpression */:
58161                     return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
58162                 case 216 /* BinaryExpression */:
58163                     switch (node.operatorToken.kind) {
58164                         case 62 /* EqualsToken */:
58165                         case 27 /* CommaToken */:
58166                             return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
58167                     }
58168                     break;
58169                 case 200 /* ObjectLiteralExpression */:
58170                     return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
58171                 case 199 /* ArrayLiteralExpression */:
58172                     return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
58173                 case 281 /* JsxAttributes */:
58174                     return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer);
58175                 case 209 /* ArrowFunction */:
58176                     return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer);
58177             }
58178             return false;
58179         }
58180         function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
58181             var callSignatures = getSignaturesOfType(source, 0 /* Call */);
58182             var constructSignatures = getSignaturesOfType(source, 1 /* Construct */);
58183             for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) {
58184                 var signatures = _a[_i];
58185                 if (ts.some(signatures, function (s) {
58186                     var returnType = getReturnTypeOfSignature(s);
58187                     return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined);
58188                 })) {
58189                     var resultObj = errorOutputContainer || {};
58190                     checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj);
58191                     var diagnostic = resultObj.errors[resultObj.errors.length - 1];
58192                     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));
58193                     return true;
58194                 }
58195             }
58196             return false;
58197         }
58198         function elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer) {
58199             // Don't elaborate blocks
58200             if (ts.isBlock(node.body)) {
58201                 return false;
58202             }
58203             // Or functions with annotated parameter types
58204             if (ts.some(node.parameters, ts.hasType)) {
58205                 return false;
58206             }
58207             var sourceSig = getSingleCallSignature(source);
58208             if (!sourceSig) {
58209                 return false;
58210             }
58211             var targetSignatures = getSignaturesOfType(target, 0 /* Call */);
58212             if (!ts.length(targetSignatures)) {
58213                 return false;
58214             }
58215             var returnExpression = node.body;
58216             var sourceReturn = getReturnTypeOfSignature(sourceSig);
58217             var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature));
58218             if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) {
58219                 var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
58220                 if (elaborated) {
58221                     return elaborated;
58222                 }
58223                 var resultObj = errorOutputContainer || {};
58224                 checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, containingMessageChain, resultObj);
58225                 if (resultObj.errors) {
58226                     if (target.symbol && ts.length(target.symbol.declarations)) {
58227                         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));
58228                     }
58229                     if ((ts.getFunctionFlags(node) & 2 /* Async */) === 0
58230                         // exclude cases where source itself is promisy - this way we don't make a suggestion when relating
58231                         // an IPromise and a Promise that are slightly different
58232                         && !getTypeOfPropertyOfType(sourceReturn, "then")
58233                         && checkTypeRelatedTo(createPromiseType(sourceReturn), targetReturn, relation, /*errorNode*/ undefined)) {
58234                         ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async));
58235                     }
58236                     return true;
58237                 }
58238             }
58239             return false;
58240         }
58241         function getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType) {
58242             var idx = getIndexedAccessTypeOrUndefined(target, nameType);
58243             if (idx) {
58244                 return idx;
58245             }
58246             if (target.flags & 1048576 /* Union */) {
58247                 var best = getBestMatchingType(source, target);
58248                 if (best) {
58249                     return getIndexedAccessTypeOrUndefined(best, nameType);
58250                 }
58251             }
58252         }
58253         function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) {
58254             next.contextualType = sourcePropType;
58255             try {
58256                 return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType);
58257             }
58258             finally {
58259                 next.contextualType = undefined;
58260             }
58261         }
58262         /**
58263          * For every element returned from the iterator, checks that element to issue an error on a property of that element's type
58264          * 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`
58265          * Otherwise, we issue an error on _every_ element which fail the assignability check
58266          */
58267         function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) {
58268             // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
58269             var reportedError = false;
58270             for (var status = iterator.next(); !status.done; status = iterator.next()) {
58271                 var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage;
58272                 var targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
58273                 if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */)
58274                     continue; // Don't elaborate on indexes on generic variables
58275                 var sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
58276                 if (sourcePropType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
58277                     var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
58278                     if (elaborated) {
58279                         reportedError = true;
58280                     }
58281                     else {
58282                         // Issue error on the prop itself, since the prop couldn't elaborate the error
58283                         var resultObj = errorOutputContainer || {};
58284                         // Use the expression type, if available
58285                         var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType;
58286                         var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
58287                         if (result && specificSource !== sourcePropType) {
58288                             // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType
58289                             checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
58290                         }
58291                         if (resultObj.errors) {
58292                             var reportedDiag = resultObj.errors[resultObj.errors.length - 1];
58293                             var propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
58294                             var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined;
58295                             var issuedElaboration = false;
58296                             if (!targetProp) {
58297                                 var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) ||
58298                                     getIndexInfoOfType(target, 0 /* String */) ||
58299                                     undefined;
58300                                 if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
58301                                     issuedElaboration = true;
58302                                     ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
58303                                 }
58304                             }
58305                             if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) {
58306                                 var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
58307                                 if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
58308                                     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)));
58309                                 }
58310                             }
58311                         }
58312                         reportedError = true;
58313                     }
58314                 }
58315             }
58316             return reportedError;
58317         }
58318         function generateJsxAttributes(node) {
58319             var _i, _a, prop;
58320             return __generator(this, function (_b) {
58321                 switch (_b.label) {
58322                     case 0:
58323                         if (!ts.length(node.properties))
58324                             return [2 /*return*/];
58325                         _i = 0, _a = node.properties;
58326                         _b.label = 1;
58327                     case 1:
58328                         if (!(_i < _a.length)) return [3 /*break*/, 4];
58329                         prop = _a[_i];
58330                         if (ts.isJsxSpreadAttribute(prop))
58331                             return [3 /*break*/, 3];
58332                         return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }];
58333                     case 2:
58334                         _b.sent();
58335                         _b.label = 3;
58336                     case 3:
58337                         _i++;
58338                         return [3 /*break*/, 1];
58339                     case 4: return [2 /*return*/];
58340                 }
58341             });
58342         }
58343         function generateJsxChildren(node, getInvalidTextDiagnostic) {
58344             var memberOffset, i, child, nameType, elem;
58345             return __generator(this, function (_a) {
58346                 switch (_a.label) {
58347                     case 0:
58348                         if (!ts.length(node.children))
58349                             return [2 /*return*/];
58350                         memberOffset = 0;
58351                         i = 0;
58352                         _a.label = 1;
58353                     case 1:
58354                         if (!(i < node.children.length)) return [3 /*break*/, 5];
58355                         child = node.children[i];
58356                         nameType = getLiteralType(i - memberOffset);
58357                         elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic);
58358                         if (!elem) return [3 /*break*/, 3];
58359                         return [4 /*yield*/, elem];
58360                     case 2:
58361                         _a.sent();
58362                         return [3 /*break*/, 4];
58363                     case 3:
58364                         memberOffset++;
58365                         _a.label = 4;
58366                     case 4:
58367                         i++;
58368                         return [3 /*break*/, 1];
58369                     case 5: return [2 /*return*/];
58370                 }
58371             });
58372         }
58373         function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) {
58374             switch (child.kind) {
58375                 case 283 /* JsxExpression */:
58376                     // child is of the type of the expression
58377                     return { errorNode: child, innerExpression: child.expression, nameType: nameType };
58378                 case 11 /* JsxText */:
58379                     if (child.containsOnlyTriviaWhiteSpaces) {
58380                         break; // Whitespace only jsx text isn't real jsx text
58381                     }
58382                     // child is a string
58383                     return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() };
58384                 case 273 /* JsxElement */:
58385                 case 274 /* JsxSelfClosingElement */:
58386                 case 277 /* JsxFragment */:
58387                     // child is of type JSX.Element
58388                     return { errorNode: child, innerExpression: child, nameType: nameType };
58389                 default:
58390                     return ts.Debug.assertNever(child, "Found invalid jsx child");
58391             }
58392         }
58393         function elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer) {
58394             var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation, containingMessageChain, errorOutputContainer);
58395             var invalidTextDiagnostic;
58396             if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) {
58397                 var containingElement = node.parent.parent;
58398                 var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
58399                 var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
58400                 var childrenNameType = getLiteralType(childrenPropName);
58401                 var childrenTargetType = getIndexedAccessType(target, childrenNameType);
58402                 var validChildren = ts.getSemanticJsxChildren(containingElement.children);
58403                 if (!ts.length(validChildren)) {
58404                     return result;
58405                 }
58406                 var moreThanOneRealChildren = ts.length(validChildren) > 1;
58407                 var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType);
58408                 var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); });
58409                 if (moreThanOneRealChildren) {
58410                     if (arrayLikeTargetParts !== neverType) {
58411                         var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */));
58412                         var children = generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic);
58413                         result = elaborateElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result;
58414                     }
58415                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
58416                         // arity mismatch
58417                         result = true;
58418                         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));
58419                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
58420                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
58421                         }
58422                     }
58423                 }
58424                 else {
58425                     if (nonArrayLikeTargetParts !== neverType) {
58426                         var child = validChildren[0];
58427                         var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic);
58428                         if (elem_1) {
58429                             result = elaborateElementwise((function () { return __generator(this, function (_a) {
58430                                 switch (_a.label) {
58431                                     case 0: return [4 /*yield*/, elem_1];
58432                                     case 1:
58433                                         _a.sent();
58434                                         return [2 /*return*/];
58435                                 }
58436                             }); })(), source, target, relation, containingMessageChain, errorOutputContainer) || result;
58437                         }
58438                     }
58439                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
58440                         // arity mismatch
58441                         result = true;
58442                         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));
58443                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
58444                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
58445                         }
58446                     }
58447                 }
58448             }
58449             return result;
58450             function getInvalidTextualChildDiagnostic() {
58451                 if (!invalidTextDiagnostic) {
58452                     var tagNameText = ts.getTextOfNode(node.parent.tagName);
58453                     var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
58454                     var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
58455                     var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName));
58456                     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;
58457                     invalidTextDiagnostic = __assign(__assign({}, diagnostic), { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) });
58458                 }
58459                 return invalidTextDiagnostic;
58460             }
58461         }
58462         function generateLimitedTupleElements(node, target) {
58463             var len, i, elem, nameType;
58464             return __generator(this, function (_a) {
58465                 switch (_a.label) {
58466                     case 0:
58467                         len = ts.length(node.elements);
58468                         if (!len)
58469                             return [2 /*return*/];
58470                         i = 0;
58471                         _a.label = 1;
58472                     case 1:
58473                         if (!(i < len)) return [3 /*break*/, 4];
58474                         // 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
58475                         if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i)))
58476                             return [3 /*break*/, 3];
58477                         elem = node.elements[i];
58478                         if (ts.isOmittedExpression(elem))
58479                             return [3 /*break*/, 3];
58480                         nameType = getLiteralType(i);
58481                         return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }];
58482                     case 2:
58483                         _a.sent();
58484                         _a.label = 3;
58485                     case 3:
58486                         i++;
58487                         return [3 /*break*/, 1];
58488                     case 4: return [2 /*return*/];
58489                 }
58490             });
58491         }
58492         function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
58493             if (target.flags & 131068 /* Primitive */)
58494                 return false;
58495             if (isTupleLikeType(source)) {
58496                 return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer);
58497             }
58498             // recreate a tuple from the elements, if possible
58499             // Since we're re-doing the expression type, we need to reapply the contextual type
58500             var oldContext = node.contextualType;
58501             node.contextualType = target;
58502             try {
58503                 var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
58504                 node.contextualType = oldContext;
58505                 if (isTupleLikeType(tupleizedType)) {
58506                     return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer);
58507                 }
58508                 return false;
58509             }
58510             finally {
58511                 node.contextualType = oldContext;
58512             }
58513         }
58514         function generateObjectLiteralElements(node) {
58515             var _i, _a, prop, type, _b;
58516             return __generator(this, function (_c) {
58517                 switch (_c.label) {
58518                     case 0:
58519                         if (!ts.length(node.properties))
58520                             return [2 /*return*/];
58521                         _i = 0, _a = node.properties;
58522                         _c.label = 1;
58523                     case 1:
58524                         if (!(_i < _a.length)) return [3 /*break*/, 8];
58525                         prop = _a[_i];
58526                         if (ts.isSpreadAssignment(prop))
58527                             return [3 /*break*/, 7];
58528                         type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */);
58529                         if (!type || (type.flags & 131072 /* Never */)) {
58530                             return [3 /*break*/, 7];
58531                         }
58532                         _b = prop.kind;
58533                         switch (_b) {
58534                             case 168 /* SetAccessor */: return [3 /*break*/, 2];
58535                             case 167 /* GetAccessor */: return [3 /*break*/, 2];
58536                             case 165 /* MethodDeclaration */: return [3 /*break*/, 2];
58537                             case 289 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2];
58538                             case 288 /* PropertyAssignment */: return [3 /*break*/, 4];
58539                         }
58540                         return [3 /*break*/, 6];
58541                     case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }];
58542                     case 3:
58543                         _c.sent();
58544                         return [3 /*break*/, 7];
58545                     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 }];
58546                     case 5:
58547                         _c.sent();
58548                         return [3 /*break*/, 7];
58549                     case 6:
58550                         ts.Debug.assertNever(prop);
58551                         _c.label = 7;
58552                     case 7:
58553                         _i++;
58554                         return [3 /*break*/, 1];
58555                     case 8: return [2 /*return*/];
58556                 }
58557             });
58558         }
58559         function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
58560             if (target.flags & 131068 /* Primitive */)
58561                 return false;
58562             return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer);
58563         }
58564         /**
58565          * This is *not* a bi-directional relationship.
58566          * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'.
58567          */
58568         function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) {
58569             return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
58570         }
58571         function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
58572             return compareSignaturesRelated(source, target, ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0, /*reportErrors*/ false, 
58573             /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */;
58574         }
58575         /**
58576          * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
58577          */
58578         function isAnySignature(s) {
58579             return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
58580                 signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
58581                 isTypeAny(getReturnTypeOfSignature(s));
58582         }
58583         /**
58584          * See signatureRelatedTo, compareSignaturesIdentical
58585          */
58586         function compareSignaturesRelated(source, target, checkMode, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) {
58587             // TODO (drosen): De-duplicate code between related functions.
58588             if (source === target) {
58589                 return -1 /* True */;
58590             }
58591             if (isAnySignature(target)) {
58592                 return -1 /* True */;
58593             }
58594             var targetCount = getParameterCount(target);
58595             var sourceHasMoreParameters = !hasEffectiveRestParameter(target) &&
58596                 (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount);
58597             if (sourceHasMoreParameters) {
58598                 return 0 /* False */;
58599             }
58600             if (source.typeParameters && source.typeParameters !== target.typeParameters) {
58601                 target = getCanonicalSignature(target);
58602                 source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
58603             }
58604             var sourceCount = getParameterCount(source);
58605             var sourceRestType = getNonArrayRestType(source);
58606             var targetRestType = getNonArrayRestType(target);
58607             if (sourceRestType || targetRestType) {
58608                 void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers);
58609             }
58610             if (sourceRestType && targetRestType && sourceCount !== targetCount) {
58611                 // We're not able to relate misaligned complex rest parameters
58612                 return 0 /* False */;
58613             }
58614             var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
58615             var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 165 /* MethodDeclaration */ &&
58616                 kind !== 164 /* MethodSignature */ && kind !== 166 /* Constructor */;
58617             var result = -1 /* True */;
58618             var sourceThisType = getThisTypeOfSignature(source);
58619             if (sourceThisType && sourceThisType !== voidType) {
58620                 var targetThisType = getThisTypeOfSignature(target);
58621                 if (targetThisType) {
58622                     // void sources are assignable to anything.
58623                     var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false)
58624                         || compareTypes(targetThisType, sourceThisType, reportErrors);
58625                     if (!related) {
58626                         if (reportErrors) {
58627                             errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible);
58628                         }
58629                         return 0 /* False */;
58630                     }
58631                     result &= related;
58632                 }
58633             }
58634             var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
58635             var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
58636             for (var i = 0; i < paramCount; i++) {
58637                 var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : tryGetTypeAtPosition(source, i);
58638                 var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : tryGetTypeAtPosition(target, i);
58639                 if (sourceType && targetType) {
58640                     // In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
58641                     // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
58642                     // they naturally relate only contra-variantly). However, if the source and target parameters both have
58643                     // function types with a single call signature, we know we are relating two callback parameters. In
58644                     // that case it is sufficient to only relate the parameters of the signatures co-variantly because,
58645                     // similar to return values, callback parameters are output positions. This means that a Promise<T>,
58646                     // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
58647                     // with respect to T.
58648                     var sourceSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType));
58649                     var targetSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType));
58650                     var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) &&
58651                         (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */);
58652                     var related = callbacks ?
58653                         compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* StrictArity */) | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) :
58654                         !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors);
58655                     // With strict arity, (x: number | undefined) => void is a subtype of (x?: number | undefined) => void
58656                     if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes(sourceType, targetType, /*reportErrors*/ false)) {
58657                         related = 0 /* False */;
58658                     }
58659                     if (!related) {
58660                         if (reportErrors) {
58661                             errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
58662                         }
58663                         return 0 /* False */;
58664                     }
58665                     result &= related;
58666                 }
58667             }
58668             if (!(checkMode & 4 /* IgnoreReturnTypes */)) {
58669                 // If a signature resolution is already in-flight, skip issuing a circularity error
58670                 // here and just use the `any` type directly
58671                 var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType
58672                     : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol))
58673                         : getReturnTypeOfSignature(target);
58674                 if (targetReturnType === voidType) {
58675                     return result;
58676                 }
58677                 var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType
58678                     : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol))
58679                         : getReturnTypeOfSignature(source);
58680                 // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions
58681                 var targetTypePredicate = getTypePredicateOfSignature(target);
58682                 if (targetTypePredicate) {
58683                     var sourceTypePredicate = getTypePredicateOfSignature(source);
58684                     if (sourceTypePredicate) {
58685                         result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
58686                     }
58687                     else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
58688                         if (reportErrors) {
58689                             errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
58690                         }
58691                         return 0 /* False */;
58692                     }
58693                 }
58694                 else {
58695                     // When relating callback signatures, we still need to relate return types bi-variantly as otherwise
58696                     // the containing type wouldn't be co-variant. For example, interface Foo<T> { add(cb: () => T): void }
58697                     // wouldn't be co-variant for T without this rule.
58698                     result &= checkMode & 1 /* BivariantCallback */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) ||
58699                         compareTypes(sourceReturnType, targetReturnType, reportErrors);
58700                     if (!result && reportErrors && incompatibleErrorReporter) {
58701                         incompatibleErrorReporter(sourceReturnType, targetReturnType);
58702                     }
58703                 }
58704             }
58705             return result;
58706         }
58707         function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
58708             if (source.kind !== target.kind) {
58709                 if (reportErrors) {
58710                     errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
58711                     errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
58712                 }
58713                 return 0 /* False */;
58714             }
58715             if (source.kind === 1 /* Identifier */ || source.kind === 3 /* AssertsIdentifier */) {
58716                 if (source.parameterIndex !== target.parameterIndex) {
58717                     if (reportErrors) {
58718                         errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
58719                         errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
58720                     }
58721                     return 0 /* False */;
58722                 }
58723             }
58724             var related = source.type === target.type ? -1 /* True */ :
58725                 source.type && target.type ? compareTypes(source.type, target.type, reportErrors) :
58726                     0 /* False */;
58727             if (related === 0 /* False */ && reportErrors) {
58728                 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
58729             }
58730             return related;
58731         }
58732         function isImplementationCompatibleWithOverload(implementation, overload) {
58733             var erasedSource = getErasedSignature(implementation);
58734             var erasedTarget = getErasedSignature(overload);
58735             // First see if the return types are compatible in either direction.
58736             var sourceReturnType = getReturnTypeOfSignature(erasedSource);
58737             var targetReturnType = getReturnTypeOfSignature(erasedTarget);
58738             if (targetReturnType === voidType
58739                 || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation)
58740                 || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) {
58741                 return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true);
58742             }
58743             return false;
58744         }
58745         function isEmptyResolvedType(t) {
58746             return t !== anyFunctionType &&
58747                 t.properties.length === 0 &&
58748                 t.callSignatures.length === 0 &&
58749                 t.constructSignatures.length === 0 &&
58750                 !t.stringIndexInfo &&
58751                 !t.numberIndexInfo;
58752         }
58753         function isEmptyObjectType(type) {
58754             return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) :
58755                 type.flags & 67108864 /* NonPrimitive */ ? true :
58756                     type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) :
58757                         type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) :
58758                             false;
58759         }
58760         function isEmptyAnonymousObjectType(type) {
58761             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */ && (type.members && isEmptyResolvedType(type) ||
58762                 type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && getMembersOfSymbol(type.symbol).size === 0));
58763         }
58764         function isStringIndexSignatureOnlyType(type) {
58765             return type.flags & 524288 /* Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfoOfType(type, 0 /* String */) && !getIndexInfoOfType(type, 1 /* Number */) ||
58766                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) ||
58767                 false;
58768         }
58769         function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) {
58770             if (sourceSymbol === targetSymbol) {
58771                 return true;
58772             }
58773             var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
58774             var entry = enumRelation.get(id);
58775             if (entry !== undefined && !(!(entry & 4 /* Reported */) && entry & 2 /* Failed */ && errorReporter)) {
58776                 return !!(entry & 1 /* Succeeded */);
58777             }
58778             if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) {
58779                 enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
58780                 return false;
58781             }
58782             var targetEnumType = getTypeOfSymbol(targetSymbol);
58783             for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) {
58784                 var property = _a[_i];
58785                 if (property.flags & 8 /* EnumMember */) {
58786                     var targetProperty = getPropertyOfType(targetEnumType, property.escapedName);
58787                     if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) {
58788                         if (errorReporter) {
58789                             errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */));
58790                             enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
58791                         }
58792                         else {
58793                             enumRelation.set(id, 2 /* Failed */);
58794                         }
58795                         return false;
58796                     }
58797                 }
58798             }
58799             enumRelation.set(id, 1 /* Succeeded */);
58800             return true;
58801         }
58802         function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
58803             var s = source.flags;
58804             var t = target.flags;
58805             if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType)
58806                 return true;
58807             if (t & 131072 /* Never */)
58808                 return false;
58809             if (s & 402653316 /* StringLike */ && t & 4 /* String */)
58810                 return true;
58811             if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ &&
58812                 t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) &&
58813                 source.value === target.value)
58814                 return true;
58815             if (s & 296 /* NumberLike */ && t & 8 /* Number */)
58816                 return true;
58817             if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ &&
58818                 t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) &&
58819                 source.value === target.value)
58820                 return true;
58821             if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */)
58822                 return true;
58823             if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */)
58824                 return true;
58825             if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */)
58826                 return true;
58827             if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
58828                 return true;
58829             if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) {
58830                 if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
58831                     return true;
58832                 if (s & 2944 /* Literal */ && t & 2944 /* Literal */ &&
58833                     source.value === target.value &&
58834                     isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter))
58835                     return true;
58836             }
58837             if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */)))
58838                 return true;
58839             if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */))
58840                 return true;
58841             if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */)
58842                 return true;
58843             if (relation === assignableRelation || relation === comparableRelation) {
58844                 if (s & 1 /* Any */)
58845                     return true;
58846                 // Type number or any numeric literal type is assignable to any numeric enum type or any
58847                 // numeric enum literal type. This rule exists for backwards compatibility reasons because
58848                 // bit-flag enum types sometimes look like literal enum types with numeric literal values.
58849                 if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */))
58850                     return true;
58851             }
58852             return false;
58853         }
58854         function isTypeRelatedTo(source, target, relation) {
58855             if (isFreshLiteralType(source)) {
58856                 source = source.regularType;
58857             }
58858             if (isFreshLiteralType(target)) {
58859                 target = target.regularType;
58860             }
58861             if (source === target) {
58862                 return true;
58863             }
58864             if (relation !== identityRelation) {
58865                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation)) {
58866                     return true;
58867                 }
58868             }
58869             else {
58870                 if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) &&
58871                     source.flags !== target.flags && !(source.flags & 469237760 /* Substructure */))
58872                     return false;
58873             }
58874             if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
58875                 var related = relation.get(getRelationKey(source, target, 0 /* None */, relation));
58876                 if (related !== undefined) {
58877                     return !!(related & 1 /* Succeeded */);
58878                 }
58879             }
58880             if (source.flags & 469499904 /* StructuredOrInstantiable */ || target.flags & 469499904 /* StructuredOrInstantiable */) {
58881                 return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined);
58882             }
58883             return false;
58884         }
58885         function isIgnoredJsxProperty(source, sourceProp) {
58886             return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName);
58887         }
58888         function getNormalizedType(type, writing) {
58889             while (true) {
58890                 var t = isFreshLiteralType(type) ? type.regularType :
58891                     ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) :
58892                         type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) :
58893                             type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute :
58894                                 type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) :
58895                                     type;
58896                 if (t === type)
58897                     break;
58898                 type = t;
58899             }
58900             return type;
58901         }
58902         /**
58903          * Checks if 'source' is related to 'target' (e.g.: is a assignable to).
58904          * @param source The left-hand-side of the relation.
58905          * @param target The right-hand-side of the relation.
58906          * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'.
58907          * Used as both to determine which checks are performed and as a cache of previously computed results.
58908          * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used.
58909          * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used.
58910          * @param containingMessageChain A chain of errors to prepend any new errors found.
58911          * @param errorOutputContainer Return the diagnostic. Do not log if 'skipLogging' is truthy.
58912          */
58913         function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
58914             var errorInfo;
58915             var relatedInfo;
58916             var maybeKeys;
58917             var sourceStack;
58918             var targetStack;
58919             var maybeCount = 0;
58920             var depth = 0;
58921             var expandingFlags = 0 /* None */;
58922             var overflow = false;
58923             var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid
58924             var lastSkippedInfo;
58925             var incompatibleStack = [];
58926             var inPropertyCheck = false;
58927             ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
58928             var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage);
58929             if (incompatibleStack.length) {
58930                 reportIncompatibleStack();
58931             }
58932             if (overflow) {
58933                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth });
58934                 var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
58935                 if (errorOutputContainer) {
58936                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
58937                 }
58938             }
58939             else if (errorInfo) {
58940                 if (containingMessageChain) {
58941                     var chain = containingMessageChain();
58942                     if (chain) {
58943                         ts.concatenateDiagnosticMessageChains(chain, errorInfo);
58944                         errorInfo = chain;
58945                     }
58946                 }
58947                 var relatedInformation = void 0;
58948                 // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement
58949                 if (headMessage && errorNode && !result && source.symbol) {
58950                     var links = getSymbolLinks(source.symbol);
58951                     if (links.originatingImport && !ts.isImportCall(links.originatingImport)) {
58952                         var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined);
58953                         if (helpfulRetry) {
58954                             // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import
58955                             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);
58956                             relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it
58957                         }
58958                     }
58959                 }
58960                 var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
58961                 if (relatedInfo) {
58962                     ts.addRelatedInfo.apply(void 0, __spreadArray([diag], relatedInfo));
58963                 }
58964                 if (errorOutputContainer) {
58965                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
58966                 }
58967                 if (!errorOutputContainer || !errorOutputContainer.skipLogging) {
58968                     diagnostics.add(diag);
58969                 }
58970             }
58971             if (errorNode && errorOutputContainer && errorOutputContainer.skipLogging && result === 0 /* False */) {
58972                 ts.Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error.");
58973             }
58974             return result !== 0 /* False */;
58975             function resetErrorInfo(saved) {
58976                 errorInfo = saved.errorInfo;
58977                 lastSkippedInfo = saved.lastSkippedInfo;
58978                 incompatibleStack = saved.incompatibleStack;
58979                 overrideNextErrorInfo = saved.overrideNextErrorInfo;
58980                 relatedInfo = saved.relatedInfo;
58981             }
58982             function captureErrorCalculationState() {
58983                 return {
58984                     errorInfo: errorInfo,
58985                     lastSkippedInfo: lastSkippedInfo,
58986                     incompatibleStack: incompatibleStack.slice(),
58987                     overrideNextErrorInfo: overrideNextErrorInfo,
58988                     relatedInfo: !relatedInfo ? undefined : relatedInfo.slice()
58989                 };
58990             }
58991             function reportIncompatibleError(message, arg0, arg1, arg2, arg3) {
58992                 overrideNextErrorInfo++; // Suppress the next relation error
58993                 lastSkippedInfo = undefined; // Reset skipped info cache
58994                 incompatibleStack.push([message, arg0, arg1, arg2, arg3]);
58995             }
58996             function reportIncompatibleStack() {
58997                 var stack = incompatibleStack;
58998                 incompatibleStack = [];
58999                 var info = lastSkippedInfo;
59000                 lastSkippedInfo = undefined;
59001                 if (stack.length === 1) {
59002                     reportError.apply(void 0, stack[0]);
59003                     if (info) {
59004                         // Actually do the last relation error
59005                         reportRelationError.apply(void 0, __spreadArray([/*headMessage*/ undefined], info));
59006                     }
59007                     return;
59008                 }
59009                 // The first error will be the innermost, while the last will be the outermost - so by popping off the end,
59010                 // we can build from left to right
59011                 var path = "";
59012                 var secondaryRootErrors = [];
59013                 while (stack.length) {
59014                     var _a = stack.pop(), msg = _a[0], args = _a.slice(1);
59015                     switch (msg.code) {
59016                         case ts.Diagnostics.Types_of_property_0_are_incompatible.code: {
59017                             // Parenthesize a `new` if there is one
59018                             if (path.indexOf("new ") === 0) {
59019                                 path = "(" + path + ")";
59020                             }
59021                             var str = "" + args[0];
59022                             // If leading, just print back the arg (irrespective of if it's a valid identifier)
59023                             if (path.length === 0) {
59024                                 path = "" + str;
59025                             }
59026                             // Otherwise write a dotted name if possible
59027                             else if (ts.isIdentifierText(str, compilerOptions.target)) {
59028                                 path = path + "." + str;
59029                             }
59030                             // Failing that, check if the name is already a computed name
59031                             else if (str[0] === "[" && str[str.length - 1] === "]") {
59032                                 path = "" + path + str;
59033                             }
59034                             // And finally write out a computed name as a last resort
59035                             else {
59036                                 path = path + "[" + str + "]";
59037                             }
59038                             break;
59039                         }
59040                         case ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible.code:
59041                         case ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code:
59042                         case ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code:
59043                         case ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: {
59044                             if (path.length === 0) {
59045                                 // Don't flatten signature compatability errors at the start of a chain - instead prefer
59046                                 // to unify (the with no arguments bit is excessive for printback) and print them back
59047                                 var mappedMsg = msg;
59048                                 if (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
59049                                     mappedMsg = ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible;
59050                                 }
59051                                 else if (msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
59052                                     mappedMsg = ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible;
59053                                 }
59054                                 secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]);
59055                             }
59056                             else {
59057                                 var prefix = (msg.code === ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code ||
59058                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
59059                                     ? "new "
59060                                     : "";
59061                                 var params = (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ||
59062                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
59063                                     ? ""
59064                                     : "...";
59065                                 path = "" + prefix + path + "(" + params + ")";
59066                             }
59067                             break;
59068                         }
59069                         default:
59070                             return ts.Debug.fail("Unhandled Diagnostic: " + msg.code);
59071                     }
59072                 }
59073                 if (path) {
59074                     reportError(path[path.length - 1] === ")"
59075                         ? ts.Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types
59076                         : ts.Diagnostics.The_types_of_0_are_incompatible_between_these_types, path);
59077                 }
59078                 else {
59079                     // Remove the innermost secondary error as it will duplicate the error already reported by `reportRelationError` on entry
59080                     secondaryRootErrors.shift();
59081                 }
59082                 for (var _i = 0, secondaryRootErrors_1 = secondaryRootErrors; _i < secondaryRootErrors_1.length; _i++) {
59083                     var _b = secondaryRootErrors_1[_i], msg = _b[0], args = _b.slice(1);
59084                     var originalValue = msg.elidedInCompatabilityPyramid;
59085                     msg.elidedInCompatabilityPyramid = false; // Temporarily override elision to ensure error is reported
59086                     reportError.apply(void 0, __spreadArray([msg], args));
59087                     msg.elidedInCompatabilityPyramid = originalValue;
59088                 }
59089                 if (info) {
59090                     // Actually do the last relation error
59091                     reportRelationError.apply(void 0, __spreadArray([/*headMessage*/ undefined], info));
59092                 }
59093             }
59094             function reportError(message, arg0, arg1, arg2, arg3) {
59095                 ts.Debug.assert(!!errorNode);
59096                 if (incompatibleStack.length)
59097                     reportIncompatibleStack();
59098                 if (message.elidedInCompatabilityPyramid)
59099                     return;
59100                 errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3);
59101             }
59102             function associateRelatedInfo(info) {
59103                 ts.Debug.assert(!!errorInfo);
59104                 if (!relatedInfo) {
59105                     relatedInfo = [info];
59106                 }
59107                 else {
59108                     relatedInfo.push(info);
59109                 }
59110             }
59111             function reportRelationError(message, source, target) {
59112                 if (incompatibleStack.length)
59113                     reportIncompatibleStack();
59114                 var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1];
59115                 var generalizedSource = source;
59116                 var generalizedSourceType = sourceType;
59117                 if (isLiteralType(source) && !typeCouldHaveTopLevelSingletonTypes(target)) {
59118                     generalizedSource = getBaseTypeOfLiteralType(source);
59119                     ts.Debug.assert(!isTypeAssignableTo(generalizedSource, target), "generalized source shouldn't be assignable");
59120                     generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource);
59121                 }
59122                 if (target.flags & 262144 /* TypeParameter */) {
59123                     var constraint = getBaseConstraintOfType(target);
59124                     var needsOriginalSource = void 0;
59125                     if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source, constraint)))) {
59126                         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));
59127                     }
59128                     else {
59129                         reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, generalizedSourceType);
59130                     }
59131                 }
59132                 if (!message) {
59133                     if (relation === comparableRelation) {
59134                         message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1;
59135                     }
59136                     else if (sourceType === targetType) {
59137                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated;
59138                     }
59139                     else {
59140                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1;
59141                     }
59142                 }
59143                 reportError(message, generalizedSourceType, targetType);
59144             }
59145             function tryElaborateErrorsForPrimitivesAndObjects(source, target) {
59146                 var sourceType = symbolValueDeclarationIsContextSensitive(source.symbol) ? typeToString(source, source.symbol.valueDeclaration) : typeToString(source);
59147                 var targetType = symbolValueDeclarationIsContextSensitive(target.symbol) ? typeToString(target, target.symbol.valueDeclaration) : typeToString(target);
59148                 if ((globalStringType === source && stringType === target) ||
59149                     (globalNumberType === source && numberType === target) ||
59150                     (globalBooleanType === source && booleanType === target) ||
59151                     (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) {
59152                     reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
59153                 }
59154             }
59155             /**
59156              * Try and elaborate array and tuple errors. Returns false
59157              * if we have found an elaboration, or we should ignore
59158              * any other elaborations when relating the `source` and
59159              * `target` types.
59160              */
59161             function tryElaborateArrayLikeErrors(source, target, reportErrors) {
59162                 /**
59163                  * The spec for elaboration is:
59164                  * - If the source is a readonly tuple and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
59165                  * - If the source is a tuple then skip property elaborations if the target is an array or tuple.
59166                  * - If the source is a readonly array and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
59167                  * - If the source an array then skip property elaborations if the target is a tuple.
59168                  */
59169                 if (isTupleType(source)) {
59170                     if (source.target.readonly && isMutableArrayOrTuple(target)) {
59171                         if (reportErrors) {
59172                             reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
59173                         }
59174                         return false;
59175                     }
59176                     return isTupleType(target) || isArrayType(target);
59177                 }
59178                 if (isReadonlyArrayType(source) && isMutableArrayOrTuple(target)) {
59179                     if (reportErrors) {
59180                         reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
59181                     }
59182                     return false;
59183                 }
59184                 if (isTupleType(target)) {
59185                     return isArrayType(source);
59186                 }
59187                 return true;
59188             }
59189             /**
59190              * Compare two types and return
59191              * * Ternary.True if they are related with no assumptions,
59192              * * Ternary.Maybe if they are related with assumptions of other relationships, or
59193              * * Ternary.False if they are not related.
59194              */
59195             function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) {
59196                 if (reportErrors === void 0) { reportErrors = false; }
59197                 if (intersectionState === void 0) { intersectionState = 0 /* None */; }
59198                 // Before normalization: if `source` is type an object type, and `target` is primitive,
59199                 // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result
59200                 if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) {
59201                     if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) {
59202                         return -1 /* True */;
59203                     }
59204                     reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */));
59205                     return 0 /* False */;
59206                 }
59207                 // Normalize the source and target types: Turn fresh literal types into regular literal types,
59208                 // turn deferred type references into regular type references, simplify indexed access and
59209                 // conditional types, and resolve substitution types to either the substitution (on the source
59210                 // side) or the type variable (on the target side).
59211                 var source = getNormalizedType(originalSource, /*writing*/ false);
59212                 var target = getNormalizedType(originalTarget, /*writing*/ true);
59213                 if (source === target)
59214                     return -1 /* True */;
59215                 if (relation === identityRelation) {
59216                     return isIdenticalTo(source, target);
59217                 }
59218                 // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common,
59219                 // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself,
59220                 // as we break down the _target_ union first, _then_ get the source constraint - so for every
59221                 // member of the target, we attempt to find a match in the source. This avoids that in cases where
59222                 // the target is exactly the constraint.
59223                 if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) {
59224                     return -1 /* True */;
59225                 }
59226                 // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
59227                 // If so, reporting the `null` and `undefined` in the type is hardly useful.
59228                 // First, see if we're even relating an object type to a union.
59229                 // Then see if the target is stripped down to a single non-union type.
59230                 // Note
59231                 //  * We actually want to remove null and undefined naively here (rather than using getNonNullableType),
59232                 //    since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
59233                 //    when dealing with generics.
59234                 //  * We also don't deal with primitive source types, since we already halt elaboration below.
59235                 if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ &&
59236                     target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) {
59237                     var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */);
59238                     if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) {
59239                         if (source === nullStrippedTarget)
59240                             return -1 /* True */;
59241                         target = nullStrippedTarget;
59242                     }
59243                 }
59244                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
59245                     isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined))
59246                     return -1 /* True */;
59247                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
59248                 var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */);
59249                 if (isPerformingExcessPropertyChecks) {
59250                     if (hasExcessProperties(source, target, reportErrors)) {
59251                         if (reportErrors) {
59252                             reportRelationError(headMessage, source, originalTarget.aliasSymbol ? originalTarget : target);
59253                         }
59254                         return 0 /* False */;
59255                     }
59256                 }
59257                 var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) &&
59258                     source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType &&
59259                     target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) &&
59260                     (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source));
59261                 if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) {
59262                     if (reportErrors) {
59263                         var sourceString = typeToString(originalSource.aliasSymbol ? originalSource : source);
59264                         var targetString = typeToString(originalTarget.aliasSymbol ? originalTarget : target);
59265                         var calls = getSignaturesOfType(source, 0 /* Call */);
59266                         var constructs = getSignaturesOfType(source, 1 /* Construct */);
59267                         if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) ||
59268                             constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) {
59269                             reportError(ts.Diagnostics.Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it, sourceString, targetString);
59270                         }
59271                         else {
59272                             reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, sourceString, targetString);
59273                         }
59274                     }
59275                     return 0 /* False */;
59276                 }
59277                 traceUnionsOrIntersectionsTooLarge(source, target);
59278                 var result = 0 /* False */;
59279                 var saveErrorInfo = captureErrorCalculationState();
59280                 // Note that these checks are specifically ordered to produce correct results. In particular,
59281                 // we need to deconstruct unions before intersections (because unions are always at the top),
59282                 // and we need to handle "each" relations before "some" relations for the same kind of type.
59283                 if (source.flags & 3145728 /* UnionOrIntersection */ || target.flags & 3145728 /* UnionOrIntersection */) {
59284                     result = getConstituentCount(source) * getConstituentCount(target) >= 4 ?
59285                         recursiveTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */) :
59286                         structuredTypeRelatedTo(source, target, reportErrors, intersectionState | 8 /* UnionIntersectionCheck */);
59287                 }
59288                 if (!result && !(source.flags & 1048576 /* Union */) && (source.flags & (469499904 /* StructuredOrInstantiable */) || target.flags & 469499904 /* StructuredOrInstantiable */)) {
59289                     if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) {
59290                         resetErrorInfo(saveErrorInfo);
59291                     }
59292                 }
59293                 if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) {
59294                     // The combined constraint of an intersection type is the intersection of the constraints of
59295                     // the constituents. When an intersection type contains instantiable types with union type
59296                     // constraints, there are situations where we need to examine the combined constraint. One is
59297                     // when the target is a union type. Another is when the intersection contains types belonging
59298                     // to one of the disjoint domains. For example, given type variables T and U, each with the
59299                     // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
59300                     // we need to check this constraint against a union on the target side. Also, given a type
59301                     // variable V constrained to 'string | number', 'V & number' has a combined constraint of
59302                     // 'string & number | number & number' which reduces to just 'number'.
59303                     // This also handles type parameters, as a type parameter with a union constraint compared against a union
59304                     // needs to have its constraint hoisted into an intersection with said type parameter, this way
59305                     // the type param can be compared with itself in the target (with the influence of its constraint to match other parts)
59306                     // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)`
59307                     var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */));
59308                     if (constraint && (source.flags & 2097152 /* Intersection */ || target.flags & 1048576 /* Union */)) {
59309                         if (everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself
59310                             // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
59311                             if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
59312                                 resetErrorInfo(saveErrorInfo);
59313                             }
59314                         }
59315                     }
59316                 }
59317                 // For certain combinations involving intersections and optional, excess, or mismatched properties we need
59318                 // an extra property check where the intersection is viewed as a single object. The following are motivating
59319                 // examples that all should be errors, but aren't without this extra property check:
59320                 //
59321                 //   let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 };  // Nested excess property
59322                 //
59323                 //   declare let wrong: { a: { y: string } };
59324                 //   let weak: { a?: { x?: number } } & { c?: string } = wrong;  // Nested weak object type
59325                 //
59326                 //   function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) {
59327                 //     x = y;  // Mismatched property in source intersection
59328                 //   }
59329                 //
59330                 // We suppress recursive intersection property checks because they can generate lots of work when relating
59331                 // recursive intersections that are structurally similar but not exactly identical. See #37854.
59332                 if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) ||
59333                     isNonGenericObjectType(target) && !isArrayType(target) && !isTupleType(target) && source.flags & 2097152 /* Intersection */ && getApparentType(source).flags & 3670016 /* StructuredType */ && !ts.some(source.types, function (t) { return !!(ts.getObjectFlags(t) & 2097152 /* NonInferrableType */); }))) {
59334                     inPropertyCheck = true;
59335                     result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */);
59336                     inPropertyCheck = false;
59337                 }
59338                 reportErrorResults(source, target, result, isComparingJsxAttributes);
59339                 return result;
59340                 function reportErrorResults(source, target, result, isComparingJsxAttributes) {
59341                     if (!result && reportErrors) {
59342                         source = originalSource.aliasSymbol ? originalSource : source;
59343                         target = originalTarget.aliasSymbol ? originalTarget : target;
59344                         var maybeSuppress = overrideNextErrorInfo > 0;
59345                         if (maybeSuppress) {
59346                             overrideNextErrorInfo--;
59347                         }
59348                         if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
59349                             var currentError = errorInfo;
59350                             tryElaborateArrayLikeErrors(source, target, reportErrors);
59351                             if (errorInfo !== currentError) {
59352                                 maybeSuppress = !!errorInfo;
59353                             }
59354                         }
59355                         if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) {
59356                             tryElaborateErrorsForPrimitivesAndObjects(source, target);
59357                         }
59358                         else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) {
59359                             reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
59360                         }
59361                         else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) {
59362                             var targetTypes = target.types;
59363                             var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
59364                             var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
59365                             if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType &&
59366                                 (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
59367                                 // do not report top error
59368                                 return result;
59369                             }
59370                         }
59371                         else {
59372                             errorInfo = elaborateNeverIntersection(errorInfo, originalTarget);
59373                         }
59374                         if (!headMessage && maybeSuppress) {
59375                             lastSkippedInfo = [source, target];
59376                             // Used by, eg, missing property checking to replace the top-level message with a more informative one
59377                             return result;
59378                         }
59379                         reportRelationError(headMessage, source, target);
59380                     }
59381                 }
59382             }
59383             function traceUnionsOrIntersectionsTooLarge(source, target) {
59384                 if (!ts.tracing) {
59385                     return;
59386                 }
59387                 if ((source.flags & 3145728 /* UnionOrIntersection */) && (target.flags & 3145728 /* UnionOrIntersection */)) {
59388                     var sourceUnionOrIntersection = source;
59389                     var targetUnionOrIntersection = target;
59390                     if (sourceUnionOrIntersection.objectFlags & targetUnionOrIntersection.objectFlags & 262144 /* PrimitiveUnion */) {
59391                         // There's a fast path for comparing primitive unions
59392                         return;
59393                     }
59394                     var sourceSize = sourceUnionOrIntersection.types.length;
59395                     var targetSize = targetUnionOrIntersection.types.length;
59396                     if (sourceSize * targetSize > 1E6) {
59397                         ts.tracing.instant("checkTypes" /* CheckTypes */, "traceUnionsOrIntersectionsTooLarge_DepthLimit", {
59398                             sourceId: source.id,
59399                             sourceSize: sourceSize,
59400                             targetId: target.id,
59401                             targetSize: targetSize,
59402                             pos: errorNode === null || errorNode === void 0 ? void 0 : errorNode.pos,
59403                             end: errorNode === null || errorNode === void 0 ? void 0 : errorNode.end
59404                         });
59405                     }
59406                 }
59407             }
59408             function isIdenticalTo(source, target) {
59409                 var flags = source.flags & target.flags;
59410                 if (!(flags & 469237760 /* Substructure */)) {
59411                     return 0 /* False */;
59412                 }
59413                 traceUnionsOrIntersectionsTooLarge(source, target);
59414                 if (flags & 3145728 /* UnionOrIntersection */) {
59415                     var result_6 = eachTypeRelatedToSomeType(source, target);
59416                     if (result_6) {
59417                         result_6 &= eachTypeRelatedToSomeType(target, source);
59418                     }
59419                     return result_6;
59420                 }
59421                 return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */);
59422             }
59423             function getTypeOfPropertyInTypes(types, name) {
59424                 var appendPropType = function (propTypes, type) {
59425                     type = getApparentType(type);
59426                     var prop = type.flags & 3145728 /* UnionOrIntersection */ ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name);
59427                     var propType = prop && getTypeOfSymbol(prop) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || undefinedType;
59428                     return ts.append(propTypes, propType);
59429                 };
59430                 return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray);
59431             }
59432             function hasExcessProperties(source, target, reportErrors) {
59433                 if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) {
59434                     return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny
59435                 }
59436                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
59437                 if ((relation === assignableRelation || relation === comparableRelation) &&
59438                     (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) {
59439                     return false;
59440                 }
59441                 var reducedTarget = target;
59442                 var checkTypes;
59443                 if (target.flags & 1048576 /* Union */) {
59444                     reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target);
59445                     checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget];
59446                 }
59447                 var _loop_16 = function (prop) {
59448                     if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) {
59449                         if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) {
59450                             if (reportErrors) {
59451                                 // Report error in terms of object types in the target as those are the only ones
59452                                 // we check in isKnownProperty.
59453                                 var errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget);
59454                                 // We know *exactly* where things went wrong when comparing the types.
59455                                 // Use this property as the error node as this will be more helpful in
59456                                 // reasoning about what went wrong.
59457                                 if (!errorNode)
59458                                     return { value: ts.Debug.fail() };
59459                                 if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) {
59460                                     // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal.
59461                                     // However, using an object-literal error message will be very confusing to the users so we give different a message.
59462                                     if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) {
59463                                         // Note that extraneous children (as in `<NoChild>extra</NoChild>`) don't pass this check,
59464                                         // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute.
59465                                         errorNode = prop.valueDeclaration.name;
59466                                     }
59467                                     var propName = symbolToString(prop);
59468                                     var suggestionSymbol = getSuggestedSymbolForNonexistentJSXAttribute(propName, errorTarget);
59469                                     var suggestion = suggestionSymbol ? symbolToString(suggestionSymbol) : undefined;
59470                                     if (suggestion) {
59471                                         reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(errorTarget), suggestion);
59472                                     }
59473                                     else {
59474                                         reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, propName, typeToString(errorTarget));
59475                                     }
59476                                 }
59477                                 else {
59478                                     // use the property's value declaration if the property is assigned inside the literal itself
59479                                     var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations);
59480                                     var suggestion = void 0;
59481                                     if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) {
59482                                         var propDeclaration = prop.valueDeclaration;
59483                                         ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike);
59484                                         errorNode = propDeclaration;
59485                                         var name = propDeclaration.name;
59486                                         if (ts.isIdentifier(name)) {
59487                                             suggestion = getSuggestionForNonexistentProperty(name, errorTarget);
59488                                         }
59489                                     }
59490                                     if (suggestion !== undefined) {
59491                                         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);
59492                                     }
59493                                     else {
59494                                         reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget));
59495                                     }
59496                                 }
59497                             }
59498                             return { value: true };
59499                         }
59500                         if (checkTypes && !isRelatedTo(getTypeOfSymbol(prop), getTypeOfPropertyInTypes(checkTypes, prop.escapedName), reportErrors)) {
59501                             if (reportErrors) {
59502                                 reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(prop));
59503                             }
59504                             return { value: true };
59505                         }
59506                     }
59507                 };
59508                 for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
59509                     var prop = _a[_i];
59510                     var state_5 = _loop_16(prop);
59511                     if (typeof state_5 === "object")
59512                         return state_5.value;
59513                 }
59514                 return false;
59515             }
59516             function shouldCheckAsExcessProperty(prop, container) {
59517                 return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration;
59518             }
59519             function eachTypeRelatedToSomeType(source, target) {
59520                 var result = -1 /* True */;
59521                 var sourceTypes = source.types;
59522                 for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) {
59523                     var sourceType = sourceTypes_1[_i];
59524                     var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false);
59525                     if (!related) {
59526                         return 0 /* False */;
59527                     }
59528                     result &= related;
59529                 }
59530                 return result;
59531             }
59532             function typeRelatedToSomeType(source, target, reportErrors) {
59533                 var targetTypes = target.types;
59534                 if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) {
59535                     return -1 /* True */;
59536                 }
59537                 for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
59538                     var type = targetTypes_1[_i];
59539                     var related = isRelatedTo(source, type, /*reportErrors*/ false);
59540                     if (related) {
59541                         return related;
59542                     }
59543                 }
59544                 if (reportErrors) {
59545                     var bestMatchingType = getBestMatchingType(source, target, isRelatedTo);
59546                     isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
59547                 }
59548                 return 0 /* False */;
59549             }
59550             function typeRelatedToEachType(source, target, reportErrors, intersectionState) {
59551                 var result = -1 /* True */;
59552                 var targetTypes = target.types;
59553                 for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) {
59554                     var targetType = targetTypes_2[_i];
59555                     var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, intersectionState);
59556                     if (!related) {
59557                         return 0 /* False */;
59558                     }
59559                     result &= related;
59560                 }
59561                 return result;
59562             }
59563             function someTypeRelatedToType(source, target, reportErrors, intersectionState) {
59564                 var sourceTypes = source.types;
59565                 if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) {
59566                     return -1 /* True */;
59567                 }
59568                 var len = sourceTypes.length;
59569                 for (var i = 0; i < len; i++) {
59570                     var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, intersectionState);
59571                     if (related) {
59572                         return related;
59573                     }
59574                 }
59575                 return 0 /* False */;
59576             }
59577             function getUndefinedStrippedTargetIfNeeded(source, target) {
59578                 // As a builtin type, `undefined` is a very low type ID - making it almsot always first, making this a very fast check to see
59579                 // if we need to strip `undefined` from the target
59580                 if (source.flags & 1048576 /* Union */ && target.flags & 1048576 /* Union */ &&
59581                     !(source.types[0].flags & 32768 /* Undefined */) && target.types[0].flags & 32768 /* Undefined */) {
59582                     return extractTypesOfKind(target, ~32768 /* Undefined */);
59583                 }
59584                 return target;
59585             }
59586             function eachTypeRelatedToType(source, target, reportErrors, intersectionState) {
59587                 var result = -1 /* True */;
59588                 var sourceTypes = source.types;
59589                 // We strip `undefined` from the target if the `source` trivially doesn't contain it for our correspondence-checking fastpath
59590                 // since `undefined` is frequently added by optionality and would otherwise spoil a potentially useful correspondence
59591                 var undefinedStrippedTarget = getUndefinedStrippedTargetIfNeeded(source, target);
59592                 for (var i = 0; i < sourceTypes.length; i++) {
59593                     var sourceType = sourceTypes[i];
59594                     if (undefinedStrippedTarget.flags & 1048576 /* Union */ && sourceTypes.length >= undefinedStrippedTarget.types.length && sourceTypes.length % undefinedStrippedTarget.types.length === 0) {
59595                         // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison
59596                         // such unions will have identical lengths, and their corresponding elements will match up. Another common scenario is where a large
59597                         // union has a union of objects intersected with it. In such cases, if the input was, eg `("a" | "b" | "c") & (string | boolean | {} | {whatever})`,
59598                         // the result will have the structure `"a" | "b" | "c" | "a" & {} | "b" & {} | "c" & {} | "a" & {whatever} | "b" & {whatever} | "c" & {whatever}`
59599                         // - 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
59600                         var related_1 = isRelatedTo(sourceType, undefinedStrippedTarget.types[i % undefinedStrippedTarget.types.length], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState);
59601                         if (related_1) {
59602                             result &= related_1;
59603                             continue;
59604                         }
59605                     }
59606                     var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState);
59607                     if (!related) {
59608                         return 0 /* False */;
59609                     }
59610                     result &= related;
59611                 }
59612                 return result;
59613             }
59614             function typeArgumentsRelatedTo(sources, targets, variances, reportErrors, intersectionState) {
59615                 if (sources === void 0) { sources = ts.emptyArray; }
59616                 if (targets === void 0) { targets = ts.emptyArray; }
59617                 if (variances === void 0) { variances = ts.emptyArray; }
59618                 if (sources.length !== targets.length && relation === identityRelation) {
59619                     return 0 /* False */;
59620                 }
59621                 var length = sources.length <= targets.length ? sources.length : targets.length;
59622                 var result = -1 /* True */;
59623                 for (var i = 0; i < length; i++) {
59624                     // When variance information isn't available we default to covariance. This happens
59625                     // in the process of computing variance information for recursive types and when
59626                     // comparing 'this' type arguments.
59627                     var varianceFlags = i < variances.length ? variances[i] : 1 /* Covariant */;
59628                     var variance = varianceFlags & 7 /* VarianceMask */;
59629                     // We ignore arguments for independent type parameters (because they're never witnessed).
59630                     if (variance !== 4 /* Independent */) {
59631                         var s = sources[i];
59632                         var t = targets[i];
59633                         var related = -1 /* True */;
59634                         if (varianceFlags & 8 /* Unmeasurable */) {
59635                             // Even an `Unmeasurable` variance works out without a structural check if the source and target are _identical_.
59636                             // We can't simply assume invariance, because `Unmeasurable` marks nonlinear relations, for example, a relation tained by
59637                             // the `-?` modifier in a mapped type (where, no matter how the inputs are related, the outputs still might not be)
59638                             related = relation === identityRelation ? isRelatedTo(s, t, /*reportErrors*/ false) : compareTypesIdentical(s, t);
59639                         }
59640                         else if (variance === 1 /* Covariant */) {
59641                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
59642                         }
59643                         else if (variance === 2 /* Contravariant */) {
59644                             related = isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
59645                         }
59646                         else if (variance === 3 /* Bivariant */) {
59647                             // In the bivariant case we first compare contravariantly without reporting
59648                             // errors. Then, if that doesn't succeed, we compare covariantly with error
59649                             // reporting. Thus, error elaboration will be based on the the covariant check,
59650                             // which is generally easier to reason about.
59651                             related = isRelatedTo(t, s, /*reportErrors*/ false);
59652                             if (!related) {
59653                                 related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
59654                             }
59655                         }
59656                         else {
59657                             // In the invariant case we first compare covariantly, and only when that
59658                             // succeeds do we proceed to compare contravariantly. Thus, error elaboration
59659                             // will typically be based on the covariant check.
59660                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
59661                             if (related) {
59662                                 related &= isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
59663                             }
59664                         }
59665                         if (!related) {
59666                             return 0 /* False */;
59667                         }
59668                         result &= related;
59669                     }
59670                 }
59671                 return result;
59672             }
59673             // Determine if possibly recursive types are related. First, check if the result is already available in the global cache.
59674             // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
59675             // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
59676             // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
59677             // and issue an error. Otherwise, actually compare the structure of the two types.
59678             function recursiveTypeRelatedTo(source, target, reportErrors, intersectionState) {
59679                 if (overflow) {
59680                     return 0 /* False */;
59681                 }
59682                 var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 16 /* InPropertyCheck */ : 0), relation);
59683                 var entry = relation.get(id);
59684                 if (entry !== undefined) {
59685                     if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) {
59686                         // We are elaborating errors and the cached result is an unreported failure. The result will be reported
59687                         // as a failure, and should be updated as a reported failure by the bottom of this function.
59688                     }
59689                     else {
59690                         if (outofbandVarianceMarkerHandler) {
59691                             // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component
59692                             var saved = entry & 24 /* ReportsMask */;
59693                             if (saved & 8 /* ReportsUnmeasurable */) {
59694                                 instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers));
59695                             }
59696                             if (saved & 16 /* ReportsUnreliable */) {
59697                                 instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers));
59698                             }
59699                         }
59700                         return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
59701                     }
59702                 }
59703                 if (!maybeKeys) {
59704                     maybeKeys = [];
59705                     sourceStack = [];
59706                     targetStack = [];
59707                 }
59708                 else {
59709                     for (var i = 0; i < maybeCount; i++) {
59710                         // If source and target are already being compared, consider them related with assumptions
59711                         if (id === maybeKeys[i]) {
59712                             return 3 /* Maybe */;
59713                         }
59714                     }
59715                     if (depth === 100) {
59716                         overflow = true;
59717                         return 0 /* False */;
59718                     }
59719                 }
59720                 var maybeStart = maybeCount;
59721                 maybeKeys[maybeCount] = id;
59722                 maybeCount++;
59723                 sourceStack[depth] = source;
59724                 targetStack[depth] = target;
59725                 depth++;
59726                 var saveExpandingFlags = expandingFlags;
59727                 if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth))
59728                     expandingFlags |= 1 /* Source */;
59729                 if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth))
59730                     expandingFlags |= 2 /* Target */;
59731                 var originalHandler;
59732                 var propagatingVarianceFlags = 0;
59733                 if (outofbandVarianceMarkerHandler) {
59734                     originalHandler = outofbandVarianceMarkerHandler;
59735                     outofbandVarianceMarkerHandler = function (onlyUnreliable) {
59736                         propagatingVarianceFlags |= onlyUnreliable ? 16 /* ReportsUnreliable */ : 8 /* ReportsUnmeasurable */;
59737                         return originalHandler(onlyUnreliable);
59738                     };
59739                 }
59740                 if (expandingFlags === 3 /* Both */) {
59741                     ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "recursiveTypeRelatedTo_DepthLimit", {
59742                         sourceId: source.id,
59743                         sourceIdStack: sourceStack.map(function (t) { return t.id; }),
59744                         targetId: target.id,
59745                         targetIdStack: targetStack.map(function (t) { return t.id; }),
59746                         depth: depth,
59747                     });
59748                 }
59749                 var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, intersectionState) : 3 /* Maybe */;
59750                 if (outofbandVarianceMarkerHandler) {
59751                     outofbandVarianceMarkerHandler = originalHandler;
59752                 }
59753                 expandingFlags = saveExpandingFlags;
59754                 depth--;
59755                 if (result) {
59756                     if (result === -1 /* True */ || depth === 0) {
59757                         if (result === -1 /* True */ || result === 3 /* Maybe */) {
59758                             // If result is definitely true, record all maybe keys as having succeeded. Also, record Ternary.Maybe
59759                             // results as having succeeded once we reach depth 0, but never record Ternary.Unknown results.
59760                             for (var i = maybeStart; i < maybeCount; i++) {
59761                                 relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags);
59762                             }
59763                         }
59764                         maybeCount = maybeStart;
59765                     }
59766                 }
59767                 else {
59768                     // A false result goes straight into global cache (when something is false under
59769                     // assumptions it will also be false without assumptions)
59770                     relation.set(id, (reportErrors ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags);
59771                     maybeCount = maybeStart;
59772                 }
59773                 return result;
59774             }
59775             function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) {
59776                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("checkTypes" /* CheckTypes */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id });
59777                 var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState);
59778                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
59779                 return result;
59780             }
59781             function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) {
59782                 if (intersectionState & 4 /* PropertyCheck */) {
59783                     return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */);
59784                 }
59785                 if (intersectionState & 8 /* UnionIntersectionCheck */) {
59786                     // Note that these checks are specifically ordered to produce correct results. In particular,
59787                     // we need to deconstruct unions before intersections (because unions are always at the top),
59788                     // and we need to handle "each" relations before "some" relations for the same kind of type.
59789                     if (source.flags & 1048576 /* Union */) {
59790                         return relation === comparableRelation ?
59791                             someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & ~8 /* UnionIntersectionCheck */) :
59792                             eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState & ~8 /* UnionIntersectionCheck */);
59793                     }
59794                     if (target.flags & 1048576 /* Union */) {
59795                         return typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
59796                     }
59797                     if (target.flags & 2097152 /* Intersection */) {
59798                         return typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
59799                     }
59800                     // Source is an intersection. Check to see if any constituents of the intersection are immediately related
59801                     // to the target.
59802                     //
59803                     // Don't report errors though. Checking whether a constituent is related to the source is not actually
59804                     // useful and leads to some confusing error messages. Instead it is better to let the below checks
59805                     // take care of this, or to not elaborate at all. For instance,
59806                     //
59807                     //    - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
59808                     //
59809                     //    - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
59810                     //          than to report that 'D' is not assignable to 'A' or 'B'.
59811                     //
59812                     //    - For a primitive type or type parameter (such as 'number = A & B') there is no point in
59813                     //          breaking the intersection apart.
59814                     return someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
59815                 }
59816                 var flags = source.flags & target.flags;
59817                 if (relation === identityRelation && !(flags & 524288 /* Object */)) {
59818                     if (flags & 4194304 /* Index */) {
59819                         return isRelatedTo(source.type, target.type, /*reportErrors*/ false);
59820                     }
59821                     var result_7 = 0 /* False */;
59822                     if (flags & 8388608 /* IndexedAccess */) {
59823                         if (result_7 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) {
59824                             if (result_7 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) {
59825                                 return result_7;
59826                             }
59827                         }
59828                     }
59829                     if (flags & 16777216 /* Conditional */) {
59830                         if (source.root.isDistributive === target.root.isDistributive) {
59831                             if (result_7 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
59832                                 if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
59833                                     if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
59834                                         if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
59835                                             return result_7;
59836                                         }
59837                                     }
59838                                 }
59839                             }
59840                         }
59841                     }
59842                     if (flags & 33554432 /* Substitution */) {
59843                         return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false);
59844                     }
59845                     return 0 /* False */;
59846                 }
59847                 var result;
59848                 var originalErrorInfo;
59849                 var varianceCheckFailed = false;
59850                 var saveErrorInfo = captureErrorCalculationState();
59851                 // We limit alias variance probing to only object and conditional types since their alias behavior
59852                 // is more predictable than other, interned types, which may or may not have an alias depending on
59853                 // the order in which things were checked.
59854                 if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol &&
59855                     source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
59856                     !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
59857                     var variances = getAliasVariances(source.aliasSymbol);
59858                     if (variances === ts.emptyArray) {
59859                         return 1 /* Unknown */;
59860                     }
59861                     var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState);
59862                     if (varianceResult !== undefined) {
59863                         return varianceResult;
59864                     }
59865                 }
59866                 // 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],
59867                 // and U is assignable to [...T] when U is constrained to a mutable array or tuple type.
59868                 if (isSingleElementGenericTupleType(source) && !source.target.readonly && (result = isRelatedTo(getTypeArguments(source)[0], target)) ||
59869                     isSingleElementGenericTupleType(target) && (target.target.readonly || isMutableArrayOrTuple(getBaseConstraintOfType(source) || source)) && (result = isRelatedTo(source, getTypeArguments(target)[0]))) {
59870                     return result;
59871                 }
59872                 if (target.flags & 262144 /* TypeParameter */) {
59873                     // 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].
59874                     if (ts.getObjectFlags(source) & 32 /* Mapped */ && !source.declaration.nameType && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) {
59875                         if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) {
59876                             var templateType = getTemplateTypeFromMappedType(source);
59877                             var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
59878                             if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) {
59879                                 return result;
59880                             }
59881                         }
59882                     }
59883                 }
59884                 else if (target.flags & 4194304 /* Index */) {
59885                     var targetType = target.type;
59886                     // A keyof S is related to a keyof T if T is related to S.
59887                     if (source.flags & 4194304 /* Index */) {
59888                         if (result = isRelatedTo(targetType, source.type, /*reportErrors*/ false)) {
59889                             return result;
59890                         }
59891                     }
59892                     if (isTupleType(targetType)) {
59893                         // An index type can have a tuple type target when the tuple type contains variadic elements.
59894                         // Check if the source is related to the known keys of the tuple type.
59895                         if (result = isRelatedTo(source, getKnownKeysOfTupleType(targetType), reportErrors)) {
59896                             return result;
59897                         }
59898                     }
59899                     else {
59900                         // A type S is assignable to keyof T if S is assignable to keyof C, where C is the
59901                         // simplified form of T or, if T doesn't simplify, the constraint of T.
59902                         var constraint = getSimplifiedTypeOrConstraint(targetType);
59903                         if (constraint) {
59904                             // We require Ternary.True here such that circular constraints don't cause
59905                             // false positives. For example, given 'T extends { [K in keyof T]: string }',
59906                             // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
59907                             // related to other types.
59908                             if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) {
59909                                 return -1 /* True */;
59910                             }
59911                         }
59912                     }
59913                 }
59914                 else if (target.flags & 8388608 /* IndexedAccess */) {
59915                     // A type S is related to a type T[K] if S is related to C, where C is the base
59916                     // constraint of T[K] for writing.
59917                     if (relation === assignableRelation || relation === comparableRelation) {
59918                         var objectType = target.objectType;
59919                         var indexType = target.indexType;
59920                         var baseObjectType = getBaseConstraintOfType(objectType) || objectType;
59921                         var baseIndexType = getBaseConstraintOfType(indexType) || indexType;
59922                         if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) {
59923                             var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0);
59924                             var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, target.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags);
59925                             if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) {
59926                                 return result;
59927                             }
59928                         }
59929                     }
59930                 }
59931                 else if (isGenericMappedType(target) && !target.declaration.nameType) {
59932                     // A source type T is related to a target type { [P in X]: T[P] }
59933                     var template = getTemplateTypeFromMappedType(target);
59934                     var modifiers = getMappedTypeModifiers(target);
59935                     if (!(modifiers & 8 /* ExcludeOptional */)) {
59936                         if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source &&
59937                             template.indexType === getTypeParameterFromMappedType(target)) {
59938                             return -1 /* True */;
59939                         }
59940                         if (!isGenericMappedType(source)) {
59941                             var targetConstraint = getConstraintTypeFromMappedType(target);
59942                             var sourceKeys = getIndexType(source, /*stringsOnly*/ undefined, /*noIndexSignatures*/ true);
59943                             var includeOptional = modifiers & 4 /* IncludeOptional */;
59944                             var filteredByApplicability = includeOptional ? intersectTypes(targetConstraint, sourceKeys) : undefined;
59945                             // A source type T is related to a target type { [P in Q]: X } if Q is related to keyof T and T[Q] is related to X.
59946                             // A source type T is related to a target type { [P in Q]?: X } if some constituent Q' of Q is related to keyof T and T[Q'] is related to X.
59947                             if (includeOptional
59948                                 ? !(filteredByApplicability.flags & 131072 /* Never */)
59949                                 : isRelatedTo(targetConstraint, sourceKeys)) {
59950                                 var templateType = getTemplateTypeFromMappedType(target);
59951                                 var typeParameter = getTypeParameterFromMappedType(target);
59952                                 // Fastpath: When the template has the form Obj[P] where P is the mapped type parameter, directly compare `source` with `Obj`
59953                                 // to avoid creating the (potentially very large) number of new intermediate types made by manufacturing `source[P]`
59954                                 var nonNullComponent = extractTypesOfKind(templateType, ~98304 /* Nullable */);
59955                                 if (nonNullComponent.flags & 8388608 /* IndexedAccess */ && nonNullComponent.indexType === typeParameter) {
59956                                     if (result = isRelatedTo(source, nonNullComponent.objectType, reportErrors)) {
59957                                         return result;
59958                                     }
59959                                 }
59960                                 else {
59961                                     var indexingType = filteredByApplicability ? getIntersectionType([filteredByApplicability, typeParameter]) : typeParameter;
59962                                     var indexedAccessType = getIndexedAccessType(source, indexingType);
59963                                     if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
59964                                         return result;
59965                                     }
59966                                 }
59967                             }
59968                             originalErrorInfo = errorInfo;
59969                             resetErrorInfo(saveErrorInfo);
59970                         }
59971                     }
59972                 }
59973                 else if (target.flags & 134217728 /* TemplateLiteral */ && source.flags & 128 /* StringLiteral */) {
59974                     if (isPatternLiteralType(target)) {
59975                         // match all non-`string` segments
59976                         var result_8 = inferLiteralsFromTemplateLiteralType(source, target);
59977                         if (result_8 && ts.every(result_8, function (r, i) { return isStringLiteralTypeValueParsableAsType(r, target.types[i]); })) {
59978                             return -1 /* True */;
59979                         }
59980                     }
59981                 }
59982                 if (source.flags & 8650752 /* TypeVariable */) {
59983                     if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
59984                         // A type S[K] is related to a type T[J] if S is related to T and K is related to J.
59985                         if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
59986                             result &= isRelatedTo(source.indexType, target.indexType, reportErrors);
59987                         }
59988                         if (result) {
59989                             resetErrorInfo(saveErrorInfo);
59990                             return result;
59991                         }
59992                     }
59993                     else {
59994                         var constraint = getConstraintOfType(source);
59995                         if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
59996                             // A type variable with no constraint is not related to the non-primitive object type.
59997                             if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) {
59998                                 resetErrorInfo(saveErrorInfo);
59999                                 return result;
60000                             }
60001                         }
60002                         // 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
60003                         else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
60004                             resetErrorInfo(saveErrorInfo);
60005                             return result;
60006                         }
60007                         // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example
60008                         else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) {
60009                             resetErrorInfo(saveErrorInfo);
60010                             return result;
60011                         }
60012                     }
60013                 }
60014                 else if (source.flags & 4194304 /* Index */) {
60015                     if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) {
60016                         resetErrorInfo(saveErrorInfo);
60017                         return result;
60018                     }
60019                 }
60020                 else if (source.flags & 134217728 /* TemplateLiteral */) {
60021                     if (target.flags & 134217728 /* TemplateLiteral */ &&
60022                         source.texts.length === target.texts.length &&
60023                         source.types.length === target.types.length &&
60024                         ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) &&
60025                         ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) {
60026                         return -1 /* True */;
60027                     }
60028                     var constraint = getBaseConstraintOfType(source);
60029                     if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, reportErrors))) {
60030                         resetErrorInfo(saveErrorInfo);
60031                         return result;
60032                     }
60033                 }
60034                 else if (source.flags & 268435456 /* StringMapping */) {
60035                     if (target.flags & 268435456 /* StringMapping */ && source.symbol === target.symbol) {
60036                         if (result = isRelatedTo(source.type, target.type, reportErrors)) {
60037                             resetErrorInfo(saveErrorInfo);
60038                             return result;
60039                         }
60040                     }
60041                     else {
60042                         var constraint = getBaseConstraintOfType(source);
60043                         if (constraint && (result = isRelatedTo(constraint, target, reportErrors))) {
60044                             resetErrorInfo(saveErrorInfo);
60045                             return result;
60046                         }
60047                     }
60048                 }
60049                 else if (source.flags & 16777216 /* Conditional */) {
60050                     if (target.flags & 16777216 /* Conditional */) {
60051                         // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
60052                         // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
60053                         // and Y1 is related to Y2.
60054                         var sourceParams = source.root.inferTypeParameters;
60055                         var sourceExtends = source.extendsType;
60056                         var mapper = void 0;
60057                         if (sourceParams) {
60058                             // If the source has infer type parameters, we instantiate them in the context of the target
60059                             var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo);
60060                             inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 /* NoConstraints */ | 512 /* AlwaysStrict */);
60061                             sourceExtends = instantiateType(sourceExtends, ctx.mapper);
60062                             mapper = ctx.mapper;
60063                         }
60064                         if (isTypeIdenticalTo(sourceExtends, target.extendsType) &&
60065                             (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
60066                             if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), reportErrors)) {
60067                                 result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
60068                             }
60069                             if (result) {
60070                                 resetErrorInfo(saveErrorInfo);
60071                                 return result;
60072                             }
60073                         }
60074                     }
60075                     else {
60076                         // conditionals aren't related to one another via distributive constraint as it is much too inaccurate and allows way
60077                         // more assignments than are desirable (since it maps the source check type to its constraint, it loses information)
60078                         var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
60079                         if (distributiveConstraint) {
60080                             if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
60081                                 resetErrorInfo(saveErrorInfo);
60082                                 return result;
60083                             }
60084                         }
60085                     }
60086                     // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O`
60087                     // when `O` is a conditional (`never` is trivially aissgnable to `O`, as is `O`!).
60088                     var defaultConstraint = getDefaultConstraintOfConditionalType(source);
60089                     if (defaultConstraint) {
60090                         if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
60091                             resetErrorInfo(saveErrorInfo);
60092                             return result;
60093                         }
60094                     }
60095                 }
60096                 else {
60097                     // An empty object type is related to any mapped type that includes a '?' modifier.
60098                     if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target) && isEmptyObjectType(source)) {
60099                         return -1 /* True */;
60100                     }
60101                     if (isGenericMappedType(target)) {
60102                         if (isGenericMappedType(source)) {
60103                             if (result = mappedTypeRelatedTo(source, target, reportErrors)) {
60104                                 resetErrorInfo(saveErrorInfo);
60105                                 return result;
60106                             }
60107                         }
60108                         return 0 /* False */;
60109                     }
60110                     var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */);
60111                     if (relation !== identityRelation) {
60112                         source = getApparentType(source);
60113                     }
60114                     else if (isGenericMappedType(source)) {
60115                         return 0 /* False */;
60116                     }
60117                     if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
60118                         !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) {
60119                         // We have type references to the same generic type, and the type references are not marker
60120                         // type references (which are intended by be compared structurally). Obtain the variance
60121                         // information for the type parameters and relate the type arguments accordingly.
60122                         var variances = getVariances(source.target);
60123                         // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This
60124                         // effectively means we measure variance only from type parameter occurrences that aren't nested in
60125                         // recursive instantiations of the generic type.
60126                         if (variances === ts.emptyArray) {
60127                             return 1 /* Unknown */;
60128                         }
60129                         var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState);
60130                         if (varianceResult !== undefined) {
60131                             return varianceResult;
60132                         }
60133                     }
60134                     else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
60135                         if (relation !== identityRelation) {
60136                             return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
60137                         }
60138                         else {
60139                             // By flags alone, we know that the `target` is a readonly array while the source is a normal array or tuple
60140                             // or `target` is an array and source is a tuple - in both cases the types cannot be identical, by construction
60141                             return 0 /* False */;
60142                         }
60143                     }
60144                     // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
60145                     // and not `{} <- fresh({}) <- {[idx: string]: any}`
60146                     else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
60147                         return 0 /* False */;
60148                     }
60149                     // Even if relationship doesn't hold for unions, intersections, or generic type references,
60150                     // it may hold in a structural comparison.
60151                     // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
60152                     // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
60153                     // relates to X. Thus, we include intersection types on the source side here.
60154                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) {
60155                         // Report structural errors only if we haven't reported any errors yet
60156                         var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive;
60157                         result = propertiesRelatedTo(source, target, reportStructuralErrors, /*excludedProperties*/ undefined, intersectionState);
60158                         if (result) {
60159                             result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
60160                             if (result) {
60161                                 result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
60162                                 if (result) {
60163                                     result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
60164                                     if (result) {
60165                                         result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
60166                                     }
60167                                 }
60168                             }
60169                         }
60170                         if (varianceCheckFailed && result) {
60171                             errorInfo = originalErrorInfo || errorInfo || saveErrorInfo.errorInfo; // Use variance error (there is no structural one) and return false
60172                         }
60173                         else if (result) {
60174                             return result;
60175                         }
60176                     }
60177                     // If S is an object type and T is a discriminated union, S may be related to T if
60178                     // there exists a constituent of T for every combination of the discriminants of S
60179                     // with respect to T. We do not report errors here, as we will use the existing
60180                     // error result from checking each constituent of the union.
60181                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) {
60182                         var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */);
60183                         if (objectOnlyTarget.flags & 1048576 /* Union */) {
60184                             var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget);
60185                             if (result_9) {
60186                                 return result_9;
60187                             }
60188                         }
60189                     }
60190                 }
60191                 return 0 /* False */;
60192                 function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) {
60193                     if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) {
60194                         return result;
60195                     }
60196                     if (ts.some(variances, function (v) { return !!(v & 24 /* AllowsStructuralFallback */); })) {
60197                         // If some type parameter was `Unmeasurable` or `Unreliable`, and we couldn't pass by assuming it was identical, then we
60198                         // have to allow a structural fallback check
60199                         // We elide the variance-based error elaborations, since those might not be too helpful, since we'll potentially
60200                         // be assuming identity of the type parameter.
60201                         originalErrorInfo = undefined;
60202                         resetErrorInfo(saveErrorInfo);
60203                         return undefined;
60204                     }
60205                     var allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances);
60206                     varianceCheckFailed = !allowStructuralFallback;
60207                     // The type arguments did not relate appropriately, but it may be because we have no variance
60208                     // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
60209                     // arguments). It might also be the case that the target type has a 'void' type argument for
60210                     // a covariant type parameter that is only used in return positions within the generic type
60211                     // (in which case any type argument is permitted on the source side). In those cases we proceed
60212                     // with a structural comparison. Otherwise, we know for certain the instantiations aren't
60213                     // related and we can return here.
60214                     if (variances !== ts.emptyArray && !allowStructuralFallback) {
60215                         // In some cases generic types that are covariant in regular type checking mode become
60216                         // invariant in --strictFunctionTypes mode because one or more type parameters are used in
60217                         // both co- and contravariant positions. In order to make it easier to diagnose *why* such
60218                         // types are invariant, if any of the type parameters are invariant we reset the reported
60219                         // errors and instead force a structural comparison (which will include elaborations that
60220                         // reveal the reason).
60221                         // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
60222                         // we can return `False` early here to skip calculating the structural error message we don't need.
60223                         if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return (v & 7 /* VarianceMask */) === 0 /* Invariant */; }))) {
60224                             return 0 /* False */;
60225                         }
60226                         // We remember the original error information so we can restore it in case the structural
60227                         // comparison unexpectedly succeeds. This can happen when the structural comparison result
60228                         // is a Ternary.Maybe for example caused by the recursion depth limiter.
60229                         originalErrorInfo = errorInfo;
60230                         resetErrorInfo(saveErrorInfo);
60231                     }
60232                 }
60233             }
60234             function reportUnmeasurableMarkers(p) {
60235                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
60236                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false);
60237                 }
60238                 return p;
60239             }
60240             function reportUnreliableMarkers(p) {
60241                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
60242                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true);
60243                 }
60244                 return p;
60245             }
60246             // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
60247             // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
60248             // that S and T are contra-variant whereas X and Y are co-variant.
60249             function mappedTypeRelatedTo(source, target, reportErrors) {
60250                 var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
60251                     getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
60252                 if (modifiersRelated) {
60253                     var result_10;
60254                     var targetConstraint = getConstraintTypeFromMappedType(target);
60255                     var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers));
60256                     if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) {
60257                         var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
60258                         if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) {
60259                             return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
60260                         }
60261                     }
60262                 }
60263                 return 0 /* False */;
60264             }
60265             function typeRelatedToDiscriminatedType(source, target) {
60266                 // 1. Generate the combinations of discriminant properties & types 'source' can satisfy.
60267                 //    a. If the number of combinations is above a set limit, the comparison is too complex.
60268                 // 2. Filter 'target' to the subset of types whose discriminants exist in the matrix.
60269                 //    a. If 'target' does not satisfy all discriminants in the matrix, 'source' is not related.
60270                 // 3. For each type in the filtered 'target', determine if all non-discriminant properties of
60271                 //    'target' are related to a property in 'source'.
60272                 //
60273                 // NOTE: See ~/tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithDiscriminatedUnion.ts
60274                 //       for examples.
60275                 var sourceProperties = getPropertiesOfType(source);
60276                 var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
60277                 if (!sourcePropertiesFiltered)
60278                     return 0 /* False */;
60279                 // Though we could compute the number of combinations as we generate
60280                 // the matrix, this would incur additional memory overhead due to
60281                 // array allocations. To reduce this overhead, we first compute
60282                 // the number of combinations to ensure we will not surpass our
60283                 // fixed limit before incurring the cost of any allocations:
60284                 var numCombinations = 1;
60285                 for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) {
60286                     var sourceProperty = sourcePropertiesFiltered_1[_i];
60287                     numCombinations *= countTypes(getTypeOfSymbol(sourceProperty));
60288                     if (numCombinations > 25) {
60289                         // We've reached the complexity limit.
60290                         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations });
60291                         return 0 /* False */;
60292                     }
60293                 }
60294                 // Compute the set of types for each discriminant property.
60295                 var sourceDiscriminantTypes = new Array(sourcePropertiesFiltered.length);
60296                 var excludedProperties = new ts.Set();
60297                 for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
60298                     var sourceProperty = sourcePropertiesFiltered[i];
60299                     var sourcePropertyType = getTypeOfSymbol(sourceProperty);
60300                     sourceDiscriminantTypes[i] = sourcePropertyType.flags & 1048576 /* Union */
60301                         ? sourcePropertyType.types
60302                         : [sourcePropertyType];
60303                     excludedProperties.add(sourceProperty.escapedName);
60304                 }
60305                 // Match each combination of the cartesian product of discriminant properties to one or more
60306                 // constituents of 'target'. If any combination does not have a match then 'source' is not relatable.
60307                 var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes);
60308                 var matchingTypes = [];
60309                 var _loop_17 = function (combination) {
60310                     var hasMatch = false;
60311                     outer: for (var _c = 0, _d = target.types; _c < _d.length; _c++) {
60312                         var type = _d[_c];
60313                         var _loop_18 = function (i) {
60314                             var sourceProperty = sourcePropertiesFiltered[i];
60315                             var targetProperty = getPropertyOfType(type, sourceProperty.escapedName);
60316                             if (!targetProperty)
60317                                 return "continue-outer";
60318                             if (sourceProperty === targetProperty)
60319                                 return "continue";
60320                             // We compare the source property to the target in the context of a single discriminant type.
60321                             var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation);
60322                             // If the target property could not be found, or if the properties were not related,
60323                             // then this constituent is not a match.
60324                             if (!related) {
60325                                 return "continue-outer";
60326                             }
60327                         };
60328                         for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
60329                             var state_7 = _loop_18(i);
60330                             switch (state_7) {
60331                                 case "continue-outer": continue outer;
60332                             }
60333                         }
60334                         ts.pushIfUnique(matchingTypes, type, ts.equateValues);
60335                         hasMatch = true;
60336                     }
60337                     if (!hasMatch) {
60338                         return { value: 0 /* False */ };
60339                     }
60340                 };
60341                 for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) {
60342                     var combination = discriminantCombinations_1[_a];
60343                     var state_6 = _loop_17(combination);
60344                     if (typeof state_6 === "object")
60345                         return state_6.value;
60346                 }
60347                 // Compare the remaining non-discriminant properties of each match.
60348                 var result = -1 /* True */;
60349                 for (var _b = 0, matchingTypes_1 = matchingTypes; _b < matchingTypes_1.length; _b++) {
60350                     var type = matchingTypes_1[_b];
60351                     result &= propertiesRelatedTo(source, type, /*reportErrors*/ false, excludedProperties, 0 /* None */);
60352                     if (result) {
60353                         result &= signaturesRelatedTo(source, type, 0 /* Call */, /*reportStructuralErrors*/ false);
60354                         if (result) {
60355                             result &= signaturesRelatedTo(source, type, 1 /* Construct */, /*reportStructuralErrors*/ false);
60356                             if (result) {
60357                                 result &= indexTypesRelatedTo(source, type, 0 /* String */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
60358                                 // Comparing numeric index types when both `source` and `type` are tuples is unnecessary as the
60359                                 // element types should be sufficiently covered by `propertiesRelatedTo`. It also causes problems
60360                                 // with index type assignability as the types for the excluded discriminants are still included
60361                                 // in the index type.
60362                                 if (result && !(isTupleType(source) && isTupleType(type))) {
60363                                     result &= indexTypesRelatedTo(source, type, 1 /* Number */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
60364                                 }
60365                             }
60366                         }
60367                     }
60368                     if (!result) {
60369                         return result;
60370                     }
60371                 }
60372                 return result;
60373             }
60374             function excludeProperties(properties, excludedProperties) {
60375                 if (!excludedProperties || properties.length === 0)
60376                     return properties;
60377                 var result;
60378                 for (var i = 0; i < properties.length; i++) {
60379                     if (!excludedProperties.has(properties[i].escapedName)) {
60380                         if (result) {
60381                             result.push(properties[i]);
60382                         }
60383                     }
60384                     else if (!result) {
60385                         result = properties.slice(0, i);
60386                     }
60387                 }
60388                 return result || properties;
60389             }
60390             function isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) {
60391                 var targetIsOptional = strictNullChecks && !!(ts.getCheckFlags(targetProp) & 48 /* Partial */);
60392                 var source = getTypeOfSourceProperty(sourceProp);
60393                 if (ts.getCheckFlags(targetProp) & 65536 /* DeferredType */ && !getSymbolLinks(targetProp).type) {
60394                     // Rather than resolving (and normalizing) the type, relate constituent-by-constituent without performing normalization or seconadary passes
60395                     var links = getSymbolLinks(targetProp);
60396                     ts.Debug.assertIsDefined(links.deferralParent);
60397                     ts.Debug.assertIsDefined(links.deferralConstituents);
60398                     var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */);
60399                     var result_11 = unionParent ? 0 /* False */ : -1 /* True */;
60400                     var targetTypes = links.deferralConstituents;
60401                     for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) {
60402                         var targetType = targetTypes_3[_i];
60403                         var related = isRelatedTo(source, targetType, /*reportErrors*/ false, /*headMessage*/ undefined, unionParent ? 0 : 2 /* Target */);
60404                         if (!unionParent) {
60405                             if (!related) {
60406                                 // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization)
60407                                 return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
60408                             }
60409                             result_11 &= related;
60410                         }
60411                         else {
60412                             if (related) {
60413                                 return related;
60414                             }
60415                         }
60416                     }
60417                     if (unionParent && !result_11 && targetIsOptional) {
60418                         result_11 = isRelatedTo(source, undefinedType);
60419                     }
60420                     if (unionParent && !result_11 && reportErrors) {
60421                         // The easiest way to get the right errors here is to un-defer (which may be costly)
60422                         // If it turns out this is too costly too often, we can replicate the error handling logic within
60423                         // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union
60424                         // type on which to hand discriminable properties, which we are expressly trying to avoid here)
60425                         return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
60426                     }
60427                     return result_11;
60428                 }
60429                 else {
60430                     return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState);
60431                 }
60432             }
60433             function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) {
60434                 var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp);
60435                 var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp);
60436                 if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) {
60437                     if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
60438                         if (reportErrors) {
60439                             if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) {
60440                                 reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp));
60441                             }
60442                             else {
60443                                 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));
60444                             }
60445                         }
60446                         return 0 /* False */;
60447                     }
60448                 }
60449                 else if (targetPropFlags & 16 /* Protected */) {
60450                     if (!isValidOverrideOf(sourceProp, targetProp)) {
60451                         if (reportErrors) {
60452                             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));
60453                         }
60454                         return 0 /* False */;
60455                     }
60456                 }
60457                 else if (sourcePropFlags & 16 /* Protected */) {
60458                     if (reportErrors) {
60459                         reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
60460                     }
60461                     return 0 /* False */;
60462                 }
60463                 // If the target comes from a partial union prop, allow `undefined` in the target type
60464                 var related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState);
60465                 if (!related) {
60466                     if (reportErrors) {
60467                         reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
60468                     }
60469                     return 0 /* False */;
60470                 }
60471                 // When checking for comparability, be more lenient with optional properties.
60472                 if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) {
60473                     // TypeScript 1.0 spec (April 2014): 3.8.3
60474                     // S is a subtype of a type T, and T is a supertype of S if ...
60475                     // S' and T are object types and, for each member M in T..
60476                     // M is a property and S' contains a property N where
60477                     // if M is a required property, N is also a required property
60478                     // (M - property in T)
60479                     // (N - property in S)
60480                     if (reportErrors) {
60481                         reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
60482                     }
60483                     return 0 /* False */;
60484                 }
60485                 return related;
60486             }
60487             function reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties) {
60488                 var shouldSkipElaboration = false;
60489                 // give specific error in case where private names have the same description
60490                 if (unmatchedProperty.valueDeclaration
60491                     && ts.isNamedDeclaration(unmatchedProperty.valueDeclaration)
60492                     && ts.isPrivateIdentifier(unmatchedProperty.valueDeclaration.name)
60493                     && source.symbol
60494                     && source.symbol.flags & 32 /* Class */) {
60495                     var privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText;
60496                     var symbolTableKey = ts.getSymbolNameForPrivateIdentifier(source.symbol, privateIdentifierDescription);
60497                     if (symbolTableKey && getPropertyOfType(source, symbolTableKey)) {
60498                         var sourceName = ts.factory.getDeclarationName(source.symbol.valueDeclaration);
60499                         var targetName = ts.factory.getDeclarationName(target.symbol.valueDeclaration);
60500                         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));
60501                         return;
60502                     }
60503                 }
60504                 var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false));
60505                 if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code &&
60506                     headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) {
60507                     shouldSkipElaboration = true; // Retain top-level error for interface implementing issues, otherwise omit it
60508                 }
60509                 if (props.length === 1) {
60510                     var propName = symbolToString(unmatchedProperty);
60511                     reportError.apply(void 0, __spreadArray([ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName], getTypeNamesForErrorDisplay(source, target)));
60512                     if (ts.length(unmatchedProperty.declarations)) {
60513                         associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName));
60514                     }
60515                     if (shouldSkipElaboration && errorInfo) {
60516                         overrideNextErrorInfo++;
60517                     }
60518                 }
60519                 else if (tryElaborateArrayLikeErrors(source, target, /*reportErrors*/ false)) {
60520                     if (props.length > 5) { // arbitrary cutoff for too-long list form
60521                         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);
60522                     }
60523                     else {
60524                         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(", "));
60525                     }
60526                     if (shouldSkipElaboration && errorInfo) {
60527                         overrideNextErrorInfo++;
60528                     }
60529                 }
60530                 // No array like or unmatched property error - just issue top level error (errorInfo = undefined)
60531             }
60532             function propertiesRelatedTo(source, target, reportErrors, excludedProperties, intersectionState) {
60533                 if (relation === identityRelation) {
60534                     return propertiesIdenticalTo(source, target, excludedProperties);
60535                 }
60536                 var result = -1 /* True */;
60537                 if (isTupleType(target)) {
60538                     if (isArrayType(source) || isTupleType(source)) {
60539                         if (!target.target.readonly && (isReadonlyArrayType(source) || isTupleType(source) && source.target.readonly)) {
60540                             return 0 /* False */;
60541                         }
60542                         var sourceArity = getTypeReferenceArity(source);
60543                         var targetArity = getTypeReferenceArity(target);
60544                         var sourceRestFlag = isTupleType(source) ? source.target.combinedFlags & 4 /* Rest */ : 4 /* Rest */;
60545                         var targetRestFlag = target.target.combinedFlags & 4 /* Rest */;
60546                         var sourceMinLength = isTupleType(source) ? source.target.minLength : 0;
60547                         var targetMinLength = target.target.minLength;
60548                         if (!sourceRestFlag && sourceArity < targetMinLength) {
60549                             if (reportErrors) {
60550                                 reportError(ts.Diagnostics.Source_has_0_element_s_but_target_requires_1, sourceArity, targetMinLength);
60551                             }
60552                             return 0 /* False */;
60553                         }
60554                         if (!targetRestFlag && targetArity < sourceMinLength) {
60555                             if (reportErrors) {
60556                                 reportError(ts.Diagnostics.Source_has_0_element_s_but_target_allows_only_1, sourceMinLength, targetArity);
60557                             }
60558                             return 0 /* False */;
60559                         }
60560                         if (!targetRestFlag && sourceRestFlag) {
60561                             if (reportErrors) {
60562                                 if (sourceMinLength < targetMinLength) {
60563                                     reportError(ts.Diagnostics.Target_requires_0_element_s_but_source_may_have_fewer, targetMinLength);
60564                                 }
60565                                 else {
60566                                     reportError(ts.Diagnostics.Target_allows_only_0_element_s_but_source_may_have_more, targetArity);
60567                                 }
60568                             }
60569                             return 0 /* False */;
60570                         }
60571                         var sourceTypeArguments = getTypeArguments(source);
60572                         var targetTypeArguments = getTypeArguments(target);
60573                         var startCount = Math.min(isTupleType(source) ? getStartElementCount(source.target, 11 /* NonRest */) : 0, getStartElementCount(target.target, 11 /* NonRest */));
60574                         var endCount = Math.min(isTupleType(source) ? getEndElementCount(source.target, 11 /* NonRest */) : 0, targetRestFlag ? getEndElementCount(target.target, 11 /* NonRest */) : 0);
60575                         var canExcludeDiscriminants = !!excludedProperties;
60576                         for (var i = 0; i < targetArity; i++) {
60577                             var sourceIndex = i < targetArity - endCount ? i : i + sourceArity - targetArity;
60578                             var sourceFlags = isTupleType(source) && (i < startCount || i >= targetArity - endCount) ? source.target.elementFlags[sourceIndex] : 4 /* Rest */;
60579                             var targetFlags = target.target.elementFlags[i];
60580                             if (targetFlags & 8 /* Variadic */ && !(sourceFlags & 8 /* Variadic */)) {
60581                                 if (reportErrors) {
60582                                     reportError(ts.Diagnostics.Source_provides_no_match_for_variadic_element_at_position_0_in_target, i);
60583                                 }
60584                                 return 0 /* False */;
60585                             }
60586                             if (sourceFlags & 8 /* Variadic */ && !(targetFlags & 12 /* Variable */)) {
60587                                 if (reportErrors) {
60588                                     reportError(ts.Diagnostics.Variadic_element_at_position_0_in_source_does_not_match_element_at_position_1_in_target, sourceIndex, i);
60589                                 }
60590                                 return 0 /* False */;
60591                             }
60592                             if (targetFlags & 1 /* Required */ && !(sourceFlags & 1 /* Required */)) {
60593                                 if (reportErrors) {
60594                                     reportError(ts.Diagnostics.Source_provides_no_match_for_required_element_at_position_0_in_target, i);
60595                                 }
60596                                 return 0 /* False */;
60597                             }
60598                             // We can only exclude discriminant properties if we have not yet encountered a variable-length element.
60599                             if (canExcludeDiscriminants) {
60600                                 if (sourceFlags & 12 /* Variable */ || targetFlags & 12 /* Variable */) {
60601                                     canExcludeDiscriminants = false;
60602                                 }
60603                                 if (canExcludeDiscriminants && (excludedProperties === null || excludedProperties === void 0 ? void 0 : excludedProperties.has(("" + i)))) {
60604                                     continue;
60605                                 }
60606                             }
60607                             var sourceType = !isTupleType(source) ? sourceTypeArguments[0] :
60608                                 i < startCount || i >= targetArity - endCount ? sourceTypeArguments[sourceIndex] :
60609                                     getElementTypeOfSliceOfTupleType(source, startCount, endCount) || neverType;
60610                             var targetType = targetTypeArguments[i];
60611                             var targetCheckType = sourceFlags & 8 /* Variadic */ && targetFlags & 4 /* Rest */ ? createArrayType(targetType) : targetType;
60612                             var related = isRelatedTo(sourceType, targetCheckType, reportErrors, /*headMessage*/ undefined, intersectionState);
60613                             if (!related) {
60614                                 if (reportErrors) {
60615                                     if (i < startCount || i >= targetArity - endCount || sourceArity - startCount - endCount === 1) {
60616                                         reportIncompatibleError(ts.Diagnostics.Type_at_position_0_in_source_is_not_compatible_with_type_at_position_1_in_target, sourceIndex, i);
60617                                     }
60618                                     else {
60619                                         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);
60620                                     }
60621                                 }
60622                                 return 0 /* False */;
60623                             }
60624                             result &= related;
60625                         }
60626                         return result;
60627                     }
60628                     if (target.target.combinedFlags & 12 /* Variable */) {
60629                         return 0 /* False */;
60630                     }
60631                 }
60632                 var requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source);
60633                 var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false);
60634                 if (unmatchedProperty) {
60635                     if (reportErrors) {
60636                         reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties);
60637                     }
60638                     return 0 /* False */;
60639                 }
60640                 if (isObjectLiteralType(target)) {
60641                     for (var _i = 0, _a = excludeProperties(getPropertiesOfType(source), excludedProperties); _i < _a.length; _i++) {
60642                         var sourceProp = _a[_i];
60643                         if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
60644                             var sourceType = getTypeOfSymbol(sourceProp);
60645                             if (!(sourceType === undefinedType || sourceType === undefinedWideningType || sourceType === optionalType)) {
60646                                 if (reportErrors) {
60647                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
60648                                 }
60649                                 return 0 /* False */;
60650                             }
60651                         }
60652                     }
60653                 }
60654                 // 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_
60655                 // from the target union, across all members
60656                 var properties = getPropertiesOfType(target);
60657                 var numericNamesOnly = isTupleType(source) && isTupleType(target);
60658                 for (var _b = 0, _c = excludeProperties(properties, excludedProperties); _b < _c.length; _b++) {
60659                     var targetProp = _c[_b];
60660                     var name = targetProp.escapedName;
60661                     if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) {
60662                         var sourceProp = getPropertyOfType(source, name);
60663                         if (sourceProp && sourceProp !== targetProp) {
60664                             var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation);
60665                             if (!related) {
60666                                 return 0 /* False */;
60667                             }
60668                             result &= related;
60669                         }
60670                     }
60671                 }
60672                 return result;
60673             }
60674             function propertiesIdenticalTo(source, target, excludedProperties) {
60675                 if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) {
60676                     return 0 /* False */;
60677                 }
60678                 var sourceProperties = excludeProperties(getPropertiesOfObjectType(source), excludedProperties);
60679                 var targetProperties = excludeProperties(getPropertiesOfObjectType(target), excludedProperties);
60680                 if (sourceProperties.length !== targetProperties.length) {
60681                     return 0 /* False */;
60682                 }
60683                 var result = -1 /* True */;
60684                 for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
60685                     var sourceProp = sourceProperties_1[_i];
60686                     var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName);
60687                     if (!targetProp) {
60688                         return 0 /* False */;
60689                     }
60690                     var related = compareProperties(sourceProp, targetProp, isRelatedTo);
60691                     if (!related) {
60692                         return 0 /* False */;
60693                     }
60694                     result &= related;
60695                 }
60696                 return result;
60697             }
60698             function signaturesRelatedTo(source, target, kind, reportErrors) {
60699                 var _a, _b;
60700                 if (relation === identityRelation) {
60701                     return signaturesIdenticalTo(source, target, kind);
60702                 }
60703                 if (target === anyFunctionType || source === anyFunctionType) {
60704                     return -1 /* True */;
60705                 }
60706                 var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration);
60707                 var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration);
60708                 var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ?
60709                     0 /* Call */ : kind);
60710                 var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ?
60711                     0 /* Call */ : kind);
60712                 if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
60713                     var sourceIsAbstract = !!(sourceSignatures[0].flags & 4 /* Abstract */);
60714                     var targetIsAbstract = !!(targetSignatures[0].flags & 4 /* Abstract */);
60715                     if (sourceIsAbstract && !targetIsAbstract) {
60716                         // An abstract constructor type is not assignable to a non-abstract constructor type
60717                         // as it would otherwise be possible to new an abstract class. Note that the assignability
60718                         // check we perform for an extends clause excludes construct signatures from the target,
60719                         // so this check never proceeds.
60720                         if (reportErrors) {
60721                             reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
60722                         }
60723                         return 0 /* False */;
60724                     }
60725                     if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) {
60726                         return 0 /* False */;
60727                     }
60728                 }
60729                 var result = -1 /* True */;
60730                 var saveErrorInfo = captureErrorCalculationState();
60731                 var incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn;
60732                 var sourceObjectFlags = ts.getObjectFlags(source);
60733                 var targetObjectFlags = ts.getObjectFlags(target);
60734                 if (sourceObjectFlags & 64 /* Instantiated */ && targetObjectFlags & 64 /* Instantiated */ && source.symbol === target.symbol) {
60735                     // We have instantiations of the same anonymous type (which typically will be the type of a
60736                     // method). Simply do a pairwise comparison of the signatures in the two signature lists instead
60737                     // of the much more expensive N * M comparison matrix we explore below. We erase type parameters
60738                     // as they are known to always be the same.
60739                     for (var i = 0; i < targetSignatures.length; i++) {
60740                         var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors, incompatibleReporter(sourceSignatures[i], targetSignatures[i]));
60741                         if (!related) {
60742                             return 0 /* False */;
60743                         }
60744                         result &= related;
60745                     }
60746                 }
60747                 else if (sourceSignatures.length === 1 && targetSignatures.length === 1) {
60748                     // For simple functions (functions with a single signature) we only erase type parameters for
60749                     // the comparable relation. Otherwise, if the source signature is generic, we instantiate it
60750                     // in the context of the target signature before checking the relationship. Ideally we'd do
60751                     // this regardless of the number of signatures, but the potential costs are prohibitive due
60752                     // to the quadratic nature of the logic below.
60753                     var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks;
60754                     var sourceSignature = ts.first(sourceSignatures);
60755                     var targetSignature = ts.first(targetSignatures);
60756                     result = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors, incompatibleReporter(sourceSignature, targetSignature));
60757                     if (!result && reportErrors && kind === 1 /* Construct */ && (sourceObjectFlags & targetObjectFlags) &&
60758                         (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 166 /* Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 166 /* Constructor */)) {
60759                         var constructSignatureToString = function (signature) {
60760                             return signatureToString(signature, /*enclosingDeclaration*/ undefined, 262144 /* WriteArrowStyleSignature */, kind);
60761                         };
60762                         reportError(ts.Diagnostics.Type_0_is_not_assignable_to_type_1, constructSignatureToString(sourceSignature), constructSignatureToString(targetSignature));
60763                         reportError(ts.Diagnostics.Types_of_construct_signatures_are_incompatible);
60764                         return result;
60765                     }
60766                 }
60767                 else {
60768                     outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) {
60769                         var t = targetSignatures_1[_i];
60770                         // Only elaborate errors from the first failure
60771                         var shouldElaborateErrors = reportErrors;
60772                         for (var _c = 0, sourceSignatures_1 = sourceSignatures; _c < sourceSignatures_1.length; _c++) {
60773                             var s = sourceSignatures_1[_c];
60774                             var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors, incompatibleReporter(s, t));
60775                             if (related) {
60776                                 result &= related;
60777                                 resetErrorInfo(saveErrorInfo);
60778                                 continue outer;
60779                             }
60780                             shouldElaborateErrors = false;
60781                         }
60782                         if (shouldElaborateErrors) {
60783                             reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind));
60784                         }
60785                         return 0 /* False */;
60786                     }
60787                 }
60788                 return result;
60789             }
60790             function reportIncompatibleCallSignatureReturn(siga, sigb) {
60791                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
60792                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
60793                 }
60794                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
60795             }
60796             function reportIncompatibleConstructSignatureReturn(siga, sigb) {
60797                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
60798                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
60799                 }
60800                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
60801             }
60802             /**
60803              * See signatureAssignableTo, compareSignaturesIdentical
60804              */
60805             function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) {
60806                 return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedTo, makeFunctionTypeMapper(reportUnreliableMarkers));
60807             }
60808             function signaturesIdenticalTo(source, target, kind) {
60809                 var sourceSignatures = getSignaturesOfType(source, kind);
60810                 var targetSignatures = getSignaturesOfType(target, kind);
60811                 if (sourceSignatures.length !== targetSignatures.length) {
60812                     return 0 /* False */;
60813                 }
60814                 var result = -1 /* True */;
60815                 for (var i = 0; i < sourceSignatures.length; i++) {
60816                     var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
60817                     if (!related) {
60818                         return 0 /* False */;
60819                     }
60820                     result &= related;
60821                 }
60822                 return result;
60823             }
60824             function eachPropertyRelatedTo(source, target, kind, reportErrors) {
60825                 var result = -1 /* True */;
60826                 var props = source.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(source) : getPropertiesOfObjectType(source);
60827                 for (var _i = 0, props_2 = props; _i < props_2.length; _i++) {
60828                     var prop = props_2[_i];
60829                     // Skip over ignored JSX and symbol-named members
60830                     if (isIgnoredJsxProperty(source, prop)) {
60831                         continue;
60832                     }
60833                     var nameType = getSymbolLinks(prop).nameType;
60834                     if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) {
60835                         continue;
60836                     }
60837                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
60838                         var propType = getTypeOfSymbol(prop);
60839                         var type = propType.flags & 32768 /* Undefined */ || !(kind === 0 /* String */ && prop.flags & 16777216 /* Optional */)
60840                             ? propType
60841                             : getTypeWithFacts(propType, 524288 /* NEUndefined */);
60842                         var related = isRelatedTo(type, target, reportErrors);
60843                         if (!related) {
60844                             if (reportErrors) {
60845                                 reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
60846                             }
60847                             return 0 /* False */;
60848                         }
60849                         result &= related;
60850                     }
60851                 }
60852                 return result;
60853             }
60854             function indexTypeRelatedTo(sourceType, targetType, reportErrors) {
60855                 var related = isRelatedTo(sourceType, targetType, reportErrors);
60856                 if (!related && reportErrors) {
60857                     reportError(ts.Diagnostics.Index_signatures_are_incompatible);
60858                 }
60859                 return related;
60860             }
60861             function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors, intersectionState) {
60862                 if (relation === identityRelation) {
60863                     return indexTypesIdenticalTo(source, target, kind);
60864                 }
60865                 var targetType = getIndexTypeOfType(target, kind);
60866                 if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) {
60867                     // Index signature of type any permits assignment from everything but primitives
60868                     return -1 /* True */;
60869                 }
60870                 if (isGenericMappedType(source)) {
60871                     // A generic mapped type { [P in K]: T } is related to a type with an index signature
60872                     // { [x: string]: U }, and optionally with an index signature { [x: number]: V },
60873                     // if T is related to U and V.
60874                     return getIndexTypeOfType(target, 0 /* String */) ? isRelatedTo(getTemplateTypeFromMappedType(source), targetType, reportErrors) : 0 /* False */;
60875                 }
60876                 var indexType = getIndexTypeOfType(source, kind) || kind === 1 /* Number */ && getIndexTypeOfType(source, 0 /* String */);
60877                 if (indexType) {
60878                     return indexTypeRelatedTo(indexType, targetType, reportErrors);
60879                 }
60880                 if (!(intersectionState & 1 /* Source */) && isObjectTypeWithInferableIndex(source)) {
60881                     // Intersection constituents are never considered to have an inferred index signature
60882                     var related = eachPropertyRelatedTo(source, targetType, kind, reportErrors);
60883                     if (related && kind === 0 /* String */) {
60884                         var numberIndexType = getIndexTypeOfType(source, 1 /* Number */);
60885                         if (numberIndexType) {
60886                             related &= indexTypeRelatedTo(numberIndexType, targetType, reportErrors);
60887                         }
60888                     }
60889                     return related;
60890                 }
60891                 if (reportErrors) {
60892                     reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source));
60893                 }
60894                 return 0 /* False */;
60895             }
60896             function indexTypesIdenticalTo(source, target, indexKind) {
60897                 var targetInfo = getIndexInfoOfType(target, indexKind);
60898                 var sourceInfo = getIndexInfoOfType(source, indexKind);
60899                 if (!sourceInfo && !targetInfo) {
60900                     return -1 /* True */;
60901                 }
60902                 if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) {
60903                     return isRelatedTo(sourceInfo.type, targetInfo.type);
60904                 }
60905                 return 0 /* False */;
60906             }
60907             function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) {
60908                 if (!sourceSignature.declaration || !targetSignature.declaration) {
60909                     return true;
60910                 }
60911                 var sourceAccessibility = ts.getSelectedEffectiveModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
60912                 var targetAccessibility = ts.getSelectedEffectiveModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
60913                 // A public, protected and private signature is assignable to a private signature.
60914                 if (targetAccessibility === 8 /* Private */) {
60915                     return true;
60916                 }
60917                 // A public and protected signature is assignable to a protected signature.
60918                 if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) {
60919                     return true;
60920                 }
60921                 // Only a public signature is assignable to public signature.
60922                 if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) {
60923                     return true;
60924                 }
60925                 if (reportErrors) {
60926                     reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
60927                 }
60928                 return false;
60929             }
60930         }
60931         function typeCouldHaveTopLevelSingletonTypes(type) {
60932             // Okay, yes, 'boolean' is a union of 'true | false', but that's not useful
60933             // in error reporting scenarios. If you need to use this function but that detail matters,
60934             // feel free to add a flag.
60935             if (type.flags & 16 /* Boolean */) {
60936                 return false;
60937             }
60938             if (type.flags & 3145728 /* UnionOrIntersection */) {
60939                 return !!ts.forEach(type.types, typeCouldHaveTopLevelSingletonTypes);
60940             }
60941             if (type.flags & 465829888 /* Instantiable */) {
60942                 var constraint = getConstraintOfType(type);
60943                 if (constraint && constraint !== type) {
60944                     return typeCouldHaveTopLevelSingletonTypes(constraint);
60945                 }
60946             }
60947             return isUnitType(type) || !!(type.flags & 134217728 /* TemplateLiteral */);
60948         }
60949         function getBestMatchingType(source, target, isRelatedTo) {
60950             if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; }
60951             return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) ||
60952                 findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
60953                 findBestTypeForObjectLiteral(source, target) ||
60954                 findBestTypeForInvokable(source, target) ||
60955                 findMostOverlappyType(source, target);
60956         }
60957         function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) {
60958             // undefined=unknown, true=discriminated, false=not discriminated
60959             // The state of each type progresses from left to right. Discriminated types stop at 'true'.
60960             var discriminable = target.types.map(function (_) { return undefined; });
60961             for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) {
60962                 var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1];
60963                 var targetProp = getUnionOrIntersectionProperty(target, propertyName);
60964                 if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) {
60965                     continue;
60966                 }
60967                 var i = 0;
60968                 for (var _b = 0, _c = target.types; _b < _c.length; _b++) {
60969                     var type = _c[_b];
60970                     var targetType = getTypeOfPropertyOfType(type, propertyName);
60971                     if (targetType && related(getDiscriminatingType(), targetType)) {
60972                         discriminable[i] = discriminable[i] === undefined ? true : discriminable[i];
60973                     }
60974                     else {
60975                         discriminable[i] = false;
60976                     }
60977                     i++;
60978                 }
60979             }
60980             var match = discriminable.indexOf(/*searchElement*/ true);
60981             if (match === -1) {
60982                 return defaultValue;
60983             }
60984             // make sure exactly 1 matches before returning it
60985             var nextMatch = discriminable.indexOf(/*searchElement*/ true, match + 1);
60986             while (nextMatch !== -1) {
60987                 if (!isTypeIdenticalTo(target.types[match], target.types[nextMatch])) {
60988                     return defaultValue;
60989                 }
60990                 nextMatch = discriminable.indexOf(/*searchElement*/ true, nextMatch + 1);
60991             }
60992             return target.types[match];
60993         }
60994         /**
60995          * A type is 'weak' if it is an object type with at least one optional property
60996          * and no required properties, call/construct signatures or index signatures
60997          */
60998         function isWeakType(type) {
60999             if (type.flags & 524288 /* Object */) {
61000                 var resolved = resolveStructuredTypeMembers(type);
61001                 return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 &&
61002                     !resolved.stringIndexInfo && !resolved.numberIndexInfo &&
61003                     resolved.properties.length > 0 &&
61004                     ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
61005             }
61006             if (type.flags & 2097152 /* Intersection */) {
61007                 return ts.every(type.types, isWeakType);
61008             }
61009             return false;
61010         }
61011         function hasCommonProperties(source, target, isComparingJsxAttributes) {
61012             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
61013                 var prop = _a[_i];
61014                 if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
61015                     return true;
61016                 }
61017             }
61018             return false;
61019         }
61020         // Return a type reference where the source type parameter is replaced with the target marker
61021         // type, and flag the result as a marker type reference.
61022         function getMarkerTypeReference(type, source, target) {
61023             var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; }));
61024             result.objectFlags |= 8192 /* MarkerType */;
61025             return result;
61026         }
61027         function getAliasVariances(symbol) {
61028             var links = getSymbolLinks(symbol);
61029             return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) {
61030                 var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker)));
61031                 type.aliasTypeArgumentsContainsMarker = true;
61032                 return type;
61033             });
61034         }
61035         // Return an array containing the variance of each type parameter. The variance is effectively
61036         // a digest of the type comparisons that occur for each type argument when instantiations of the
61037         // generic type are structurally compared. We infer the variance information by comparing
61038         // instantiations of the generic type for type arguments with known relations. The function
61039         // returns the emptyArray singleton when invoked recursively for the given generic type.
61040         function getVariancesWorker(typeParameters, cache, createMarkerType) {
61041             var _a, _b, _c;
61042             if (typeParameters === void 0) { typeParameters = ts.emptyArray; }
61043             var variances = cache.variances;
61044             if (!variances) {
61045                 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 });
61046                 // The emptyArray singleton is used to signal a recursive invocation.
61047                 cache.variances = ts.emptyArray;
61048                 variances = [];
61049                 var _loop_19 = function (tp) {
61050                     var unmeasurable = false;
61051                     var unreliable = false;
61052                     var oldHandler = outofbandVarianceMarkerHandler;
61053                     outofbandVarianceMarkerHandler = function (onlyUnreliable) { return onlyUnreliable ? unreliable = true : unmeasurable = true; };
61054                     // We first compare instantiations where the type parameter is replaced with
61055                     // marker types that have a known subtype relationship. From this we can infer
61056                     // invariance, covariance, contravariance or bivariance.
61057                     var typeWithSuper = createMarkerType(cache, tp, markerSuperType);
61058                     var typeWithSub = createMarkerType(cache, tp, markerSubType);
61059                     var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) |
61060                         (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
61061                     // If the instantiations appear to be related bivariantly it may be because the
61062                     // type parameter is independent (i.e. it isn't witnessed anywhere in the generic
61063                     // type). To determine this we compare instantiations where the type parameter is
61064                     // replaced with marker types that are known to be unrelated.
61065                     if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) {
61066                         variance = 4 /* Independent */;
61067                     }
61068                     outofbandVarianceMarkerHandler = oldHandler;
61069                     if (unmeasurable || unreliable) {
61070                         if (unmeasurable) {
61071                             variance |= 8 /* Unmeasurable */;
61072                         }
61073                         if (unreliable) {
61074                             variance |= 16 /* Unreliable */;
61075                         }
61076                     }
61077                     variances.push(variance);
61078                 };
61079                 for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) {
61080                     var tp = typeParameters_1[_i];
61081                     _loop_19(tp);
61082                 }
61083                 cache.variances = variances;
61084                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
61085             }
61086             return variances;
61087         }
61088         function getVariances(type) {
61089             // Arrays and tuples are known to be covariant, no need to spend time computing this.
61090             if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
61091                 return arrayVariances;
61092             }
61093             return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
61094         }
61095         // Return true if the given type reference has a 'void' type argument for a covariant type parameter.
61096         // See comment at call in recursiveTypeRelatedTo for when this case matters.
61097         function hasCovariantVoidArgument(typeArguments, variances) {
61098             for (var i = 0; i < variances.length; i++) {
61099                 if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
61100                     return true;
61101                 }
61102             }
61103             return false;
61104         }
61105         function isUnconstrainedTypeParameter(type) {
61106             return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
61107         }
61108         function isNonDeferredTypeReference(type) {
61109             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node;
61110         }
61111         function isTypeReferenceWithGenericArguments(type) {
61112             return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); });
61113         }
61114         /**
61115          * getTypeReferenceId(A<T, number, U>) returns "111=0-12=1"
61116          *   where A.id=111 and number.id=12
61117          */
61118         function getTypeReferenceId(type, typeParameters, depth) {
61119             if (depth === void 0) { depth = 0; }
61120             var result = "" + type.target.id;
61121             for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) {
61122                 var t = _a[_i];
61123                 if (isUnconstrainedTypeParameter(t)) {
61124                     var index = typeParameters.indexOf(t);
61125                     if (index < 0) {
61126                         index = typeParameters.length;
61127                         typeParameters.push(t);
61128                     }
61129                     result += "=" + index;
61130                 }
61131                 else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
61132                     result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">";
61133                 }
61134                 else {
61135                     result += "-" + t.id;
61136                 }
61137             }
61138             return result;
61139         }
61140         /**
61141          * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters.
61142          * For other cases, the types ids are used.
61143          */
61144         function getRelationKey(source, target, intersectionState, relation) {
61145             if (relation === identityRelation && source.id > target.id) {
61146                 var temp = source;
61147                 source = target;
61148                 target = temp;
61149             }
61150             var postFix = intersectionState ? ":" + intersectionState : "";
61151             if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) {
61152                 var typeParameters = [];
61153                 return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + postFix;
61154             }
61155             return source.id + "," + target.id + postFix;
61156         }
61157         // Invoke the callback for each underlying property symbol of the given symbol and return the first
61158         // value that isn't undefined.
61159         function forEachProperty(prop, callback) {
61160             if (ts.getCheckFlags(prop) & 6 /* Synthetic */) {
61161                 for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) {
61162                     var t = _a[_i];
61163                     var p = getPropertyOfType(t, prop.escapedName);
61164                     var result = p && forEachProperty(p, callback);
61165                     if (result) {
61166                         return result;
61167                     }
61168                 }
61169                 return undefined;
61170             }
61171             return callback(prop);
61172         }
61173         // Return the declaring class type of a property or undefined if property not declared in class
61174         function getDeclaringClass(prop) {
61175             return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
61176         }
61177         // Return the inherited type of the given property or undefined if property doesn't exist in a base class.
61178         function getTypeOfPropertyInBaseClass(property) {
61179             var classType = getDeclaringClass(property);
61180             var baseClassType = classType && getBaseTypes(classType)[0];
61181             return baseClassType && getTypeOfPropertyOfType(baseClassType, property.escapedName);
61182         }
61183         // Return true if some underlying source property is declared in a class that derives
61184         // from the given base class.
61185         function isPropertyInClassDerivedFrom(prop, baseClass) {
61186             return forEachProperty(prop, function (sp) {
61187                 var sourceClass = getDeclaringClass(sp);
61188                 return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
61189             });
61190         }
61191         // Return true if source property is a valid override of protected parts of target property.
61192         function isValidOverrideOf(sourceProp, targetProp) {
61193             return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ?
61194                 !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; });
61195         }
61196         // Return true if the given class derives from each of the declaring classes of the protected
61197         // constituents of the given property.
61198         function isClassDerivedFromDeclaringClasses(checkClass, prop) {
61199             return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ?
61200                 !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass;
61201         }
61202         // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
61203         // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
61204         // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
61205         // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
61206         // levels, but unequal at some level beyond that.
61207         // In addition, this will also detect when an indexed access has been chained off of 5 or more times (which is essentially
61208         // the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding false positives
61209         // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`).
61210         // It also detects when a recursive type reference has expanded 5 or more times, eg, if the true branch of
61211         // `type A<T> = null extends T ? [A<NonNullable<T>>] : [T]`
61212         // has expanded into `[A<NonNullable<NonNullable<NonNullable<NonNullable<NonNullable<T>>>>>>]`
61213         // in such cases we need to terminate the expansion, and we do so here.
61214         function isDeeplyNestedType(type, stack, depth) {
61215             if (depth >= 5) {
61216                 var identity_1 = getRecursionIdentity(type);
61217                 if (identity_1) {
61218                     var count = 0;
61219                     for (var i = 0; i < depth; i++) {
61220                         if (getRecursionIdentity(stack[i]) === identity_1) {
61221                             count++;
61222                             if (count >= 5) {
61223                                 return true;
61224                             }
61225                         }
61226                     }
61227                 }
61228             }
61229             return false;
61230         }
61231         // Types with constituents that could circularly reference the type have a recursion identity. The recursion
61232         // identity is some object that is common to instantiations of the type with the same origin.
61233         function getRecursionIdentity(type) {
61234             if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) {
61235                 if (ts.getObjectFlags(type) && 4 /* Reference */ && type.node) {
61236                     // Deferred type references are tracked through their associated AST node. This gives us finer
61237                     // granularity than using their associated target because each manifest type reference has a
61238                     // unique AST node.
61239                     return type.node;
61240                 }
61241                 if (type.symbol && !(ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol.flags & 32 /* Class */)) {
61242                     // We track all object types that have an associated symbol (representing the origin of the type), but
61243                     // exclude the static side of classes from this check since it shares its symbol with the instance side.
61244                     return type.symbol;
61245                 }
61246                 if (isTupleType(type)) {
61247                     // Tuple types are tracked through their target type
61248                     return type.target;
61249                 }
61250             }
61251             if (type.flags & 8388608 /* IndexedAccess */) {
61252                 // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A
61253                 do {
61254                     type = type.objectType;
61255                 } while (type.flags & 8388608 /* IndexedAccess */);
61256                 return type;
61257             }
61258             if (type.flags & 16777216 /* Conditional */) {
61259                 // The root object represents the origin of the conditional type
61260                 return type.root;
61261             }
61262             return undefined;
61263         }
61264         function isPropertyIdenticalTo(sourceProp, targetProp) {
61265             return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
61266         }
61267         function compareProperties(sourceProp, targetProp, compareTypes) {
61268             // Two members are considered identical when
61269             // - they are public properties with identical names, optionality, and types,
61270             // - they are private or protected properties originating in the same declaration and having identical types
61271             if (sourceProp === targetProp) {
61272                 return -1 /* True */;
61273             }
61274             var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */;
61275             var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */;
61276             if (sourcePropAccessibility !== targetPropAccessibility) {
61277                 return 0 /* False */;
61278             }
61279             if (sourcePropAccessibility) {
61280                 if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
61281                     return 0 /* False */;
61282                 }
61283             }
61284             else {
61285                 if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
61286                     return 0 /* False */;
61287                 }
61288             }
61289             if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
61290                 return 0 /* False */;
61291             }
61292             return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
61293         }
61294         function isMatchingSignature(source, target, partialMatch) {
61295             var sourceParameterCount = getParameterCount(source);
61296             var targetParameterCount = getParameterCount(target);
61297             var sourceMinArgumentCount = getMinArgumentCount(source);
61298             var targetMinArgumentCount = getMinArgumentCount(target);
61299             var sourceHasRestParameter = hasEffectiveRestParameter(source);
61300             var targetHasRestParameter = hasEffectiveRestParameter(target);
61301             // A source signature matches a target signature if the two signatures have the same number of required,
61302             // optional, and rest parameters.
61303             if (sourceParameterCount === targetParameterCount &&
61304                 sourceMinArgumentCount === targetMinArgumentCount &&
61305                 sourceHasRestParameter === targetHasRestParameter) {
61306                 return true;
61307             }
61308             // A source signature partially matches a target signature if the target signature has no fewer required
61309             // parameters
61310             if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
61311                 return true;
61312             }
61313             return false;
61314         }
61315         /**
61316          * See signatureRelatedTo, compareSignaturesIdentical
61317          */
61318         function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
61319             // TODO (drosen): De-duplicate code between related functions.
61320             if (source === target) {
61321                 return -1 /* True */;
61322             }
61323             if (!(isMatchingSignature(source, target, partialMatch))) {
61324                 return 0 /* False */;
61325             }
61326             // Check that the two signatures have the same number of type parameters.
61327             if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) {
61328                 return 0 /* False */;
61329             }
61330             // Check that type parameter constraints and defaults match. If they do, instantiate the source
61331             // signature with the type parameters of the target signature and continue the comparison.
61332             if (target.typeParameters) {
61333                 var mapper = createTypeMapper(source.typeParameters, target.typeParameters);
61334                 for (var i = 0; i < target.typeParameters.length; i++) {
61335                     var s = source.typeParameters[i];
61336                     var t = target.typeParameters[i];
61337                     if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) &&
61338                         compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) {
61339                         return 0 /* False */;
61340                     }
61341                 }
61342                 source = instantiateSignature(source, mapper, /*eraseTypeParameters*/ true);
61343             }
61344             var result = -1 /* True */;
61345             if (!ignoreThisTypes) {
61346                 var sourceThisType = getThisTypeOfSignature(source);
61347                 if (sourceThisType) {
61348                     var targetThisType = getThisTypeOfSignature(target);
61349                     if (targetThisType) {
61350                         var related = compareTypes(sourceThisType, targetThisType);
61351                         if (!related) {
61352                             return 0 /* False */;
61353                         }
61354                         result &= related;
61355                     }
61356                 }
61357             }
61358             var targetLen = getParameterCount(target);
61359             for (var i = 0; i < targetLen; i++) {
61360                 var s = getTypeAtPosition(source, i);
61361                 var t = getTypeAtPosition(target, i);
61362                 var related = compareTypes(t, s);
61363                 if (!related) {
61364                     return 0 /* False */;
61365                 }
61366                 result &= related;
61367             }
61368             if (!ignoreReturnTypes) {
61369                 var sourceTypePredicate = getTypePredicateOfSignature(source);
61370                 var targetTypePredicate = getTypePredicateOfSignature(target);
61371                 result &= sourceTypePredicate || targetTypePredicate ?
61372                     compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) :
61373                     compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
61374             }
61375             return result;
61376         }
61377         function compareTypePredicatesIdentical(source, target, compareTypes) {
61378             return !(source && target && typePredicateKindsMatch(source, target)) ? 0 /* False */ :
61379                 source.type === target.type ? -1 /* True */ :
61380                     source.type && target.type ? compareTypes(source.type, target.type) :
61381                         0 /* False */;
61382         }
61383         function literalTypesWithSameBaseType(types) {
61384             var commonBaseType;
61385             for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
61386                 var t = types_14[_i];
61387                 var baseType = getBaseTypeOfLiteralType(t);
61388                 if (!commonBaseType) {
61389                     commonBaseType = baseType;
61390                 }
61391                 if (baseType === t || baseType !== commonBaseType) {
61392                     return false;
61393                 }
61394             }
61395             return true;
61396         }
61397         // When the candidate types are all literal types with the same base type, return a union
61398         // of those literal types. Otherwise, return the leftmost type for which no type to the
61399         // right is a supertype.
61400         function getSupertypeOrUnion(types) {
61401             return literalTypesWithSameBaseType(types) ?
61402                 getUnionType(types) :
61403                 ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; });
61404         }
61405         function getCommonSupertype(types) {
61406             if (!strictNullChecks) {
61407                 return getSupertypeOrUnion(types);
61408             }
61409             var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); });
61410             return primaryTypes.length ?
61411                 getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) :
61412                 getUnionType(types, 2 /* Subtype */);
61413         }
61414         // Return the leftmost type for which no type to the right is a subtype.
61415         function getCommonSubtype(types) {
61416             return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
61417         }
61418         function isArrayType(type) {
61419             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
61420         }
61421         function isReadonlyArrayType(type) {
61422             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
61423         }
61424         function isMutableArrayOrTuple(type) {
61425             return isArrayType(type) && !isReadonlyArrayType(type) || isTupleType(type) && !type.target.readonly;
61426         }
61427         function getElementTypeOfArrayType(type) {
61428             return isArrayType(type) ? getTypeArguments(type)[0] : undefined;
61429         }
61430         function isArrayLikeType(type) {
61431             // A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
61432             // or if it is not the undefined or null type and if it is assignable to ReadonlyArray<any>
61433             return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
61434         }
61435         function isEmptyArrayLiteralType(type) {
61436             var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined;
61437             return elementType === undefinedWideningType || elementType === implicitNeverType;
61438         }
61439         function isTupleLikeType(type) {
61440             return isTupleType(type) || !!getPropertyOfType(type, "0");
61441         }
61442         function isArrayOrTupleLikeType(type) {
61443             return isArrayLikeType(type) || isTupleLikeType(type);
61444         }
61445         function getTupleElementType(type, index) {
61446             var propType = getTypeOfPropertyOfType(type, "" + index);
61447             if (propType) {
61448                 return propType;
61449             }
61450             if (everyType(type, isTupleType)) {
61451                 return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
61452             }
61453             return undefined;
61454         }
61455         function isNeitherUnitTypeNorNever(type) {
61456             return !(type.flags & (109440 /* Unit */ | 131072 /* Never */));
61457         }
61458         function isUnitType(type) {
61459             return !!(type.flags & 109440 /* Unit */);
61460         }
61461         function isLiteralType(type) {
61462             return type.flags & 16 /* Boolean */ ? true :
61463                 type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) :
61464                     isUnitType(type);
61465         }
61466         function getBaseTypeOfLiteralType(type) {
61467             return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
61468                 type.flags & 128 /* StringLiteral */ ? stringType :
61469                     type.flags & 256 /* NumberLiteral */ ? numberType :
61470                         type.flags & 2048 /* BigIntLiteral */ ? bigintType :
61471                             type.flags & 512 /* BooleanLiteral */ ? booleanType :
61472                                 type.flags & 1048576 /* Union */ ? mapType(type, getBaseTypeOfLiteralType) :
61473                                     type;
61474         }
61475         function getWidenedLiteralType(type) {
61476             return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) :
61477                 type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType :
61478                     type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType :
61479                         type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType :
61480                             type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType :
61481                                 type.flags & 1048576 /* Union */ ? mapType(type, getWidenedLiteralType) :
61482                                     type;
61483         }
61484         function getWidenedUniqueESSymbolType(type) {
61485             return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
61486                 type.flags & 1048576 /* Union */ ? mapType(type, getWidenedUniqueESSymbolType) :
61487                     type;
61488         }
61489         function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
61490             if (!isLiteralOfContextualType(type, contextualType)) {
61491                 type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
61492             }
61493             return type;
61494         }
61495         function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) {
61496             if (type && isUnitType(type)) {
61497                 var contextualType = !contextualSignatureReturnType ? undefined :
61498                     isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) :
61499                         contextualSignatureReturnType;
61500                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
61501             }
61502             return type;
61503         }
61504         function getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(type, contextualSignatureReturnType, kind, isAsyncGenerator) {
61505             if (type && isUnitType(type)) {
61506                 var contextualType = !contextualSignatureReturnType ? undefined :
61507                     getIterationTypeOfGeneratorFunctionReturnType(kind, contextualSignatureReturnType, isAsyncGenerator);
61508                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
61509             }
61510             return type;
61511         }
61512         /**
61513          * Check if a Type was written as a tuple type literal.
61514          * Prefer using isTupleLikeType() unless the use of `elementTypes`/`getTypeArguments` is required.
61515          */
61516         function isTupleType(type) {
61517             return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
61518         }
61519         function isGenericTupleType(type) {
61520             return isTupleType(type) && !!(type.target.combinedFlags & 8 /* Variadic */);
61521         }
61522         function isSingleElementGenericTupleType(type) {
61523             return isGenericTupleType(type) && type.target.elementFlags.length === 1;
61524         }
61525         function getRestTypeOfTupleType(type) {
61526             return getElementTypeOfSliceOfTupleType(type, type.target.fixedLength);
61527         }
61528         function getRestArrayTypeOfTupleType(type) {
61529             var restType = getRestTypeOfTupleType(type);
61530             return restType && createArrayType(restType);
61531         }
61532         function getElementTypeOfSliceOfTupleType(type, index, endSkipCount, writing) {
61533             if (endSkipCount === void 0) { endSkipCount = 0; }
61534             if (writing === void 0) { writing = false; }
61535             var length = getTypeReferenceArity(type) - endSkipCount;
61536             if (index < length) {
61537                 var typeArguments = getTypeArguments(type);
61538                 var elementTypes = [];
61539                 for (var i = index; i < length; i++) {
61540                     var t = typeArguments[i];
61541                     elementTypes.push(type.target.elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t);
61542                 }
61543                 return writing ? getIntersectionType(elementTypes) : getUnionType(elementTypes);
61544             }
61545             return undefined;
61546         }
61547         function isTupleTypeStructureMatching(t1, t2) {
61548             return getTypeReferenceArity(t1) === getTypeReferenceArity(t2) &&
61549                 ts.every(t1.target.elementFlags, function (f, i) { return (f & 12 /* Variable */) === (t2.target.elementFlags[i] & 12 /* Variable */); });
61550         }
61551         function isZeroBigInt(_a) {
61552             var value = _a.value;
61553             return value.base10Value === "0";
61554         }
61555         function getFalsyFlagsOfTypes(types) {
61556             var result = 0;
61557             for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
61558                 var t = types_15[_i];
61559                 result |= getFalsyFlags(t);
61560             }
61561             return result;
61562         }
61563         // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null
61564         // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns
61565         // no flags for all other types (including non-falsy literal types).
61566         function getFalsyFlags(type) {
61567             return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) :
61568                 type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 :
61569                     type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 :
61570                         type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 :
61571                             type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 :
61572                                 type.flags & 117724 /* PossiblyFalsy */;
61573         }
61574         function removeDefinitelyFalsyTypes(type) {
61575             return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ?
61576                 filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) :
61577                 type;
61578         }
61579         function extractDefinitelyFalsyTypes(type) {
61580             return mapType(type, getDefinitelyFalsyPartOfType);
61581         }
61582         function getDefinitelyFalsyPartOfType(type) {
61583             return type.flags & 4 /* String */ ? emptyStringType :
61584                 type.flags & 8 /* Number */ ? zeroType :
61585                     type.flags & 64 /* BigInt */ ? zeroBigIntType :
61586                         type === regularFalseType ||
61587                             type === falseType ||
61588                             type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */ | 3 /* AnyOrUnknown */) ||
61589                             type.flags & 128 /* StringLiteral */ && type.value === "" ||
61590                             type.flags & 256 /* NumberLiteral */ && type.value === 0 ||
61591                             type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type :
61592                             neverType;
61593         }
61594         /**
61595          * Add undefined or null or both to a type if they are missing.
61596          * @param type - type to add undefined and/or null to if not present
61597          * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both
61598          */
61599         function getNullableType(type, flags) {
61600             var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */);
61601             return missing === 0 ? type :
61602                 missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) :
61603                     missing === 65536 /* Null */ ? getUnionType([type, nullType]) :
61604                         getUnionType([type, undefinedType, nullType]);
61605         }
61606         function getOptionalType(type) {
61607             ts.Debug.assert(strictNullChecks);
61608             return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]);
61609         }
61610         function getGlobalNonNullableTypeInstantiation(type) {
61611             if (!deferredGlobalNonNullableTypeAlias) {
61612                 deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol;
61613             }
61614             // Use NonNullable global type alias if available to improve quick info/declaration emit
61615             if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
61616                 return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
61617             }
61618             return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior
61619         }
61620         function getNonNullableType(type) {
61621             return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
61622         }
61623         function addOptionalTypeMarker(type) {
61624             return strictNullChecks ? getUnionType([type, optionalType]) : type;
61625         }
61626         function isNotOptionalTypeMarker(type) {
61627             return type !== optionalType;
61628         }
61629         function removeOptionalTypeMarker(type) {
61630             return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type;
61631         }
61632         function propagateOptionalTypeMarker(type, node, wasOptional) {
61633             return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type;
61634         }
61635         function getOptionalExpressionType(exprType, expression) {
61636             return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) :
61637                 ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) :
61638                     exprType;
61639         }
61640         /**
61641          * Is source potentially coercible to target type under `==`.
61642          * Assumes that `source` is a constituent of a union, hence
61643          * the boolean literal flag on the LHS, but not on the RHS.
61644          *
61645          * This does not fully replicate the semantics of `==`. The
61646          * intention is to catch cases that are clearly not right.
61647          *
61648          * Comparing (string | number) to number should not remove the
61649          * string element.
61650          *
61651          * Comparing (string | number) to 1 will remove the string
61652          * element, though this is not sound. This is a pragmatic
61653          * choice.
61654          *
61655          * @see narrowTypeByEquality
61656          *
61657          * @param source
61658          * @param target
61659          */
61660         function isCoercibleUnderDoubleEquals(source, target) {
61661             return ((source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0)
61662                 && ((target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0);
61663         }
61664         /**
61665          * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
61666          * with no call or construct signatures.
61667          */
61668         function isObjectTypeWithInferableIndex(type) {
61669             return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) :
61670                 !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 &&
61671                     !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source));
61672         }
61673         function createSymbolWithType(source, type) {
61674             var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */);
61675             symbol.declarations = source.declarations;
61676             symbol.parent = source.parent;
61677             symbol.type = type;
61678             symbol.target = source;
61679             if (source.valueDeclaration) {
61680                 symbol.valueDeclaration = source.valueDeclaration;
61681             }
61682             var nameType = getSymbolLinks(source).nameType;
61683             if (nameType) {
61684                 symbol.nameType = nameType;
61685             }
61686             return symbol;
61687         }
61688         function transformTypeOfMembers(type, f) {
61689             var members = ts.createSymbolTable();
61690             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
61691                 var property = _a[_i];
61692                 var original = getTypeOfSymbol(property);
61693                 var updated = f(original);
61694                 members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
61695             }
61696             return members;
61697         }
61698         /**
61699          * If the the provided object literal is subject to the excess properties check,
61700          * create a new that is exempt. Recursively mark object literal members as exempt.
61701          * Leave signatures alone since they are not subject to the check.
61702          */
61703         function getRegularTypeOfObjectLiteral(type) {
61704             if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) {
61705                 return type;
61706             }
61707             var regularType = type.regularType;
61708             if (regularType) {
61709                 return regularType;
61710             }
61711             var resolved = type;
61712             var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
61713             var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
61714             regularNew.flags = resolved.flags;
61715             regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
61716             type.regularType = regularNew;
61717             return regularNew;
61718         }
61719         function createWideningContext(parent, propertyName, siblings) {
61720             return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined };
61721         }
61722         function getSiblingsOfContext(context) {
61723             if (!context.siblings) {
61724                 var siblings_1 = [];
61725                 for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) {
61726                     var type = _a[_i];
61727                     if (isObjectLiteralType(type)) {
61728                         var prop = getPropertyOfObjectType(type, context.propertyName);
61729                         if (prop) {
61730                             forEachType(getTypeOfSymbol(prop), function (t) {
61731                                 siblings_1.push(t);
61732                             });
61733                         }
61734                     }
61735                 }
61736                 context.siblings = siblings_1;
61737             }
61738             return context.siblings;
61739         }
61740         function getPropertiesOfContext(context) {
61741             if (!context.resolvedProperties) {
61742                 var names = new ts.Map();
61743                 for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) {
61744                     var t = _a[_i];
61745                     if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) {
61746                         for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) {
61747                             var prop = _c[_b];
61748                             names.set(prop.escapedName, prop);
61749                         }
61750                     }
61751                 }
61752                 context.resolvedProperties = ts.arrayFrom(names.values());
61753             }
61754             return context.resolvedProperties;
61755         }
61756         function getWidenedProperty(prop, context) {
61757             if (!(prop.flags & 4 /* Property */)) {
61758                 // Since get accessors already widen their return value there is no need to
61759                 // widen accessor based properties here.
61760                 return prop;
61761             }
61762             var original = getTypeOfSymbol(prop);
61763             var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined);
61764             var widened = getWidenedTypeWithContext(original, propContext);
61765             return widened === original ? prop : createSymbolWithType(prop, widened);
61766         }
61767         function getUndefinedProperty(prop) {
61768             var cached = undefinedProperties.get(prop.escapedName);
61769             if (cached) {
61770                 return cached;
61771             }
61772             var result = createSymbolWithType(prop, undefinedType);
61773             result.flags |= 16777216 /* Optional */;
61774             undefinedProperties.set(prop.escapedName, result);
61775             return result;
61776         }
61777         function getWidenedTypeOfObjectLiteral(type, context) {
61778             var members = ts.createSymbolTable();
61779             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
61780                 var prop = _a[_i];
61781                 members.set(prop.escapedName, getWidenedProperty(prop, context));
61782             }
61783             if (context) {
61784                 for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) {
61785                     var prop = _c[_b];
61786                     if (!members.has(prop.escapedName)) {
61787                         members.set(prop.escapedName, getUndefinedProperty(prop));
61788                     }
61789                 }
61790             }
61791             var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
61792             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
61793             var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly));
61794             result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening
61795             return result;
61796         }
61797         function getWidenedType(type) {
61798             return getWidenedTypeWithContext(type, /*context*/ undefined);
61799         }
61800         function getWidenedTypeWithContext(type, context) {
61801             if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) {
61802                 if (context === undefined && type.widened) {
61803                     return type.widened;
61804                 }
61805                 var result = void 0;
61806                 if (type.flags & (1 /* Any */ | 98304 /* Nullable */)) {
61807                     result = anyType;
61808                 }
61809                 else if (isObjectLiteralType(type)) {
61810                     result = getWidenedTypeOfObjectLiteral(type, context);
61811                 }
61812                 else if (type.flags & 1048576 /* Union */) {
61813                     var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types);
61814                     var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); });
61815                     // Widening an empty object literal transitions from a highly restrictive type to
61816                     // a highly inclusive one. For that reason we perform subtype reduction here if the
61817                     // union includes empty object types (e.g. reducing {} | string to just {}).
61818                     result = getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
61819                 }
61820                 else if (type.flags & 2097152 /* Intersection */) {
61821                     result = getIntersectionType(ts.sameMap(type.types, getWidenedType));
61822                 }
61823                 else if (isArrayType(type) || isTupleType(type)) {
61824                     result = createTypeReference(type.target, ts.sameMap(getTypeArguments(type), getWidenedType));
61825                 }
61826                 if (result && context === undefined) {
61827                     type.widened = result;
61828                 }
61829                 return result || type;
61830             }
61831             return type;
61832         }
61833         /**
61834          * Reports implicit any errors that occur as a result of widening 'null' and 'undefined'
61835          * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to
61836          * getWidenedType. But in some cases getWidenedType is called without reporting errors
61837          * (type argument inference is an example).
61838          *
61839          * The return value indicates whether an error was in fact reported. The particular circumstances
61840          * are on a best effort basis. Currently, if the null or undefined that causes widening is inside
61841          * an object literal property (arbitrarily deeply), this function reports an error. If no error is
61842          * reported, reportImplicitAnyError is a suitable fallback to report a general error.
61843          */
61844         function reportWideningErrorsInType(type) {
61845             var errorReported = false;
61846             if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) {
61847                 if (type.flags & 1048576 /* Union */) {
61848                     if (ts.some(type.types, isEmptyObjectType)) {
61849                         errorReported = true;
61850                     }
61851                     else {
61852                         for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
61853                             var t = _a[_i];
61854                             if (reportWideningErrorsInType(t)) {
61855                                 errorReported = true;
61856                             }
61857                         }
61858                     }
61859                 }
61860                 if (isArrayType(type) || isTupleType(type)) {
61861                     for (var _b = 0, _c = getTypeArguments(type); _b < _c.length; _b++) {
61862                         var t = _c[_b];
61863                         if (reportWideningErrorsInType(t)) {
61864                             errorReported = true;
61865                         }
61866                     }
61867                 }
61868                 if (isObjectLiteralType(type)) {
61869                     for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
61870                         var p = _e[_d];
61871                         var t = getTypeOfSymbol(p);
61872                         if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) {
61873                             if (!reportWideningErrorsInType(t)) {
61874                                 error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
61875                             }
61876                             errorReported = true;
61877                         }
61878                     }
61879                 }
61880             }
61881             return errorReported;
61882         }
61883         function reportImplicitAny(declaration, type, wideningKind) {
61884             var typeAsString = typeToString(getWidenedType(type));
61885             if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) {
61886                 // Only report implicit any errors/suggestions in TS and ts-check JS files
61887                 return;
61888             }
61889             var diagnostic;
61890             switch (declaration.kind) {
61891                 case 216 /* BinaryExpression */:
61892                 case 163 /* PropertyDeclaration */:
61893                 case 162 /* PropertySignature */:
61894                     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;
61895                     break;
61896                 case 160 /* Parameter */:
61897                     var param = declaration;
61898                     if (ts.isIdentifier(param.name) &&
61899                         (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
61900                         param.parent.parameters.indexOf(param) > -1 &&
61901                         (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
61902                             param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
61903                         var newName = "arg" + param.parent.parameters.indexOf(param);
61904                         errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
61905                         return;
61906                     }
61907                     diagnostic = declaration.dotDotDotToken ?
61908                         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 :
61909                         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;
61910                     break;
61911                 case 198 /* BindingElement */:
61912                     diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type;
61913                     if (!noImplicitAny) {
61914                         // Don't issue a suggestion for binding elements since the codefix doesn't yet support them.
61915                         return;
61916                     }
61917                     break;
61918                 case 308 /* JSDocFunctionType */:
61919                     error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
61920                     return;
61921                 case 251 /* FunctionDeclaration */:
61922                 case 165 /* MethodDeclaration */:
61923                 case 164 /* MethodSignature */:
61924                 case 167 /* GetAccessor */:
61925                 case 168 /* SetAccessor */:
61926                 case 208 /* FunctionExpression */:
61927                 case 209 /* ArrowFunction */:
61928                     if (noImplicitAny && !declaration.name) {
61929                         if (wideningKind === 3 /* GeneratorYield */) {
61930                             error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString);
61931                         }
61932                         else {
61933                             error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
61934                         }
61935                         return;
61936                     }
61937                     diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage :
61938                         wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type :
61939                             ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type;
61940                     break;
61941                 case 190 /* MappedType */:
61942                     if (noImplicitAny) {
61943                         error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
61944                     }
61945                     return;
61946                 default:
61947                     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;
61948             }
61949             errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
61950         }
61951         function reportErrorsFromWidening(declaration, type, wideningKind) {
61952             if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) {
61953                 // Report implicit any error within type if possible, otherwise report error on declaration
61954                 if (!reportWideningErrorsInType(type)) {
61955                     reportImplicitAny(declaration, type, wideningKind);
61956                 }
61957             }
61958         }
61959         function applyToParameterTypes(source, target, callback) {
61960             var sourceCount = getParameterCount(source);
61961             var targetCount = getParameterCount(target);
61962             var sourceRestType = getEffectiveRestType(source);
61963             var targetRestType = getEffectiveRestType(target);
61964             var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount;
61965             var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
61966             var sourceThisType = getThisTypeOfSignature(source);
61967             if (sourceThisType) {
61968                 var targetThisType = getThisTypeOfSignature(target);
61969                 if (targetThisType) {
61970                     callback(sourceThisType, targetThisType);
61971                 }
61972             }
61973             for (var i = 0; i < paramCount; i++) {
61974                 callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
61975             }
61976             if (targetRestType) {
61977                 callback(getRestTypeAtPosition(source, paramCount), targetRestType);
61978             }
61979         }
61980         function applyToReturnTypes(source, target, callback) {
61981             var sourceTypePredicate = getTypePredicateOfSignature(source);
61982             var targetTypePredicate = getTypePredicateOfSignature(target);
61983             if (sourceTypePredicate && targetTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) {
61984                 callback(sourceTypePredicate.type, targetTypePredicate.type);
61985             }
61986             else {
61987                 callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
61988             }
61989         }
61990         function createInferenceContext(typeParameters, signature, flags, compareTypes) {
61991             return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
61992         }
61993         function cloneInferenceContext(context, extraFlags) {
61994             if (extraFlags === void 0) { extraFlags = 0; }
61995             return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
61996         }
61997         function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
61998             var context = {
61999                 inferences: inferences,
62000                 signature: signature,
62001                 flags: flags,
62002                 compareTypes: compareTypes,
62003                 mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }),
62004                 nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }),
62005             };
62006             return context;
62007         }
62008         function mapToInferredType(context, t, fix) {
62009             var inferences = context.inferences;
62010             for (var i = 0; i < inferences.length; i++) {
62011                 var inference = inferences[i];
62012                 if (t === inference.typeParameter) {
62013                     if (fix && !inference.isFixed) {
62014                         clearCachedInferences(inferences);
62015                         inference.isFixed = true;
62016                     }
62017                     return getInferredType(context, i);
62018                 }
62019             }
62020             return t;
62021         }
62022         function clearCachedInferences(inferences) {
62023             for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
62024                 var inference = inferences_1[_i];
62025                 if (!inference.isFixed) {
62026                     inference.inferredType = undefined;
62027                 }
62028             }
62029         }
62030         function createInferenceInfo(typeParameter) {
62031             return {
62032                 typeParameter: typeParameter,
62033                 candidates: undefined,
62034                 contraCandidates: undefined,
62035                 inferredType: undefined,
62036                 priority: undefined,
62037                 topLevel: true,
62038                 isFixed: false,
62039                 impliedArity: undefined
62040             };
62041         }
62042         function cloneInferenceInfo(inference) {
62043             return {
62044                 typeParameter: inference.typeParameter,
62045                 candidates: inference.candidates && inference.candidates.slice(),
62046                 contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
62047                 inferredType: inference.inferredType,
62048                 priority: inference.priority,
62049                 topLevel: inference.topLevel,
62050                 isFixed: inference.isFixed,
62051                 impliedArity: inference.impliedArity
62052             };
62053         }
62054         function cloneInferredPartOfContext(context) {
62055             var inferences = ts.filter(context.inferences, hasInferenceCandidates);
62056             return inferences.length ?
62057                 createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
62058                 undefined;
62059         }
62060         function getMapperFromContext(context) {
62061             return context && context.mapper;
62062         }
62063         // Return true if the given type could possibly reference a type parameter for which
62064         // we perform type inference (i.e. a type parameter of a generic function). We cache
62065         // results for union and intersection types for performance reasons.
62066         function couldContainTypeVariables(type) {
62067             var objectFlags = ts.getObjectFlags(type);
62068             if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) {
62069                 return !!(objectFlags & 134217728 /* CouldContainTypeVariables */);
62070             }
62071             var result = !!(type.flags & 465829888 /* Instantiable */ ||
62072                 type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) ||
62073                     objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ||
62074                     objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) ||
62075                 type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables));
62076             if (type.flags & 3899393 /* ObjectFlagsType */) {
62077                 type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0);
62078             }
62079             return result;
62080         }
62081         function isNonGenericTopLevelType(type) {
62082             if (type.aliasSymbol && !type.aliasTypeArguments) {
62083                 var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 254 /* TypeAliasDeclaration */);
62084                 return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 297 /* SourceFile */ ? true : n.kind === 256 /* ModuleDeclaration */ ? false : "quit"; }));
62085             }
62086             return false;
62087         }
62088         function isTypeParameterAtTopLevel(type, typeParameter) {
62089             return !!(type === typeParameter ||
62090                 type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) ||
62091                 type.flags & 16777216 /* Conditional */ && (getTrueTypeFromConditionalType(type) === typeParameter || getFalseTypeFromConditionalType(type) === typeParameter));
62092         }
62093         /** Create an object with properties named in the string literal type. Every property has type `any` */
62094         function createEmptyObjectTypeFromStringLiteral(type) {
62095             var members = ts.createSymbolTable();
62096             forEachType(type, function (t) {
62097                 if (!(t.flags & 128 /* StringLiteral */)) {
62098                     return;
62099                 }
62100                 var name = ts.escapeLeadingUnderscores(t.value);
62101                 var literalProp = createSymbol(4 /* Property */, name);
62102                 literalProp.type = anyType;
62103                 if (t.symbol) {
62104                     literalProp.declarations = t.symbol.declarations;
62105                     literalProp.valueDeclaration = t.symbol.valueDeclaration;
62106                 }
62107                 members.set(name, literalProp);
62108             });
62109             var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined;
62110             return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined);
62111         }
62112         /**
62113          * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
62114          * an object type with the same set of properties as the source type, where the type of each
62115          * property is computed by inferring from the source property type to X for the type
62116          * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
62117          */
62118         function inferTypeForHomomorphicMappedType(source, target, constraint) {
62119             if (inInferTypeForHomomorphicMappedType) {
62120                 return undefined;
62121             }
62122             var key = source.id + "," + target.id + "," + constraint.id;
62123             if (reverseMappedCache.has(key)) {
62124                 return reverseMappedCache.get(key);
62125             }
62126             inInferTypeForHomomorphicMappedType = true;
62127             var type = createReverseMappedType(source, target, constraint);
62128             inInferTypeForHomomorphicMappedType = false;
62129             reverseMappedCache.set(key, type);
62130             return type;
62131         }
62132         // We consider a type to be partially inferable if it isn't marked non-inferable or if it is
62133         // an object literal type with at least one property of an inferable type. For example, an object
62134         // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive
62135         // arrow function, but is considered partially inferable because property 'a' has an inferable type.
62136         function isPartiallyInferableType(type) {
62137             return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) ||
62138                 isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) ||
62139                 isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType);
62140         }
62141         function createReverseMappedType(source, target, constraint) {
62142             // We consider a source type reverse mappable if it has a string index signature or if
62143             // it has one or more properties and is of a partially inferable type.
62144             if (!(getIndexInfoOfType(source, 0 /* String */) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) {
62145                 return undefined;
62146             }
62147             // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
62148             // applied to the element type(s).
62149             if (isArrayType(source)) {
62150                 return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source));
62151             }
62152             if (isTupleType(source)) {
62153                 var elementTypes = ts.map(getTypeArguments(source), function (t) { return inferReverseMappedType(t, target, constraint); });
62154                 var elementFlags = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ?
62155                     ts.sameMap(source.target.elementFlags, function (f) { return f & 2 /* Optional */ ? 1 /* Required */ : f; }) :
62156                     source.target.elementFlags;
62157                 return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations);
62158             }
62159             // For all other object types we infer a new object type where the reverse mapping has been
62160             // applied to the type of each property.
62161             var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined);
62162             reversed.source = source;
62163             reversed.mappedType = target;
62164             reversed.constraintType = constraint;
62165             return reversed;
62166         }
62167         function getTypeOfReverseMappedSymbol(symbol) {
62168             return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType);
62169         }
62170         function inferReverseMappedType(sourceType, target, constraint) {
62171             var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target));
62172             var templateType = getTemplateTypeFromMappedType(target);
62173             var inference = createInferenceInfo(typeParameter);
62174             inferTypes([inference], sourceType, templateType);
62175             return getTypeFromInference(inference) || unknownType;
62176         }
62177         function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
62178             var properties, _i, properties_2, targetProp, sourceProp, targetType, sourceType;
62179             return __generator(this, function (_a) {
62180                 switch (_a.label) {
62181                     case 0:
62182                         properties = getPropertiesOfType(target);
62183                         _i = 0, properties_2 = properties;
62184                         _a.label = 1;
62185                     case 1:
62186                         if (!(_i < properties_2.length)) return [3 /*break*/, 6];
62187                         targetProp = properties_2[_i];
62188                         // TODO: remove this when we support static private identifier fields and find other solutions to get privateNamesAndStaticFields test to pass
62189                         if (isStaticPrivateIdentifierProperty(targetProp)) {
62190                             return [3 /*break*/, 5];
62191                         }
62192                         if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */))) return [3 /*break*/, 5];
62193                         sourceProp = getPropertyOfType(source, targetProp.escapedName);
62194                         if (!!sourceProp) return [3 /*break*/, 3];
62195                         return [4 /*yield*/, targetProp];
62196                     case 2:
62197                         _a.sent();
62198                         return [3 /*break*/, 5];
62199                     case 3:
62200                         if (!matchDiscriminantProperties) return [3 /*break*/, 5];
62201                         targetType = getTypeOfSymbol(targetProp);
62202                         if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5];
62203                         sourceType = getTypeOfSymbol(sourceProp);
62204                         if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5];
62205                         return [4 /*yield*/, targetProp];
62206                     case 4:
62207                         _a.sent();
62208                         _a.label = 5;
62209                     case 5:
62210                         _i++;
62211                         return [3 /*break*/, 1];
62212                     case 6: return [2 /*return*/];
62213                 }
62214             });
62215         }
62216         function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) {
62217             var result = getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next();
62218             if (!result.done)
62219                 return result.value;
62220         }
62221         function tupleTypesDefinitelyUnrelated(source, target) {
62222             return !(target.target.combinedFlags & 8 /* Variadic */) && target.target.minLength > source.target.minLength ||
62223                 !target.target.hasRestElement && (source.target.hasRestElement || target.target.fixedLength < source.target.fixedLength);
62224         }
62225         function typesDefinitelyUnrelated(source, target) {
62226             // Two tuple types with incompatible arities are definitely unrelated.
62227             // Two object types that each have a property that is unmatched in the other are definitely unrelated.
62228             return isTupleType(source) && isTupleType(target) ? tupleTypesDefinitelyUnrelated(source, target) :
62229                 !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) &&
62230                     !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ false);
62231         }
62232         function getTypeFromInference(inference) {
62233             return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
62234                 inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
62235                     undefined;
62236         }
62237         function hasSkipDirectInferenceFlag(node) {
62238             return !!getNodeLinks(node).skipDirectInference;
62239         }
62240         function isFromInferenceBlockedSource(type) {
62241             return !!(type.symbol && ts.some(type.symbol.declarations, hasSkipDirectInferenceFlag));
62242         }
62243         function isValidBigIntString(s) {
62244             var scanner = ts.createScanner(99 /* ESNext */, /*skipTrivia*/ false);
62245             var success = true;
62246             scanner.setOnError(function () { return success = false; });
62247             scanner.setText(s + "n");
62248             var result = scanner.scan();
62249             if (result === 40 /* MinusToken */) {
62250                 result = scanner.scan();
62251             }
62252             var flags = scanner.getTokenFlags();
62253             // validate that
62254             // * scanning proceeded without error
62255             // * a bigint can be scanned, and that when it is scanned, it is
62256             // * the full length of the input string (so the scanner is one character beyond the augmented input length)
62257             // * it does not contain a numeric seperator (the `BigInt` constructor does not accept a numeric seperator in its input)
62258             return success && result === 9 /* BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* ContainsSeparator */);
62259         }
62260         function isStringLiteralTypeValueParsableAsType(s, target) {
62261             if (target.flags & 1048576 /* Union */) {
62262                 return !!forEachType(target, function (t) { return isStringLiteralTypeValueParsableAsType(s, t); });
62263             }
62264             switch (target) {
62265                 case stringType: return true;
62266                 case numberType: return s.value !== "" && isFinite(+(s.value));
62267                 case bigintType: return s.value !== "" && isValidBigIntString(s.value);
62268                 // the next 4 should be handled in `getTemplateLiteralType`, as they are all exactly one value, but are here for completeness, just in case
62269                 // this function is ever used on types which don't come from template literal holes
62270                 case trueType: return s.value === "true";
62271                 case falseType: return s.value === "false";
62272                 case undefinedType: return s.value === "undefined";
62273                 case nullType: return s.value === "null";
62274                 default: return !!(target.flags & 1 /* Any */);
62275             }
62276         }
62277         function inferLiteralsFromTemplateLiteralType(source, target) {
62278             var value = source.value;
62279             var texts = target.texts;
62280             var lastIndex = texts.length - 1;
62281             var startText = texts[0];
62282             var endText = texts[lastIndex];
62283             if (!(value.startsWith(startText) && value.slice(startText.length).endsWith(endText)))
62284                 return undefined;
62285             var matches = [];
62286             var str = value.slice(startText.length, value.length - endText.length);
62287             var pos = 0;
62288             for (var i = 1; i < lastIndex; i++) {
62289                 var delim = texts[i];
62290                 var delimPos = delim.length > 0 ? str.indexOf(delim, pos) : pos < str.length ? pos + 1 : -1;
62291                 if (delimPos < 0)
62292                     return undefined;
62293                 matches.push(getLiteralType(str.slice(pos, delimPos)));
62294                 pos = delimPos + delim.length;
62295             }
62296             matches.push(getLiteralType(str.slice(pos)));
62297             return matches;
62298         }
62299         function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
62300             if (priority === void 0) { priority = 0; }
62301             if (contravariant === void 0) { contravariant = false; }
62302             var bivariant = false;
62303             var propagationType;
62304             var inferencePriority = 1024 /* MaxValue */;
62305             var allowComplexConstraintInference = true;
62306             var visited;
62307             var sourceStack;
62308             var targetStack;
62309             var expandingFlags = 0 /* None */;
62310             inferFromTypes(originalSource, originalTarget);
62311             function inferFromTypes(source, target) {
62312                 if (!couldContainTypeVariables(target)) {
62313                     return;
62314                 }
62315                 if (source === wildcardType) {
62316                     // We are inferring from an 'any' type. We want to infer this type for every type parameter
62317                     // referenced in the target type, so we record it as the propagation type and infer from the
62318                     // target to itself. Then, as we find candidates we substitute the propagation type.
62319                     var savePropagationType = propagationType;
62320                     propagationType = source;
62321                     inferFromTypes(target, target);
62322                     propagationType = savePropagationType;
62323                     return;
62324                 }
62325                 if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
62326                     // Source and target are types originating in the same generic type alias declaration.
62327                     // Simply infer from source type arguments to target type arguments.
62328                     inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol));
62329                     return;
62330                 }
62331                 if (source === target && source.flags & 3145728 /* UnionOrIntersection */) {
62332                     // When source and target are the same union or intersection type, just relate each constituent
62333                     // type to itself.
62334                     for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
62335                         var t = _a[_i];
62336                         inferFromTypes(t, t);
62337                     }
62338                     return;
62339                 }
62340                 if (target.flags & 1048576 /* Union */) {
62341                     // First, infer between identically matching source and target constituents and remove the
62342                     // matching types.
62343                     var _b = inferFromMatchingTypes(source.flags & 1048576 /* Union */ ? source.types : [source], target.types, isTypeOrBaseIdenticalTo), tempSources = _b[0], tempTargets = _b[1];
62344                     // Next, infer between closely matching source and target constituents and remove
62345                     // the matching types. Types closely match when they are instantiations of the same
62346                     // object type or instantiations of the same type alias.
62347                     var _c = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy), sources = _c[0], targets = _c[1];
62348                     if (targets.length === 0) {
62349                         return;
62350                     }
62351                     target = getUnionType(targets);
62352                     if (sources.length === 0) {
62353                         // All source constituents have been matched and there is nothing further to infer from.
62354                         // However, simply making no inferences is undesirable because it could ultimately mean
62355                         // inferring a type parameter constraint. Instead, make a lower priority inference from
62356                         // the full source to whatever remains in the target. For example, when inferring from
62357                         // string to 'string | T', make a lower priority inference of string for T.
62358                         inferWithPriority(source, target, 1 /* NakedTypeVariable */);
62359                         return;
62360                     }
62361                     source = getUnionType(sources);
62362                 }
62363                 else if (target.flags & 2097152 /* Intersection */ && ts.some(target.types, function (t) { return !!getInferenceInfoForType(t) || (isGenericMappedType(t) && !!getInferenceInfoForType(getHomomorphicTypeVariable(t) || neverType)); })) {
62364                     // We reduce intersection types only when they contain naked type parameters. For example, when
62365                     // inferring from 'string[] & { extra: any }' to 'string[] & T' we want to remove string[] and
62366                     // infer { extra: any } for T. But when inferring to 'string[] & Iterable<T>' we want to keep the
62367                     // string[] on the source side and infer string for T.
62368                     // Likewise, we consider a homomorphic mapped type constrainted to the target type parameter as similar to a "naked type variable"
62369                     // in such scenarios.
62370                     if (!(source.flags & 1048576 /* Union */)) {
62371                         // Infer between identically matching source and target constituents and remove the matching types.
62372                         var _d = inferFromMatchingTypes(source.flags & 2097152 /* Intersection */ ? source.types : [source], target.types, isTypeIdenticalTo), sources = _d[0], targets = _d[1];
62373                         if (sources.length === 0 || targets.length === 0) {
62374                             return;
62375                         }
62376                         source = getIntersectionType(sources);
62377                         target = getIntersectionType(targets);
62378                     }
62379                 }
62380                 else if (target.flags & (8388608 /* IndexedAccess */ | 33554432 /* Substitution */)) {
62381                     target = getActualTypeVariable(target);
62382                 }
62383                 if (target.flags & 8650752 /* TypeVariable */) {
62384                     // If target is a type parameter, make an inference, unless the source type contains
62385                     // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
62386                     // Because the anyFunctionType is internal, it should not be exposed to the user by adding
62387                     // it as an inference candidate. Hopefully, a better candidate will come along that does
62388                     // not contain anyFunctionType when we come back to this argument for its second round
62389                     // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
62390                     // when constructing types from type parameters that had no inference candidates).
62391                     if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType ||
62392                         (priority & 64 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) {
62393                         return;
62394                     }
62395                     var inference = getInferenceInfoForType(target);
62396                     if (inference) {
62397                         if (!inference.isFixed) {
62398                             if (inference.priority === undefined || priority < inference.priority) {
62399                                 inference.candidates = undefined;
62400                                 inference.contraCandidates = undefined;
62401                                 inference.topLevel = true;
62402                                 inference.priority = priority;
62403                             }
62404                             if (priority === inference.priority) {
62405                                 var candidate = propagationType || source;
62406                                 // We make contravariant inferences only if we are in a pure contravariant position,
62407                                 // i.e. only if we have not descended into a bivariant position.
62408                                 if (contravariant && !bivariant) {
62409                                     if (!ts.contains(inference.contraCandidates, candidate)) {
62410                                         inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
62411                                         clearCachedInferences(inferences);
62412                                     }
62413                                 }
62414                                 else if (!ts.contains(inference.candidates, candidate)) {
62415                                     inference.candidates = ts.append(inference.candidates, candidate);
62416                                     clearCachedInferences(inferences);
62417                                 }
62418                             }
62419                             if (!(priority & 64 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
62420                                 inference.topLevel = false;
62421                                 clearCachedInferences(inferences);
62422                             }
62423                         }
62424                         inferencePriority = Math.min(inferencePriority, priority);
62425                         return;
62426                     }
62427                     else {
62428                         // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine
62429                         var simplified = getSimplifiedType(target, /*writing*/ false);
62430                         if (simplified !== target) {
62431                             invokeOnce(source, simplified, inferFromTypes);
62432                         }
62433                         else if (target.flags & 8388608 /* IndexedAccess */) {
62434                             var indexType = getSimplifiedType(target.indexType, /*writing*/ false);
62435                             // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider
62436                             // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can.
62437                             if (indexType.flags & 465829888 /* Instantiable */) {
62438                                 var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false);
62439                                 if (simplified_1 && simplified_1 !== target) {
62440                                     invokeOnce(source, simplified_1, inferFromTypes);
62441                                 }
62442                             }
62443                         }
62444                     }
62445                 }
62446                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target)) &&
62447                     !(source.node && target.node)) {
62448                     // If source and target are references to the same generic type, infer from type arguments
62449                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
62450                 }
62451                 else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) {
62452                     contravariant = !contravariant;
62453                     inferFromTypes(source.type, target.type);
62454                     contravariant = !contravariant;
62455                 }
62456                 else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) {
62457                     var empty = createEmptyObjectTypeFromStringLiteral(source);
62458                     contravariant = !contravariant;
62459                     inferWithPriority(empty, target.type, 128 /* LiteralKeyof */);
62460                     contravariant = !contravariant;
62461                 }
62462                 else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
62463                     inferFromTypes(source.objectType, target.objectType);
62464                     inferFromTypes(source.indexType, target.indexType);
62465                 }
62466                 else if (source.flags & 268435456 /* StringMapping */ && target.flags & 268435456 /* StringMapping */) {
62467                     if (source.symbol === target.symbol) {
62468                         inferFromTypes(source.type, target.type);
62469                     }
62470                 }
62471                 else if (target.flags & 16777216 /* Conditional */) {
62472                     invokeOnce(source, target, inferToConditionalType);
62473                 }
62474                 else if (target.flags & 3145728 /* UnionOrIntersection */) {
62475                     inferToMultipleTypes(source, target.types, target.flags);
62476                 }
62477                 else if (source.flags & 1048576 /* Union */) {
62478                     // Source is a union or intersection type, infer from each constituent type
62479                     var sourceTypes = source.types;
62480                     for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) {
62481                         var sourceType = sourceTypes_2[_e];
62482                         inferFromTypes(sourceType, target);
62483                     }
62484                 }
62485                 else if (target.flags & 134217728 /* TemplateLiteral */) {
62486                     inferToTemplateLiteralType(source, target);
62487                 }
62488                 else {
62489                     source = getReducedType(source);
62490                     if (!(priority & 256 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) {
62491                         var apparentSource = getApparentType(source);
62492                         // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type.
62493                         // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes`
62494                         // with the simplified source.
62495                         if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) {
62496                             // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints!
62497                             // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference
62498                             // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
62499                             // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
62500                             // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
62501                             // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
62502                             // remove this `allowComplexConstraintInference` flag.
62503                             allowComplexConstraintInference = false;
62504                             return inferFromTypes(apparentSource, target);
62505                         }
62506                         source = apparentSource;
62507                     }
62508                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
62509                         invokeOnce(source, target, inferFromObjectTypes);
62510                     }
62511                 }
62512             }
62513             function inferWithPriority(source, target, newPriority) {
62514                 var savePriority = priority;
62515                 priority |= newPriority;
62516                 inferFromTypes(source, target);
62517                 priority = savePriority;
62518             }
62519             function invokeOnce(source, target, action) {
62520                 var key = source.id + "," + target.id;
62521                 var status = visited && visited.get(key);
62522                 if (status !== undefined) {
62523                     inferencePriority = Math.min(inferencePriority, status);
62524                     return;
62525                 }
62526                 (visited || (visited = new ts.Map())).set(key, -1 /* Circularity */);
62527                 var saveInferencePriority = inferencePriority;
62528                 inferencePriority = 1024 /* MaxValue */;
62529                 // We stop inferring and report a circularity if we encounter duplicate recursion identities on both
62530                 // the source side and the target side.
62531                 var saveExpandingFlags = expandingFlags;
62532                 var sourceIdentity = getRecursionIdentity(source) || source;
62533                 var targetIdentity = getRecursionIdentity(target) || target;
62534                 if (sourceIdentity && ts.contains(sourceStack, sourceIdentity))
62535                     expandingFlags |= 1 /* Source */;
62536                 if (targetIdentity && ts.contains(targetStack, targetIdentity))
62537                     expandingFlags |= 2 /* Target */;
62538                 if (expandingFlags !== 3 /* Both */) {
62539                     if (sourceIdentity)
62540                         (sourceStack || (sourceStack = [])).push(sourceIdentity);
62541                     if (targetIdentity)
62542                         (targetStack || (targetStack = [])).push(targetIdentity);
62543                     action(source, target);
62544                     if (targetIdentity)
62545                         targetStack.pop();
62546                     if (sourceIdentity)
62547                         sourceStack.pop();
62548                 }
62549                 else {
62550                     inferencePriority = -1 /* Circularity */;
62551                 }
62552                 expandingFlags = saveExpandingFlags;
62553                 visited.set(key, inferencePriority);
62554                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
62555             }
62556             function inferFromMatchingTypes(sources, targets, matches) {
62557                 var matchedSources;
62558                 var matchedTargets;
62559                 for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
62560                     var t = targets_1[_i];
62561                     for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {
62562                         var s = sources_1[_a];
62563                         if (matches(s, t)) {
62564                             inferFromTypes(s, t);
62565                             matchedSources = ts.appendIfUnique(matchedSources, s);
62566                             matchedTargets = ts.appendIfUnique(matchedTargets, t);
62567                         }
62568                     }
62569                 }
62570                 return [
62571                     matchedSources ? ts.filter(sources, function (t) { return !ts.contains(matchedSources, t); }) : sources,
62572                     matchedTargets ? ts.filter(targets, function (t) { return !ts.contains(matchedTargets, t); }) : targets,
62573                 ];
62574             }
62575             function inferFromTypeArguments(sourceTypes, targetTypes, variances) {
62576                 var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
62577                 for (var i = 0; i < count; i++) {
62578                     if (i < variances.length && (variances[i] & 7 /* VarianceMask */) === 2 /* Contravariant */) {
62579                         inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
62580                     }
62581                     else {
62582                         inferFromTypes(sourceTypes[i], targetTypes[i]);
62583                     }
62584                 }
62585             }
62586             function inferFromContravariantTypes(source, target) {
62587                 if (strictFunctionTypes || priority & 512 /* AlwaysStrict */) {
62588                     contravariant = !contravariant;
62589                     inferFromTypes(source, target);
62590                     contravariant = !contravariant;
62591                 }
62592                 else {
62593                     inferFromTypes(source, target);
62594                 }
62595             }
62596             function getInferenceInfoForType(type) {
62597                 if (type.flags & 8650752 /* TypeVariable */) {
62598                     for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
62599                         var inference = inferences_2[_i];
62600                         if (type === inference.typeParameter) {
62601                             return inference;
62602                         }
62603                     }
62604                 }
62605                 return undefined;
62606             }
62607             function getSingleTypeVariableFromIntersectionTypes(types) {
62608                 var typeVariable;
62609                 for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
62610                     var type = types_16[_i];
62611                     var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); });
62612                     if (!t || typeVariable && t !== typeVariable) {
62613                         return undefined;
62614                     }
62615                     typeVariable = t;
62616                 }
62617                 return typeVariable;
62618             }
62619             function inferToMultipleTypes(source, targets, targetFlags) {
62620                 var typeVariableCount = 0;
62621                 if (targetFlags & 1048576 /* Union */) {
62622                     var nakedTypeVariable = void 0;
62623                     var sources = source.flags & 1048576 /* Union */ ? source.types : [source];
62624                     var matched_1 = new Array(sources.length);
62625                     var inferenceCircularity = false;
62626                     // First infer to types that are not naked type variables. For each source type we
62627                     // track whether inferences were made from that particular type to some target with
62628                     // equal priority (i.e. of equal quality) to what we would infer for a naked type
62629                     // parameter.
62630                     for (var _i = 0, targets_2 = targets; _i < targets_2.length; _i++) {
62631                         var t = targets_2[_i];
62632                         if (getInferenceInfoForType(t)) {
62633                             nakedTypeVariable = t;
62634                             typeVariableCount++;
62635                         }
62636                         else {
62637                             for (var i = 0; i < sources.length; i++) {
62638                                 var saveInferencePriority = inferencePriority;
62639                                 inferencePriority = 1024 /* MaxValue */;
62640                                 inferFromTypes(sources[i], t);
62641                                 if (inferencePriority === priority)
62642                                     matched_1[i] = true;
62643                                 inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */;
62644                                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
62645                             }
62646                         }
62647                     }
62648                     if (typeVariableCount === 0) {
62649                         // If every target is an intersection of types containing a single naked type variable,
62650                         // make a lower priority inference to that type variable. This handles inferring from
62651                         // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T.
62652                         var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets);
62653                         if (intersectionTypeVariable) {
62654                             inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */);
62655                         }
62656                         return;
62657                     }
62658                     // If the target has a single naked type variable and no inference circularities were
62659                     // encountered above (meaning we explored the types fully), create a union of the source
62660                     // types from which no inferences have been made so far and infer from that union to the
62661                     // naked type variable.
62662                     if (typeVariableCount === 1 && !inferenceCircularity) {
62663                         var unmatched = ts.flatMap(sources, function (s, i) { return matched_1[i] ? undefined : s; });
62664                         if (unmatched.length) {
62665                             inferFromTypes(getUnionType(unmatched), nakedTypeVariable);
62666                             return;
62667                         }
62668                     }
62669                 }
62670                 else {
62671                     // We infer from types that are not naked type variables first so that inferences we
62672                     // make from nested naked type variables and given slightly higher priority by virtue
62673                     // of being first in the candidates array.
62674                     for (var _a = 0, targets_3 = targets; _a < targets_3.length; _a++) {
62675                         var t = targets_3[_a];
62676                         if (getInferenceInfoForType(t)) {
62677                             typeVariableCount++;
62678                         }
62679                         else {
62680                             inferFromTypes(source, t);
62681                         }
62682                     }
62683                 }
62684                 // Inferences directly to naked type variables are given lower priority as they are
62685                 // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
62686                 // we want to infer string for T, not Promise<string> | string. For intersection types
62687                 // we only infer to single naked type variables.
62688                 if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) {
62689                     for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) {
62690                         var t = targets_4[_b];
62691                         if (getInferenceInfoForType(t)) {
62692                             inferWithPriority(source, t, 1 /* NakedTypeVariable */);
62693                         }
62694                     }
62695                 }
62696             }
62697             function inferToMappedType(source, target, constraintType) {
62698                 if (constraintType.flags & 1048576 /* Union */) {
62699                     var result = false;
62700                     for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
62701                         var type = _a[_i];
62702                         result = inferToMappedType(source, target, type) || result;
62703                     }
62704                     return result;
62705                 }
62706                 if (constraintType.flags & 4194304 /* Index */) {
62707                     // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
62708                     // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
62709                     // type and then make a secondary inference from that type to T. We make a secondary inference
62710                     // such that direct inferences to T get priority over inferences to Partial<T>, for example.
62711                     var inference = getInferenceInfoForType(constraintType.type);
62712                     if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) {
62713                         var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType);
62714                         if (inferredType) {
62715                             // We assign a lower priority to inferences made from types containing non-inferrable
62716                             // types because we may only have a partial result (i.e. we may have failed to make
62717                             // reverse inferences for some properties).
62718                             inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ?
62719                                 8 /* PartialHomomorphicMappedType */ :
62720                                 4 /* HomomorphicMappedType */);
62721                         }
62722                     }
62723                     return true;
62724                 }
62725                 if (constraintType.flags & 262144 /* TypeParameter */) {
62726                     // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
62727                     // parameter. First infer from 'keyof S' to K.
62728                     inferWithPriority(getIndexType(source), constraintType, 16 /* MappedTypeConstraint */);
62729                     // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
62730                     // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
62731                     // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
62732                     // Pick<T, K>.
62733                     var extendedConstraint = getConstraintOfType(constraintType);
62734                     if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
62735                         return true;
62736                     }
62737                     // If no inferences can be made to K's constraint, infer from a union of the property types
62738                     // in the source to the template type X.
62739                     var propTypes = ts.map(getPropertiesOfType(source), getTypeOfSymbol);
62740                     var stringIndexType = getIndexTypeOfType(source, 0 /* String */);
62741                     var numberIndexInfo = getNonEnumNumberIndexInfo(source);
62742                     var numberIndexType = numberIndexInfo && numberIndexInfo.type;
62743                     inferFromTypes(getUnionType(ts.append(ts.append(propTypes, stringIndexType), numberIndexType)), getTemplateTypeFromMappedType(target));
62744                     return true;
62745                 }
62746                 return false;
62747             }
62748             function inferToConditionalType(source, target) {
62749                 if (source.flags & 16777216 /* Conditional */) {
62750                     inferFromTypes(source.checkType, target.checkType);
62751                     inferFromTypes(source.extendsType, target.extendsType);
62752                     inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
62753                     inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
62754                 }
62755                 else {
62756                     var savePriority = priority;
62757                     priority |= contravariant ? 32 /* ContravariantConditional */ : 0;
62758                     var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)];
62759                     inferToMultipleTypes(source, targetTypes, target.flags);
62760                     priority = savePriority;
62761                 }
62762             }
62763             function inferToTemplateLiteralType(source, target) {
62764                 var matches = source.flags & 128 /* StringLiteral */ ? inferLiteralsFromTemplateLiteralType(source, target) :
62765                     source.flags & 134217728 /* TemplateLiteral */ && ts.arraysEqual(source.texts, target.texts) ? source.types :
62766                         undefined;
62767                 var types = target.types;
62768                 for (var i = 0; i < types.length; i++) {
62769                     inferFromTypes(matches ? matches[i] : neverType, types[i]);
62770                 }
62771             }
62772             function inferFromObjectTypes(source, target) {
62773                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target))) {
62774                     // If source and target are references to the same generic type, infer from type arguments
62775                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
62776                     return;
62777                 }
62778                 if (isGenericMappedType(source) && isGenericMappedType(target)) {
62779                     // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
62780                     // from S to T and from X to Y.
62781                     inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
62782                     inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
62783                     var sourceNameType = getNameTypeFromMappedType(source);
62784                     var targetNameType = getNameTypeFromMappedType(target);
62785                     if (sourceNameType && targetNameType)
62786                         inferFromTypes(sourceNameType, targetNameType);
62787                 }
62788                 if (ts.getObjectFlags(target) & 32 /* Mapped */ && !target.declaration.nameType) {
62789                     var constraintType = getConstraintTypeFromMappedType(target);
62790                     if (inferToMappedType(source, target, constraintType)) {
62791                         return;
62792                     }
62793                 }
62794                 // Infer from the members of source and target only if the two types are possibly related
62795                 if (!typesDefinitelyUnrelated(source, target)) {
62796                     if (isArrayType(source) || isTupleType(source)) {
62797                         if (isTupleType(target)) {
62798                             var sourceArity = getTypeReferenceArity(source);
62799                             var targetArity = getTypeReferenceArity(target);
62800                             var elementTypes = getTypeArguments(target);
62801                             var elementFlags = target.target.elementFlags;
62802                             // When source and target are tuple types with the same structure (fixed, variadic, and rest are matched
62803                             // to the same kind in each position), simply infer between the element types.
62804                             if (isTupleType(source) && isTupleTypeStructureMatching(source, target)) {
62805                                 for (var i = 0; i < targetArity; i++) {
62806                                     inferFromTypes(getTypeArguments(source)[i], elementTypes[i]);
62807                                 }
62808                                 return;
62809                             }
62810                             var startLength = isTupleType(source) ? Math.min(source.target.fixedLength, target.target.fixedLength) : 0;
62811                             var endLength = Math.min(isTupleType(source) ? getEndElementCount(source.target, 3 /* Fixed */) : 0, target.target.hasRestElement ? getEndElementCount(target.target, 3 /* Fixed */) : 0);
62812                             // Infer between starting fixed elements.
62813                             for (var i = 0; i < startLength; i++) {
62814                                 inferFromTypes(getTypeArguments(source)[i], elementTypes[i]);
62815                             }
62816                             if (!isTupleType(source) || sourceArity - startLength - endLength === 1 && source.target.elementFlags[startLength] & 4 /* Rest */) {
62817                                 // Single rest element remains in source, infer from that to every element in target
62818                                 var restType = getTypeArguments(source)[startLength];
62819                                 for (var i = startLength; i < targetArity - endLength; i++) {
62820                                     inferFromTypes(elementFlags[i] & 8 /* Variadic */ ? createArrayType(restType) : restType, elementTypes[i]);
62821                                 }
62822                             }
62823                             else {
62824                                 var middleLength = targetArity - startLength - endLength;
62825                                 if (middleLength === 2 && elementFlags[startLength] & elementFlags[startLength + 1] & 8 /* Variadic */ && isTupleType(source)) {
62826                                     // Middle of target is [...T, ...U] and source is tuple type
62827                                     var targetInfo = getInferenceInfoForType(elementTypes[startLength]);
62828                                     if (targetInfo && targetInfo.impliedArity !== undefined) {
62829                                         // Infer slices from source based on implied arity of T.
62830                                         inferFromTypes(sliceTupleType(source, startLength, endLength + sourceArity - targetInfo.impliedArity), elementTypes[startLength]);
62831                                         inferFromTypes(sliceTupleType(source, startLength + targetInfo.impliedArity, endLength), elementTypes[startLength + 1]);
62832                                     }
62833                                 }
62834                                 else if (middleLength === 1 && elementFlags[startLength] & 8 /* Variadic */) {
62835                                     // Middle of target is exactly one variadic element. Infer the slice between the fixed parts in the source.
62836                                     // If target ends in optional element(s), make a lower priority a speculative inference.
62837                                     var endsInOptional = target.target.elementFlags[targetArity - 1] & 2 /* Optional */;
62838                                     var sourceSlice = isTupleType(source) ? sliceTupleType(source, startLength, endLength) : createArrayType(getTypeArguments(source)[0]);
62839                                     inferWithPriority(sourceSlice, elementTypes[startLength], endsInOptional ? 2 /* SpeculativeTuple */ : 0);
62840                                 }
62841                                 else if (middleLength === 1 && elementFlags[startLength] & 4 /* Rest */) {
62842                                     // Middle of target is exactly one rest element. If middle of source is not empty, infer union of middle element types.
62843                                     var restType = isTupleType(source) ? getElementTypeOfSliceOfTupleType(source, startLength, endLength) : getTypeArguments(source)[0];
62844                                     if (restType) {
62845                                         inferFromTypes(restType, elementTypes[startLength]);
62846                                     }
62847                                 }
62848                             }
62849                             // Infer between ending fixed elements
62850                             for (var i = 0; i < endLength; i++) {
62851                                 inferFromTypes(getTypeArguments(source)[sourceArity - i - 1], elementTypes[targetArity - i - 1]);
62852                             }
62853                             return;
62854                         }
62855                         if (isArrayType(target)) {
62856                             inferFromIndexTypes(source, target);
62857                             return;
62858                         }
62859                     }
62860                     inferFromProperties(source, target);
62861                     inferFromSignatures(source, target, 0 /* Call */);
62862                     inferFromSignatures(source, target, 1 /* Construct */);
62863                     inferFromIndexTypes(source, target);
62864                 }
62865             }
62866             function inferFromProperties(source, target) {
62867                 var properties = getPropertiesOfObjectType(target);
62868                 for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
62869                     var targetProp = properties_3[_i];
62870                     var sourceProp = getPropertyOfType(source, targetProp.escapedName);
62871                     if (sourceProp) {
62872                         inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
62873                     }
62874                 }
62875             }
62876             function inferFromSignatures(source, target, kind) {
62877                 var sourceSignatures = getSignaturesOfType(source, kind);
62878                 var targetSignatures = getSignaturesOfType(target, kind);
62879                 var sourceLen = sourceSignatures.length;
62880                 var targetLen = targetSignatures.length;
62881                 var len = sourceLen < targetLen ? sourceLen : targetLen;
62882                 var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */);
62883                 for (var i = 0; i < len; i++) {
62884                     inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters);
62885                 }
62886             }
62887             function inferFromSignature(source, target, skipParameters) {
62888                 if (!skipParameters) {
62889                     var saveBivariant = bivariant;
62890                     var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
62891                     // Once we descend into a bivariant signature we remain bivariant for all nested inferences
62892                     bivariant = bivariant || kind === 165 /* MethodDeclaration */ || kind === 164 /* MethodSignature */ || kind === 166 /* Constructor */;
62893                     applyToParameterTypes(source, target, inferFromContravariantTypes);
62894                     bivariant = saveBivariant;
62895                 }
62896                 applyToReturnTypes(source, target, inferFromTypes);
62897             }
62898             function inferFromIndexTypes(source, target) {
62899                 var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
62900                 if (targetStringIndexType) {
62901                     var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) ||
62902                         getImplicitIndexTypeOfType(source, 0 /* String */);
62903                     if (sourceIndexType) {
62904                         inferFromTypes(sourceIndexType, targetStringIndexType);
62905                     }
62906                 }
62907                 var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */);
62908                 if (targetNumberIndexType) {
62909                     var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) ||
62910                         getIndexTypeOfType(source, 0 /* String */) ||
62911                         getImplicitIndexTypeOfType(source, 1 /* Number */);
62912                     if (sourceIndexType) {
62913                         inferFromTypes(sourceIndexType, targetNumberIndexType);
62914                     }
62915                 }
62916             }
62917         }
62918         function isTypeOrBaseIdenticalTo(s, t) {
62919             return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */);
62920         }
62921         function isTypeCloselyMatchedBy(s, t) {
62922             return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol ||
62923                 s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol);
62924         }
62925         function hasPrimitiveConstraint(type) {
62926             var constraint = getConstraintOfTypeParameter(type);
62927             return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */);
62928         }
62929         function isObjectLiteralType(type) {
62930             return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */);
62931         }
62932         function isObjectOrArrayLiteralType(type) {
62933             return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */));
62934         }
62935         function unionObjectAndArrayLiteralCandidates(candidates) {
62936             if (candidates.length > 1) {
62937                 var objectLiterals = ts.filter(candidates, isObjectOrArrayLiteralType);
62938                 if (objectLiterals.length) {
62939                     var literalsType = getUnionType(objectLiterals, 2 /* Subtype */);
62940                     return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectOrArrayLiteralType(t); }), [literalsType]);
62941                 }
62942             }
62943             return candidates;
62944         }
62945         function getContravariantInference(inference) {
62946             return inference.priority & 208 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
62947         }
62948         function getCovariantInference(inference, signature) {
62949             // Extract all object and array literal types and replace them with a single widened and normalized type.
62950             var candidates = unionObjectAndArrayLiteralCandidates(inference.candidates);
62951             // We widen inferred literal types if
62952             // all inferences were made to top-level occurrences of the type parameter, and
62953             // the type parameter has no constraint or its constraint includes no primitive or literal types, and
62954             // the type parameter was fixed during inference or does not occur at top-level in the return type.
62955             var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter);
62956             var widenLiteralTypes = !primitiveConstraint && inference.topLevel &&
62957                 (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
62958             var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) :
62959                 widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) :
62960                     candidates;
62961             // If all inferences were made from a position that implies a combined result, infer a union type.
62962             // Otherwise, infer a common supertype.
62963             var unwidenedType = inference.priority & 208 /* PriorityImpliesCombination */ ?
62964                 getUnionType(baseCandidates, 2 /* Subtype */) :
62965                 getCommonSupertype(baseCandidates);
62966             return getWidenedType(unwidenedType);
62967         }
62968         function getInferredType(context, index) {
62969             var inference = context.inferences[index];
62970             if (!inference.inferredType) {
62971                 var inferredType = void 0;
62972                 var signature = context.signature;
62973                 if (signature) {
62974                     var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined;
62975                     if (inference.contraCandidates) {
62976                         var inferredContravariantType = getContravariantInference(inference);
62977                         // If we have both co- and contra-variant inferences, we prefer the contra-variant inference
62978                         // unless the co-variant inference is a subtype and not 'never'.
62979                         inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) &&
62980                             isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ?
62981                             inferredCovariantType : inferredContravariantType;
62982                     }
62983                     else if (inferredCovariantType) {
62984                         inferredType = inferredCovariantType;
62985                     }
62986                     else if (context.flags & 1 /* NoDefault */) {
62987                         // We use silentNeverType as the wildcard that signals no inferences.
62988                         inferredType = silentNeverType;
62989                     }
62990                     else {
62991                         // Infer either the default or the empty object type when no inferences were
62992                         // made. It is important to remember that in this case, inference still
62993                         // succeeds, meaning there is no error for not having inference candidates. An
62994                         // inference error only occurs when there are *conflicting* candidates, i.e.
62995                         // candidates with no common supertype.
62996                         var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
62997                         if (defaultType) {
62998                             // Instantiate the default type. Any forward reference to a type
62999                             // parameter should be instantiated to the empty object type.
63000                             inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
63001                         }
63002                     }
63003                 }
63004                 else {
63005                     inferredType = getTypeFromInference(inference);
63006                 }
63007                 inference.inferredType = inferredType || getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
63008                 var constraint = getConstraintOfTypeParameter(inference.typeParameter);
63009                 if (constraint) {
63010                     var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
63011                     if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
63012                         inference.inferredType = inferredType = instantiatedConstraint;
63013                     }
63014                 }
63015             }
63016             return inference.inferredType;
63017         }
63018         function getDefaultTypeArgumentType(isInJavaScriptFile) {
63019             return isInJavaScriptFile ? anyType : unknownType;
63020         }
63021         function getInferredTypes(context) {
63022             var result = [];
63023             for (var i = 0; i < context.inferences.length; i++) {
63024                 result.push(getInferredType(context, i));
63025             }
63026             return result;
63027         }
63028         // EXPRESSION TYPE CHECKING
63029         function getCannotFindNameDiagnosticForName(node) {
63030             switch (node.escapedText) {
63031                 case "document":
63032                 case "console":
63033                     return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
63034                 case "$":
63035                     return compilerOptions.types
63036                         ? 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
63037                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery;
63038                 case "describe":
63039                 case "suite":
63040                 case "it":
63041                 case "test":
63042                     return compilerOptions.types
63043                         ? 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
63044                         : 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;
63045                 case "process":
63046                 case "require":
63047                 case "Buffer":
63048                 case "module":
63049                     return compilerOptions.types
63050                         ? 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
63051                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode;
63052                 case "Map":
63053                 case "Set":
63054                 case "Promise":
63055                 case "Symbol":
63056                 case "WeakMap":
63057                 case "WeakSet":
63058                 case "Iterator":
63059                 case "AsyncIterator":
63060                 case "SharedArrayBuffer":
63061                 case "Atomics":
63062                 case "AsyncIterable":
63063                 case "AsyncIterableIterator":
63064                 case "AsyncGenerator":
63065                 case "AsyncGeneratorFunction":
63066                 case "BigInt":
63067                 case "Reflect":
63068                 case "BigInt64Array":
63069                 case "BigUint64Array":
63070                     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;
63071                 default:
63072                     if (node.parent.kind === 289 /* ShorthandPropertyAssignment */) {
63073                         return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer;
63074                     }
63075                     else {
63076                         return ts.Diagnostics.Cannot_find_name_0;
63077                     }
63078             }
63079         }
63080         function getResolvedSymbol(node) {
63081             var links = getNodeLinks(node);
63082             if (!links.resolvedSymbol) {
63083                 links.resolvedSymbol = !ts.nodeIsMissing(node) &&
63084                     resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), 
63085                     /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol;
63086             }
63087             return links.resolvedSymbol;
63088         }
63089         function isInTypeQuery(node) {
63090             // TypeScript 1.0 spec (April 2014): 3.6.3
63091             // A type query consists of the keyword typeof followed by an expression.
63092             // The expression is restricted to a single identifier or a sequence of identifiers separated by periods
63093             return !!ts.findAncestor(node, function (n) { return n.kind === 176 /* TypeQuery */ ? true : n.kind === 78 /* Identifier */ || n.kind === 157 /* QualifiedName */ ? false : "quit"; });
63094         }
63095         // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers
63096         // separated by dots). The key consists of the id of the symbol referenced by the
63097         // leftmost identifier followed by zero or more property names separated by dots.
63098         // The result is undefined if the reference isn't a dotted name. We prefix nodes
63099         // occurring in an apparent type position with '@' because the control flow type
63100         // of such nodes may be based on the apparent type instead of the declared type.
63101         function getFlowCacheKey(node, declaredType, initialType, flowContainer) {
63102             switch (node.kind) {
63103                 case 78 /* Identifier */:
63104                     var symbol = getResolvedSymbol(node);
63105                     return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
63106                 case 107 /* ThisKeyword */:
63107                     return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType);
63108                 case 225 /* NonNullExpression */:
63109                 case 207 /* ParenthesizedExpression */:
63110                     return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
63111                 case 201 /* PropertyAccessExpression */:
63112                 case 202 /* ElementAccessExpression */:
63113                     var propName = getAccessedPropertyName(node);
63114                     if (propName !== undefined) {
63115                         var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
63116                         return key && key + "." + propName;
63117                     }
63118             }
63119             return undefined;
63120         }
63121         function isMatchingReference(source, target) {
63122             switch (target.kind) {
63123                 case 207 /* ParenthesizedExpression */:
63124                 case 225 /* NonNullExpression */:
63125                     return isMatchingReference(source, target.expression);
63126                 case 216 /* BinaryExpression */:
63127                     return (ts.isAssignmentExpression(target) && isMatchingReference(source, target.left)) ||
63128                         (ts.isBinaryExpression(target) && target.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source, target.right));
63129             }
63130             switch (source.kind) {
63131                 case 78 /* Identifier */:
63132                 case 79 /* PrivateIdentifier */:
63133                     return target.kind === 78 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) ||
63134                         (target.kind === 249 /* VariableDeclaration */ || target.kind === 198 /* BindingElement */) &&
63135                             getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target);
63136                 case 107 /* ThisKeyword */:
63137                     return target.kind === 107 /* ThisKeyword */;
63138                 case 105 /* SuperKeyword */:
63139                     return target.kind === 105 /* SuperKeyword */;
63140                 case 225 /* NonNullExpression */:
63141                 case 207 /* ParenthesizedExpression */:
63142                     return isMatchingReference(source.expression, target);
63143                 case 201 /* PropertyAccessExpression */:
63144                 case 202 /* ElementAccessExpression */:
63145                     return ts.isAccessExpression(target) &&
63146                         getAccessedPropertyName(source) === getAccessedPropertyName(target) &&
63147                         isMatchingReference(source.expression, target.expression);
63148                 case 157 /* QualifiedName */:
63149                     return ts.isAccessExpression(target) &&
63150                         source.right.escapedText === getAccessedPropertyName(target) &&
63151                         isMatchingReference(source.left, target.expression);
63152                 case 216 /* BinaryExpression */:
63153                     return (ts.isBinaryExpression(source) && source.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source.right, target));
63154             }
63155             return false;
63156         }
63157         // Given a source x, check if target matches x or is an && operation with an operand that matches x.
63158         function containsTruthyCheck(source, target) {
63159             return isMatchingReference(source, target) ||
63160                 (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ &&
63161                     (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right)));
63162         }
63163         function getAccessedPropertyName(access) {
63164             return access.kind === 201 /* PropertyAccessExpression */ ? access.name.escapedText :
63165                 ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) :
63166                     undefined;
63167         }
63168         function containsMatchingReference(source, target) {
63169             while (ts.isAccessExpression(source)) {
63170                 source = source.expression;
63171                 if (isMatchingReference(source, target)) {
63172                     return true;
63173                 }
63174             }
63175             return false;
63176         }
63177         function optionalChainContainsReference(source, target) {
63178             while (ts.isOptionalChain(source)) {
63179                 source = source.expression;
63180                 if (isMatchingReference(source, target)) {
63181                     return true;
63182                 }
63183             }
63184             return false;
63185         }
63186         function isDiscriminantProperty(type, name) {
63187             if (type && type.flags & 1048576 /* Union */) {
63188                 var prop = getUnionOrIntersectionProperty(type, name);
63189                 if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) {
63190                     if (prop.isDiscriminantProperty === undefined) {
63191                         prop.isDiscriminantProperty =
63192                             (prop.checkFlags & 192 /* Discriminant */) === 192 /* Discriminant */ &&
63193                                 !maybeTypeOfKind(getTypeOfSymbol(prop), 465829888 /* Instantiable */);
63194                     }
63195                     return !!prop.isDiscriminantProperty;
63196                 }
63197             }
63198             return false;
63199         }
63200         function findDiscriminantProperties(sourceProperties, target) {
63201             var result;
63202             for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) {
63203                 var sourceProperty = sourceProperties_2[_i];
63204                 if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
63205                     if (result) {
63206                         result.push(sourceProperty);
63207                         continue;
63208                     }
63209                     result = [sourceProperty];
63210                 }
63211             }
63212             return result;
63213         }
63214         function isOrContainsMatchingReference(source, target) {
63215             return isMatchingReference(source, target) || containsMatchingReference(source, target);
63216         }
63217         function hasMatchingArgument(expression, reference) {
63218             if (expression.arguments) {
63219                 for (var _i = 0, _a = expression.arguments; _i < _a.length; _i++) {
63220                     var argument = _a[_i];
63221                     if (isOrContainsMatchingReference(reference, argument)) {
63222                         return true;
63223                     }
63224                 }
63225             }
63226             if (expression.expression.kind === 201 /* PropertyAccessExpression */ &&
63227                 isOrContainsMatchingReference(reference, expression.expression.expression)) {
63228                 return true;
63229             }
63230             return false;
63231         }
63232         function getFlowNodeId(flow) {
63233             if (!flow.id || flow.id < 0) {
63234                 flow.id = nextFlowId;
63235                 nextFlowId++;
63236             }
63237             return flow.id;
63238         }
63239         function typeMaybeAssignableTo(source, target) {
63240             if (!(source.flags & 1048576 /* Union */)) {
63241                 return isTypeAssignableTo(source, target);
63242             }
63243             for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
63244                 var t = _a[_i];
63245                 if (isTypeAssignableTo(t, target)) {
63246                     return true;
63247                 }
63248             }
63249             return false;
63250         }
63251         // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable.
63252         // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean,
63253         // we remove type string.
63254         function getAssignmentReducedType(declaredType, assignedType) {
63255             if (declaredType !== assignedType) {
63256                 if (assignedType.flags & 131072 /* Never */) {
63257                     return assignedType;
63258                 }
63259                 var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); });
63260                 if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) {
63261                     reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types
63262                 }
63263                 // Our crude heuristic produces an invalid result in some cases: see GH#26130.
63264                 // For now, when that happens, we give up and don't narrow at all.  (This also
63265                 // means we'll never narrow for erroneous assignments where the assigned type
63266                 // is not assignable to the declared type.)
63267                 if (isTypeAssignableTo(assignedType, reducedType)) {
63268                     return reducedType;
63269                 }
63270             }
63271             return declaredType;
63272         }
63273         function getTypeFactsOfTypes(types) {
63274             var result = 0 /* None */;
63275             for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
63276                 var t = types_17[_i];
63277                 result |= getTypeFacts(t);
63278             }
63279             return result;
63280         }
63281         function isFunctionObjectType(type) {
63282             // We do a quick check for a "bind" property before performing the more expensive subtype
63283             // check. This gives us a quicker out in the common case where an object type is not a function.
63284             var resolved = resolveStructuredTypeMembers(type);
63285             return !!(resolved.callSignatures.length || resolved.constructSignatures.length ||
63286                 resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
63287         }
63288         function getTypeFacts(type) {
63289             var flags = type.flags;
63290             if (flags & 4 /* String */) {
63291                 return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
63292             }
63293             if (flags & 128 /* StringLiteral */) {
63294                 var isEmpty = type.value === "";
63295                 return strictNullChecks ?
63296                     isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ :
63297                     isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
63298             }
63299             if (flags & (8 /* Number */ | 32 /* Enum */)) {
63300                 return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
63301             }
63302             if (flags & 256 /* NumberLiteral */) {
63303                 var isZero = type.value === 0;
63304                 return strictNullChecks ?
63305                     isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ :
63306                     isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
63307             }
63308             if (flags & 64 /* BigInt */) {
63309                 return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
63310             }
63311             if (flags & 2048 /* BigIntLiteral */) {
63312                 var isZero = isZeroBigInt(type);
63313                 return strictNullChecks ?
63314                     isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ :
63315                     isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
63316             }
63317             if (flags & 16 /* Boolean */) {
63318                 return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
63319             }
63320             if (flags & 528 /* BooleanLike */) {
63321                 return strictNullChecks ?
63322                     (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ :
63323                     (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
63324             }
63325             if (flags & 524288 /* Object */) {
63326                 return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ?
63327                     strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ :
63328                     isFunctionObjectType(type) ?
63329                         strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ :
63330                         strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
63331             }
63332             if (flags & (16384 /* Void */ | 32768 /* Undefined */)) {
63333                 return 9830144 /* UndefinedFacts */;
63334             }
63335             if (flags & 65536 /* Null */) {
63336                 return 9363232 /* NullFacts */;
63337             }
63338             if (flags & 12288 /* ESSymbolLike */) {
63339                 return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
63340             }
63341             if (flags & 67108864 /* NonPrimitive */) {
63342                 return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
63343             }
63344             if (flags & 131072 /* Never */) {
63345                 return 0 /* None */;
63346             }
63347             if (flags & 465829888 /* Instantiable */) {
63348                 return !isPatternLiteralType(type) ? getTypeFacts(getBaseConstraintOfType(type) || unknownType) :
63349                     strictNullChecks ? 7929345 /* NonEmptyStringStrictFacts */ : 16776705 /* NonEmptyStringFacts */;
63350             }
63351             if (flags & 3145728 /* UnionOrIntersection */) {
63352                 return getTypeFactsOfTypes(type.types);
63353             }
63354             return 16777215 /* All */;
63355         }
63356         function getTypeWithFacts(type, include) {
63357             return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
63358         }
63359         function getTypeWithDefault(type, defaultExpression) {
63360             if (defaultExpression) {
63361                 var defaultType = getTypeOfExpression(defaultExpression);
63362                 return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]);
63363             }
63364             return type;
63365         }
63366         function getTypeOfDestructuredProperty(type, name) {
63367             var nameType = getLiteralTypeFromPropertyName(name);
63368             if (!isTypeUsableAsPropertyName(nameType))
63369                 return errorType;
63370             var text = getPropertyNameFromType(nameType);
63371             return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) ||
63372                 isNumericLiteralName(text) && includeUndefinedInIndexSignature(getIndexTypeOfType(type, 1 /* Number */)) ||
63373                 includeUndefinedInIndexSignature(getIndexTypeOfType(type, 0 /* String */)) ||
63374                 errorType;
63375         }
63376         function getTypeOfDestructuredArrayElement(type, index) {
63377             return everyType(type, isTupleLikeType) && getTupleElementType(type, index) ||
63378                 includeUndefinedInIndexSignature(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined)) ||
63379                 errorType;
63380         }
63381         function includeUndefinedInIndexSignature(type) {
63382             if (!type)
63383                 return type;
63384             return compilerOptions.noUncheckedIndexedAccess ?
63385                 getUnionType([type, undefinedType]) :
63386                 type;
63387         }
63388         function getTypeOfDestructuredSpreadExpression(type) {
63389             return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType);
63390         }
63391         function getAssignedTypeOfBinaryExpression(node) {
63392             var isDestructuringDefaultAssignment = node.parent.kind === 199 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) ||
63393                 node.parent.kind === 288 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
63394             return isDestructuringDefaultAssignment ?
63395                 getTypeWithDefault(getAssignedType(node), node.right) :
63396                 getTypeOfExpression(node.right);
63397         }
63398         function isDestructuringAssignmentTarget(parent) {
63399             return parent.parent.kind === 216 /* BinaryExpression */ && parent.parent.left === parent ||
63400                 parent.parent.kind === 239 /* ForOfStatement */ && parent.parent.initializer === parent;
63401         }
63402         function getAssignedTypeOfArrayLiteralElement(node, element) {
63403             return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
63404         }
63405         function getAssignedTypeOfSpreadExpression(node) {
63406             return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
63407         }
63408         function getAssignedTypeOfPropertyAssignment(node) {
63409             return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
63410         }
63411         function getAssignedTypeOfShorthandPropertyAssignment(node) {
63412             return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
63413         }
63414         function getAssignedType(node) {
63415             var parent = node.parent;
63416             switch (parent.kind) {
63417                 case 238 /* ForInStatement */:
63418                     return stringType;
63419                 case 239 /* ForOfStatement */:
63420                     return checkRightHandSideOfForOf(parent) || errorType;
63421                 case 216 /* BinaryExpression */:
63422                     return getAssignedTypeOfBinaryExpression(parent);
63423                 case 210 /* DeleteExpression */:
63424                     return undefinedType;
63425                 case 199 /* ArrayLiteralExpression */:
63426                     return getAssignedTypeOfArrayLiteralElement(parent, node);
63427                 case 220 /* SpreadElement */:
63428                     return getAssignedTypeOfSpreadExpression(parent);
63429                 case 288 /* PropertyAssignment */:
63430                     return getAssignedTypeOfPropertyAssignment(parent);
63431                 case 289 /* ShorthandPropertyAssignment */:
63432                     return getAssignedTypeOfShorthandPropertyAssignment(parent);
63433             }
63434             return errorType;
63435         }
63436         function getInitialTypeOfBindingElement(node) {
63437             var pattern = node.parent;
63438             var parentType = getInitialType(pattern.parent);
63439             var type = pattern.kind === 196 /* ObjectBindingPattern */ ?
63440                 getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) :
63441                 !node.dotDotDotToken ?
63442                     getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) :
63443                     getTypeOfDestructuredSpreadExpression(parentType);
63444             return getTypeWithDefault(type, node.initializer);
63445         }
63446         function getTypeOfInitializer(node) {
63447             // Return the cached type if one is available. If the type of the variable was inferred
63448             // from its initializer, we'll already have cached the type. Otherwise we compute it now
63449             // without caching such that transient types are reflected.
63450             var links = getNodeLinks(node);
63451             return links.resolvedType || getTypeOfExpression(node);
63452         }
63453         function getInitialTypeOfVariableDeclaration(node) {
63454             if (node.initializer) {
63455                 return getTypeOfInitializer(node.initializer);
63456             }
63457             if (node.parent.parent.kind === 238 /* ForInStatement */) {
63458                 return stringType;
63459             }
63460             if (node.parent.parent.kind === 239 /* ForOfStatement */) {
63461                 return checkRightHandSideOfForOf(node.parent.parent) || errorType;
63462             }
63463             return errorType;
63464         }
63465         function getInitialType(node) {
63466             return node.kind === 249 /* VariableDeclaration */ ?
63467                 getInitialTypeOfVariableDeclaration(node) :
63468                 getInitialTypeOfBindingElement(node);
63469         }
63470         function isEmptyArrayAssignment(node) {
63471             return node.kind === 249 /* VariableDeclaration */ && node.initializer &&
63472                 isEmptyArrayLiteral(node.initializer) ||
63473                 node.kind !== 198 /* BindingElement */ && node.parent.kind === 216 /* BinaryExpression */ &&
63474                     isEmptyArrayLiteral(node.parent.right);
63475         }
63476         function getReferenceCandidate(node) {
63477             switch (node.kind) {
63478                 case 207 /* ParenthesizedExpression */:
63479                     return getReferenceCandidate(node.expression);
63480                 case 216 /* BinaryExpression */:
63481                     switch (node.operatorToken.kind) {
63482                         case 62 /* EqualsToken */:
63483                         case 74 /* BarBarEqualsToken */:
63484                         case 75 /* AmpersandAmpersandEqualsToken */:
63485                         case 76 /* QuestionQuestionEqualsToken */:
63486                             return getReferenceCandidate(node.left);
63487                         case 27 /* CommaToken */:
63488                             return getReferenceCandidate(node.right);
63489                     }
63490             }
63491             return node;
63492         }
63493         function getReferenceRoot(node) {
63494             var parent = node.parent;
63495             return parent.kind === 207 /* ParenthesizedExpression */ ||
63496                 parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node ||
63497                 parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ?
63498                 getReferenceRoot(parent) : node;
63499         }
63500         function getTypeOfSwitchClause(clause) {
63501             if (clause.kind === 284 /* CaseClause */) {
63502                 return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
63503             }
63504             return neverType;
63505         }
63506         function getSwitchClauseTypes(switchStatement) {
63507             var links = getNodeLinks(switchStatement);
63508             if (!links.switchTypes) {
63509                 links.switchTypes = [];
63510                 for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
63511                     var clause = _a[_i];
63512                     links.switchTypes.push(getTypeOfSwitchClause(clause));
63513                 }
63514             }
63515             return links.switchTypes;
63516         }
63517         function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) {
63518             var witnesses = [];
63519             for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
63520                 var clause = _a[_i];
63521                 if (clause.kind === 284 /* CaseClause */) {
63522                     if (ts.isStringLiteralLike(clause.expression)) {
63523                         witnesses.push(clause.expression.text);
63524                         continue;
63525                     }
63526                     return ts.emptyArray;
63527                 }
63528                 if (retainDefault)
63529                     witnesses.push(/*explicitDefaultStatement*/ undefined);
63530             }
63531             return witnesses;
63532         }
63533         function eachTypeContainedIn(source, types) {
63534             return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source);
63535         }
63536         function isTypeSubsetOf(source, target) {
63537             return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target);
63538         }
63539         function isTypeSubsetOfUnion(source, target) {
63540             if (source.flags & 1048576 /* Union */) {
63541                 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
63542                     var t = _a[_i];
63543                     if (!containsType(target.types, t)) {
63544                         return false;
63545                     }
63546                 }
63547                 return true;
63548             }
63549             if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) {
63550                 return true;
63551             }
63552             return containsType(target.types, source);
63553         }
63554         function forEachType(type, f) {
63555             return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type);
63556         }
63557         function everyType(type, f) {
63558             return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type);
63559         }
63560         function filterType(type, f) {
63561             if (type.flags & 1048576 /* Union */) {
63562                 var types = type.types;
63563                 var filtered = ts.filter(types, f);
63564                 if (filtered === types) {
63565                     return type;
63566                 }
63567                 var origin = type.origin;
63568                 var newOrigin = void 0;
63569                 if (origin && origin.flags & 1048576 /* Union */) {
63570                     // If the origin type is a (denormalized) union type, filter its non-union constituents. If that ends
63571                     // up removing a smaller number of types than in the normalized constituent set (meaning some of the
63572                     // filtered types are within nested unions in the origin), then we can't construct a new origin type.
63573                     // Otherwise, if we have exactly one type left in the origin set, return that as the filtered type.
63574                     // Otherwise, construct a new filtered origin type.
63575                     var originTypes = origin.types;
63576                     var originFiltered = ts.filter(originTypes, function (t) { return !!(t.flags & 1048576 /* Union */) || f(t); });
63577                     if (originTypes.length - originFiltered.length === types.length - filtered.length) {
63578                         if (originFiltered.length === 1) {
63579                             return originFiltered[0];
63580                         }
63581                         newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered);
63582                     }
63583                 }
63584                 return getUnionTypeFromSortedList(filtered, type.objectFlags, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, newOrigin);
63585             }
63586             return type.flags & 131072 /* Never */ || f(type) ? type : neverType;
63587         }
63588         function countTypes(type) {
63589             return type.flags & 1048576 /* Union */ ? type.types.length : 1;
63590         }
63591         function mapType(type, mapper, noReductions) {
63592             if (type.flags & 131072 /* Never */) {
63593                 return type;
63594             }
63595             if (!(type.flags & 1048576 /* Union */)) {
63596                 return mapper(type);
63597             }
63598             var origin = type.origin;
63599             var types = origin && origin.flags & 1048576 /* Union */ ? origin.types : type.types;
63600             var mappedTypes;
63601             var changed = false;
63602             for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
63603                 var t = types_18[_i];
63604                 var mapped = t.flags & 1048576 /* Union */ ? mapType(t, mapper, noReductions) : mapper(t);
63605                 changed || (changed = t !== mapped);
63606                 if (mapped) {
63607                     if (!mappedTypes) {
63608                         mappedTypes = [mapped];
63609                     }
63610                     else {
63611                         mappedTypes.push(mapped);
63612                     }
63613                 }
63614             }
63615             return changed ? mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : type;
63616         }
63617         function mapTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) {
63618             return type.flags & 1048576 /* Union */ && aliasSymbol ?
63619                 getUnionType(ts.map(type.types, mapper), 1 /* Literal */, aliasSymbol, aliasTypeArguments) :
63620                 mapType(type, mapper);
63621         }
63622         function getConstituentCount(type) {
63623             return type.flags & 3145728 /* UnionOrIntersection */ ? type.types.length : 1;
63624         }
63625         function extractTypesOfKind(type, kind) {
63626             return filterType(type, function (t) { return (t.flags & kind) !== 0; });
63627         }
63628         // Return a new type in which occurrences of the string and number primitive types in
63629         // typeWithPrimitives have been replaced with occurrences of string literals and numeric
63630         // literals in typeWithLiterals, respectively.
63631         function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
63632             if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) ||
63633                 isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) ||
63634                 isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) {
63635                 return mapType(typeWithPrimitives, function (t) {
63636                     return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) :
63637                         t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) :
63638                             t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t;
63639                 });
63640             }
63641             return typeWithPrimitives;
63642         }
63643         function isIncomplete(flowType) {
63644             return flowType.flags === 0;
63645         }
63646         function getTypeFromFlowType(flowType) {
63647             return flowType.flags === 0 ? flowType.type : flowType;
63648         }
63649         function createFlowType(type, incomplete) {
63650             return incomplete ? { flags: 0, type: type.flags & 131072 /* Never */ ? silentNeverType : type } : type;
63651         }
63652         // An evolving array type tracks the element types that have so far been seen in an
63653         // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving
63654         // array types are ultimately converted into manifest array types (using getFinalArrayType)
63655         // and never escape the getFlowTypeOfReference function.
63656         function createEvolvingArrayType(elementType) {
63657             var result = createObjectType(256 /* EvolvingArray */);
63658             result.elementType = elementType;
63659             return result;
63660         }
63661         function getEvolvingArrayType(elementType) {
63662             return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
63663         }
63664         // When adding evolving array element types we do not perform subtype reduction. Instead,
63665         // we defer subtype reduction until the evolving array type is finalized into a manifest
63666         // array type.
63667         function addEvolvingArrayElementType(evolvingArrayType, node) {
63668             var elementType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)));
63669             return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
63670         }
63671         function createFinalArrayType(elementType) {
63672             return elementType.flags & 131072 /* Never */ ?
63673                 autoArrayType :
63674                 createArrayType(elementType.flags & 1048576 /* Union */ ?
63675                     getUnionType(elementType.types, 2 /* Subtype */) :
63676                     elementType);
63677         }
63678         // We perform subtype reduction upon obtaining the final array type from an evolving array type.
63679         function getFinalArrayType(evolvingArrayType) {
63680             return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
63681         }
63682         function finalizeEvolvingArrayType(type) {
63683             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
63684         }
63685         function getElementTypeOfEvolvingArrayType(type) {
63686             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
63687         }
63688         function isEvolvingArrayTypeList(types) {
63689             var hasEvolvingArrayType = false;
63690             for (var _i = 0, types_19 = types; _i < types_19.length; _i++) {
63691                 var t = types_19[_i];
63692                 if (!(t.flags & 131072 /* Never */)) {
63693                     if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
63694                         return false;
63695                     }
63696                     hasEvolvingArrayType = true;
63697                 }
63698             }
63699             return hasEvolvingArrayType;
63700         }
63701         // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
63702         // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
63703         function isEvolvingArrayOperationTarget(node) {
63704             var root = getReferenceRoot(node);
63705             var parent = root.parent;
63706             var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" ||
63707                 parent.parent.kind === 203 /* CallExpression */
63708                     && ts.isIdentifier(parent.name)
63709                     && ts.isPushOrUnshiftIdentifier(parent.name));
63710             var isElementAssignment = parent.kind === 202 /* ElementAccessExpression */ &&
63711                 parent.expression === root &&
63712                 parent.parent.kind === 216 /* BinaryExpression */ &&
63713                 parent.parent.operatorToken.kind === 62 /* EqualsToken */ &&
63714                 parent.parent.left === parent &&
63715                 !ts.isAssignmentTarget(parent.parent) &&
63716                 isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */);
63717             return isLengthPushOrUnshift || isElementAssignment;
63718         }
63719         function isDeclarationWithExplicitTypeAnnotation(declaration) {
63720             return (declaration.kind === 249 /* VariableDeclaration */ || declaration.kind === 160 /* Parameter */ ||
63721                 declaration.kind === 163 /* PropertyDeclaration */ || declaration.kind === 162 /* PropertySignature */) &&
63722                 !!ts.getEffectiveTypeAnnotationNode(declaration);
63723         }
63724         function getExplicitTypeOfSymbol(symbol, diagnostic) {
63725             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) {
63726                 return getTypeOfSymbol(symbol);
63727             }
63728             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
63729                 if (ts.getCheckFlags(symbol) & 262144 /* Mapped */) {
63730                     var origin = symbol.syntheticOrigin;
63731                     if (origin && getExplicitTypeOfSymbol(origin)) {
63732                         return getTypeOfSymbol(symbol);
63733                     }
63734                 }
63735                 var declaration = symbol.valueDeclaration;
63736                 if (declaration) {
63737                     if (isDeclarationWithExplicitTypeAnnotation(declaration)) {
63738                         return getTypeOfSymbol(symbol);
63739                     }
63740                     if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) {
63741                         var statement = declaration.parent.parent;
63742                         var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined);
63743                         if (expressionType) {
63744                             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
63745                             return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined);
63746                         }
63747                     }
63748                     if (diagnostic) {
63749                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol)));
63750                     }
63751                 }
63752             }
63753         }
63754         // We require the dotted function name in an assertion expression to be comprised of identifiers
63755         // that reference function, method, class or value module symbols; or variable, property or
63756         // parameter symbols with declarations that have explicit type annotations. Such references are
63757         // resolvable with no possibility of triggering circularities in control flow analysis.
63758         function getTypeOfDottedName(node, diagnostic) {
63759             if (!(node.flags & 16777216 /* InWithStatement */)) {
63760                 switch (node.kind) {
63761                     case 78 /* Identifier */:
63762                         var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node));
63763                         return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol, diagnostic);
63764                     case 107 /* ThisKeyword */:
63765                         return getExplicitThisType(node);
63766                     case 105 /* SuperKeyword */:
63767                         return checkSuperExpression(node);
63768                     case 201 /* PropertyAccessExpression */: {
63769                         var type = getTypeOfDottedName(node.expression, diagnostic);
63770                         if (type) {
63771                             var name = node.name;
63772                             var prop = void 0;
63773                             if (ts.isPrivateIdentifier(name)) {
63774                                 if (!type.symbol) {
63775                                     return undefined;
63776                                 }
63777                                 prop = getPropertyOfType(type, ts.getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText));
63778                             }
63779                             else {
63780                                 prop = getPropertyOfType(type, name.escapedText);
63781                             }
63782                             return prop && getExplicitTypeOfSymbol(prop, diagnostic);
63783                         }
63784                         return undefined;
63785                     }
63786                     case 207 /* ParenthesizedExpression */:
63787                         return getTypeOfDottedName(node.expression, diagnostic);
63788                 }
63789             }
63790         }
63791         function getEffectsSignature(node) {
63792             var links = getNodeLinks(node);
63793             var signature = links.effectsSignature;
63794             if (signature === undefined) {
63795                 // A call expression parented by an expression statement is a potential assertion. Other call
63796                 // expressions are potential type predicate function calls. In order to avoid triggering
63797                 // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call
63798                 // target expression of an assertion.
63799                 var funcType = void 0;
63800                 if (node.parent.kind === 233 /* ExpressionStatement */) {
63801                     funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined);
63802                 }
63803                 else if (node.expression.kind !== 105 /* SuperKeyword */) {
63804                     if (ts.isOptionalChain(node)) {
63805                         funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression);
63806                     }
63807                     else {
63808                         funcType = checkNonNullExpression(node.expression);
63809                     }
63810                 }
63811                 var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */);
63812                 var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] :
63813                     ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) :
63814                         undefined;
63815                 signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature;
63816             }
63817             return signature === unknownSignature ? undefined : signature;
63818         }
63819         function hasTypePredicateOrNeverReturnType(signature) {
63820             return !!(getTypePredicateOfSignature(signature) ||
63821                 signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */);
63822         }
63823         function getTypePredicateArgument(predicate, callExpression) {
63824             if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) {
63825                 return callExpression.arguments[predicate.parameterIndex];
63826             }
63827             var invokedExpression = ts.skipParentheses(callExpression.expression);
63828             return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined;
63829         }
63830         function reportFlowControlError(node) {
63831             var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock);
63832             var sourceFile = ts.getSourceFileOfNode(node);
63833             var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
63834             diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
63835         }
63836         function isReachableFlowNode(flow) {
63837             var result = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ false);
63838             lastFlowNode = flow;
63839             lastFlowNodeReachable = result;
63840             return result;
63841         }
63842         function isFalseExpression(expr) {
63843             var node = ts.skipParentheses(expr);
63844             return node.kind === 94 /* FalseKeyword */ || node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) ||
63845                 node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right));
63846         }
63847         function isReachableFlowNodeWorker(flow, noCacheCheck) {
63848             while (true) {
63849                 if (flow === lastFlowNode) {
63850                     return lastFlowNodeReachable;
63851                 }
63852                 var flags = flow.flags;
63853                 if (flags & 4096 /* Shared */) {
63854                     if (!noCacheCheck) {
63855                         var id = getFlowNodeId(flow);
63856                         var reachable = flowNodeReachable[id];
63857                         return reachable !== undefined ? reachable : (flowNodeReachable[id] = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ true));
63858                     }
63859                     noCacheCheck = false;
63860                 }
63861                 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */)) {
63862                     flow = flow.antecedent;
63863                 }
63864                 else if (flags & 512 /* Call */) {
63865                     var signature = getEffectsSignature(flow.node);
63866                     if (signature) {
63867                         var predicate = getTypePredicateOfSignature(signature);
63868                         if (predicate && predicate.kind === 3 /* AssertsIdentifier */ && !predicate.type) {
63869                             var predicateArgument = flow.node.arguments[predicate.parameterIndex];
63870                             if (predicateArgument && isFalseExpression(predicateArgument)) {
63871                                 return false;
63872                             }
63873                         }
63874                         if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
63875                             return false;
63876                         }
63877                     }
63878                     flow = flow.antecedent;
63879                 }
63880                 else if (flags & 4 /* BranchLabel */) {
63881                     // A branching point is reachable if any branch is reachable.
63882                     return ts.some(flow.antecedents, function (f) { return isReachableFlowNodeWorker(f, /*noCacheCheck*/ false); });
63883                 }
63884                 else if (flags & 8 /* LoopLabel */) {
63885                     var antecedents = flow.antecedents;
63886                     if (antecedents === undefined || antecedents.length === 0) {
63887                         return false;
63888                     }
63889                     // A loop is reachable if the control flow path that leads to the top is reachable.
63890                     flow = antecedents[0];
63891                 }
63892                 else if (flags & 128 /* SwitchClause */) {
63893                     // The control flow path representing an unmatched value in a switch statement with
63894                     // no default clause is unreachable if the switch statement is exhaustive.
63895                     if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) {
63896                         return false;
63897                     }
63898                     flow = flow.antecedent;
63899                 }
63900                 else if (flags & 1024 /* ReduceLabel */) {
63901                     // Cache is unreliable once we start adjusting labels
63902                     lastFlowNode = undefined;
63903                     var target = flow.target;
63904                     var saveAntecedents = target.antecedents;
63905                     target.antecedents = flow.antecedents;
63906                     var result = isReachableFlowNodeWorker(flow.antecedent, /*noCacheCheck*/ false);
63907                     target.antecedents = saveAntecedents;
63908                     return result;
63909                 }
63910                 else {
63911                     return !(flags & 1 /* Unreachable */);
63912                 }
63913             }
63914         }
63915         // Return true if the given flow node is preceded by a 'super(...)' call in every possible code path
63916         // leading to the node.
63917         function isPostSuperFlowNode(flow, noCacheCheck) {
63918             while (true) {
63919                 var flags = flow.flags;
63920                 if (flags & 4096 /* Shared */) {
63921                     if (!noCacheCheck) {
63922                         var id = getFlowNodeId(flow);
63923                         var postSuper = flowNodePostSuper[id];
63924                         return postSuper !== undefined ? postSuper : (flowNodePostSuper[id] = isPostSuperFlowNode(flow, /*noCacheCheck*/ true));
63925                     }
63926                     noCacheCheck = false;
63927                 }
63928                 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */ | 128 /* SwitchClause */)) {
63929                     flow = flow.antecedent;
63930                 }
63931                 else if (flags & 512 /* Call */) {
63932                     if (flow.node.expression.kind === 105 /* SuperKeyword */) {
63933                         return true;
63934                     }
63935                     flow = flow.antecedent;
63936                 }
63937                 else if (flags & 4 /* BranchLabel */) {
63938                     // A branching point is post-super if every branch is post-super.
63939                     return ts.every(flow.antecedents, function (f) { return isPostSuperFlowNode(f, /*noCacheCheck*/ false); });
63940                 }
63941                 else if (flags & 8 /* LoopLabel */) {
63942                     // A loop is post-super if the control flow path that leads to the top is post-super.
63943                     flow = flow.antecedents[0];
63944                 }
63945                 else if (flags & 1024 /* ReduceLabel */) {
63946                     var target = flow.target;
63947                     var saveAntecedents = target.antecedents;
63948                     target.antecedents = flow.antecedents;
63949                     var result = isPostSuperFlowNode(flow.antecedent, /*noCacheCheck*/ false);
63950                     target.antecedents = saveAntecedents;
63951                     return result;
63952                 }
63953                 else {
63954                     // Unreachable nodes are considered post-super to silence errors
63955                     return !!(flags & 1 /* Unreachable */);
63956                 }
63957             }
63958         }
63959         function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) {
63960             if (initialType === void 0) { initialType = declaredType; }
63961             var key;
63962             var isKeySet = false;
63963             var flowDepth = 0;
63964             if (flowAnalysisDisabled) {
63965                 return errorType;
63966             }
63967             if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 536624127 /* Narrowable */)) {
63968                 return declaredType;
63969             }
63970             flowInvocationCount++;
63971             var sharedFlowStart = sharedFlowCount;
63972             var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
63973             sharedFlowCount = sharedFlowStart;
63974             // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation,
63975             // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations
63976             // on empty arrays are possible without implicit any errors and new element types can be inferred without
63977             // type mismatch errors.
63978             var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
63979             if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 225 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) {
63980                 return declaredType;
63981             }
63982             return resultType;
63983             function getOrSetCacheKey() {
63984                 if (isKeySet) {
63985                     return key;
63986                 }
63987                 isKeySet = true;
63988                 return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer);
63989             }
63990             function getTypeAtFlowNode(flow) {
63991                 if (flowDepth === 2000) {
63992                     // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
63993                     // and disable further control flow analysis in the containing function or module body.
63994                     ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.instant("checkTypes" /* CheckTypes */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id });
63995                     flowAnalysisDisabled = true;
63996                     reportFlowControlError(reference);
63997                     return errorType;
63998                 }
63999                 flowDepth++;
64000                 var sharedFlow;
64001                 while (true) {
64002                     var flags = flow.flags;
64003                     if (flags & 4096 /* Shared */) {
64004                         // We cache results of flow type resolution for shared nodes that were previously visited in
64005                         // the same getFlowTypeOfReference invocation. A node is considered shared when it is the
64006                         // antecedent of more than one node.
64007                         for (var i = sharedFlowStart; i < sharedFlowCount; i++) {
64008                             if (sharedFlowNodes[i] === flow) {
64009                                 flowDepth--;
64010                                 return sharedFlowTypes[i];
64011                             }
64012                         }
64013                         sharedFlow = flow;
64014                     }
64015                     var type = void 0;
64016                     if (flags & 16 /* Assignment */) {
64017                         type = getTypeAtFlowAssignment(flow);
64018                         if (!type) {
64019                             flow = flow.antecedent;
64020                             continue;
64021                         }
64022                     }
64023                     else if (flags & 512 /* Call */) {
64024                         type = getTypeAtFlowCall(flow);
64025                         if (!type) {
64026                             flow = flow.antecedent;
64027                             continue;
64028                         }
64029                     }
64030                     else if (flags & 96 /* Condition */) {
64031                         type = getTypeAtFlowCondition(flow);
64032                     }
64033                     else if (flags & 128 /* SwitchClause */) {
64034                         type = getTypeAtSwitchClause(flow);
64035                     }
64036                     else if (flags & 12 /* Label */) {
64037                         if (flow.antecedents.length === 1) {
64038                             flow = flow.antecedents[0];
64039                             continue;
64040                         }
64041                         type = flags & 4 /* BranchLabel */ ?
64042                             getTypeAtFlowBranchLabel(flow) :
64043                             getTypeAtFlowLoopLabel(flow);
64044                     }
64045                     else if (flags & 256 /* ArrayMutation */) {
64046                         type = getTypeAtFlowArrayMutation(flow);
64047                         if (!type) {
64048                             flow = flow.antecedent;
64049                             continue;
64050                         }
64051                     }
64052                     else if (flags & 1024 /* ReduceLabel */) {
64053                         var target = flow.target;
64054                         var saveAntecedents = target.antecedents;
64055                         target.antecedents = flow.antecedents;
64056                         type = getTypeAtFlowNode(flow.antecedent);
64057                         target.antecedents = saveAntecedents;
64058                     }
64059                     else if (flags & 2 /* Start */) {
64060                         // Check if we should continue with the control flow of the containing function.
64061                         var container = flow.node;
64062                         if (container && container !== flowContainer &&
64063                             reference.kind !== 201 /* PropertyAccessExpression */ &&
64064                             reference.kind !== 202 /* ElementAccessExpression */ &&
64065                             reference.kind !== 107 /* ThisKeyword */) {
64066                             flow = container.flowNode;
64067                             continue;
64068                         }
64069                         // At the top of the flow we have the initial type.
64070                         type = initialType;
64071                     }
64072                     else {
64073                         // Unreachable code errors are reported in the binding phase. Here we
64074                         // simply return the non-auto declared type to reduce follow-on errors.
64075                         type = convertAutoToAny(declaredType);
64076                     }
64077                     if (sharedFlow) {
64078                         // Record visited node and the associated type in the cache.
64079                         sharedFlowNodes[sharedFlowCount] = sharedFlow;
64080                         sharedFlowTypes[sharedFlowCount] = type;
64081                         sharedFlowCount++;
64082                     }
64083                     flowDepth--;
64084                     return type;
64085                 }
64086             }
64087             function getInitialOrAssignedType(flow) {
64088                 var node = flow.node;
64089                 return getConstraintForLocation(node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */ ?
64090                     getInitialType(node) :
64091                     getAssignedType(node), reference);
64092             }
64093             function getTypeAtFlowAssignment(flow) {
64094                 var node = flow.node;
64095                 // Assignments only narrow the computed type if the declared type is a union type. Thus, we
64096                 // only need to evaluate the assigned type if the declared type is a union type.
64097                 if (isMatchingReference(reference, node)) {
64098                     if (!isReachableFlowNode(flow)) {
64099                         return unreachableNeverType;
64100                     }
64101                     if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) {
64102                         var flowType = getTypeAtFlowNode(flow.antecedent);
64103                         return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
64104                     }
64105                     if (declaredType === autoType || declaredType === autoArrayType) {
64106                         if (isEmptyArrayAssignment(node)) {
64107                             return getEvolvingArrayType(neverType);
64108                         }
64109                         var assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow));
64110                         return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
64111                     }
64112                     if (declaredType.flags & 1048576 /* Union */) {
64113                         return getAssignmentReducedType(declaredType, getInitialOrAssignedType(flow));
64114                     }
64115                     return declaredType;
64116                 }
64117                 // We didn't have a direct match. However, if the reference is a dotted name, this
64118                 // may be an assignment to a left hand part of the reference. For example, for a
64119                 // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case,
64120                 // return the declared type.
64121                 if (containsMatchingReference(reference, node)) {
64122                     if (!isReachableFlowNode(flow)) {
64123                         return unreachableNeverType;
64124                     }
64125                     // A matching dotted name might also be an expando property on a function *expression*,
64126                     // in which case we continue control flow analysis back to the function's declaration
64127                     if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) {
64128                         var init = ts.getDeclaredExpandoInitializer(node);
64129                         if (init && (init.kind === 208 /* FunctionExpression */ || init.kind === 209 /* ArrowFunction */)) {
64130                             return getTypeAtFlowNode(flow.antecedent);
64131                         }
64132                     }
64133                     return declaredType;
64134                 }
64135                 // for (const _ in ref) acts as a nonnull on ref
64136                 if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 238 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) {
64137                     return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)));
64138                 }
64139                 // Assignment doesn't affect reference
64140                 return undefined;
64141             }
64142             function narrowTypeByAssertion(type, expr) {
64143                 var node = ts.skipParentheses(expr);
64144                 if (node.kind === 94 /* FalseKeyword */) {
64145                     return unreachableNeverType;
64146                 }
64147                 if (node.kind === 216 /* BinaryExpression */) {
64148                     if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
64149                         return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right);
64150                     }
64151                     if (node.operatorToken.kind === 56 /* BarBarToken */) {
64152                         return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]);
64153                     }
64154                 }
64155                 return narrowType(type, node, /*assumeTrue*/ true);
64156             }
64157             function getTypeAtFlowCall(flow) {
64158                 var signature = getEffectsSignature(flow.node);
64159                 if (signature) {
64160                     var predicate = getTypePredicateOfSignature(signature);
64161                     if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) {
64162                         var flowType = getTypeAtFlowNode(flow.antecedent);
64163                         var type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType));
64164                         var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) :
64165                             predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) :
64166                                 type;
64167                         return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType));
64168                     }
64169                     if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
64170                         return unreachableNeverType;
64171                     }
64172                 }
64173                 return undefined;
64174             }
64175             function getTypeAtFlowArrayMutation(flow) {
64176                 if (declaredType === autoType || declaredType === autoArrayType) {
64177                     var node = flow.node;
64178                     var expr = node.kind === 203 /* CallExpression */ ?
64179                         node.expression.expression :
64180                         node.left.expression;
64181                     if (isMatchingReference(reference, getReferenceCandidate(expr))) {
64182                         var flowType = getTypeAtFlowNode(flow.antecedent);
64183                         var type = getTypeFromFlowType(flowType);
64184                         if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) {
64185                             var evolvedType_1 = type;
64186                             if (node.kind === 203 /* CallExpression */) {
64187                                 for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
64188                                     var arg = _a[_i];
64189                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg);
64190                                 }
64191                             }
64192                             else {
64193                                 // 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)
64194                                 var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
64195                                 if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
64196                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right);
64197                                 }
64198                             }
64199                             return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType));
64200                         }
64201                         return flowType;
64202                     }
64203                 }
64204                 return undefined;
64205             }
64206             function getTypeAtFlowCondition(flow) {
64207                 var flowType = getTypeAtFlowNode(flow.antecedent);
64208                 var type = getTypeFromFlowType(flowType);
64209                 if (type.flags & 131072 /* Never */) {
64210                     return flowType;
64211                 }
64212                 // If we have an antecedent type (meaning we're reachable in some way), we first
64213                 // attempt to narrow the antecedent type. If that produces the never type, and if
64214                 // the antecedent type is incomplete (i.e. a transient type in a loop), then we
64215                 // take the type guard as an indication that control *could* reach here once we
64216                 // have the complete type. We proceed by switching to the silent never type which
64217                 // doesn't report errors when operators are applied to it. Note that this is the
64218                 // *only* place a silent never type is ever generated.
64219                 var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0;
64220                 var nonEvolvingType = finalizeEvolvingArrayType(type);
64221                 var narrowedType = narrowType(nonEvolvingType, flow.node, assumeTrue);
64222                 if (narrowedType === nonEvolvingType) {
64223                     return flowType;
64224                 }
64225                 return createFlowType(narrowedType, isIncomplete(flowType));
64226             }
64227             function getTypeAtSwitchClause(flow) {
64228                 var expr = flow.switchStatement.expression;
64229                 var flowType = getTypeAtFlowNode(flow.antecedent);
64230                 var type = getTypeFromFlowType(flowType);
64231                 if (isMatchingReference(reference, expr)) {
64232                     type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
64233                 }
64234                 else if (expr.kind === 211 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
64235                     type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
64236                 }
64237                 else {
64238                     if (strictNullChecks) {
64239                         if (optionalChainContainsReference(expr, reference)) {
64240                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); });
64241                         }
64242                         else if (expr.kind === 211 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) {
64243                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); });
64244                         }
64245                     }
64246                     if (isMatchingReferenceDiscriminant(expr, type)) {
64247                         type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); });
64248                     }
64249                 }
64250                 return createFlowType(type, isIncomplete(flowType));
64251             }
64252             function getTypeAtFlowBranchLabel(flow) {
64253                 var antecedentTypes = [];
64254                 var subtypeReduction = false;
64255                 var seenIncomplete = false;
64256                 var bypassFlow;
64257                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
64258                     var antecedent = _a[_i];
64259                     if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) {
64260                         // The antecedent is the bypass branch of a potentially exhaustive switch statement.
64261                         bypassFlow = antecedent;
64262                         continue;
64263                     }
64264                     var flowType = getTypeAtFlowNode(antecedent);
64265                     var type = getTypeFromFlowType(flowType);
64266                     // If the type at a particular antecedent path is the declared type and the
64267                     // reference is known to always be assigned (i.e. when declared and initial types
64268                     // are the same), there is no reason to process more antecedents since the only
64269                     // possible outcome is subtypes that will be removed in the final union type anyway.
64270                     if (type === declaredType && declaredType === initialType) {
64271                         return type;
64272                     }
64273                     ts.pushIfUnique(antecedentTypes, type);
64274                     // If an antecedent type is not a subset of the declared type, we need to perform
64275                     // subtype reduction. This happens when a "foreign" type is injected into the control
64276                     // flow using the instanceof operator or a user defined type predicate.
64277                     if (!isTypeSubsetOf(type, declaredType)) {
64278                         subtypeReduction = true;
64279                     }
64280                     if (isIncomplete(flowType)) {
64281                         seenIncomplete = true;
64282                     }
64283                 }
64284                 if (bypassFlow) {
64285                     var flowType = getTypeAtFlowNode(bypassFlow);
64286                     var type = getTypeFromFlowType(flowType);
64287                     // If the bypass flow contributes a type we haven't seen yet and the switch statement
64288                     // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase
64289                     // the risk of circularities, we only want to perform them when they make a difference.
64290                     if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) {
64291                         if (type === declaredType && declaredType === initialType) {
64292                             return type;
64293                         }
64294                         antecedentTypes.push(type);
64295                         if (!isTypeSubsetOf(type, declaredType)) {
64296                             subtypeReduction = true;
64297                         }
64298                         if (isIncomplete(flowType)) {
64299                             seenIncomplete = true;
64300                         }
64301                     }
64302                 }
64303                 return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete);
64304             }
64305             function getTypeAtFlowLoopLabel(flow) {
64306                 // If we have previously computed the control flow type for the reference at
64307                 // this flow loop junction, return the cached type.
64308                 var id = getFlowNodeId(flow);
64309                 var cache = flowLoopCaches[id] || (flowLoopCaches[id] = new ts.Map());
64310                 var key = getOrSetCacheKey();
64311                 if (!key) {
64312                     // No cache key is generated when binding patterns are in unnarrowable situations
64313                     return declaredType;
64314                 }
64315                 var cached = cache.get(key);
64316                 if (cached) {
64317                     return cached;
64318                 }
64319                 // If this flow loop junction and reference are already being processed, return
64320                 // the union of the types computed for each branch so far, marked as incomplete.
64321                 // It is possible to see an empty array in cases where loops are nested and the
64322                 // back edge of the outer loop reaches an inner loop that is already being analyzed.
64323                 // In such cases we restart the analysis of the inner loop, which will then see
64324                 // a non-empty in-process array for the outer loop and eventually terminate because
64325                 // the first antecedent of a loop junction is always the non-looping control flow
64326                 // path that leads to the top.
64327                 for (var i = flowLoopStart; i < flowLoopCount; i++) {
64328                     if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) {
64329                         return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true);
64330                     }
64331                 }
64332                 // Add the flow loop junction and reference to the in-process stack and analyze
64333                 // each antecedent code path.
64334                 var antecedentTypes = [];
64335                 var subtypeReduction = false;
64336                 var firstAntecedentType;
64337                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
64338                     var antecedent = _a[_i];
64339                     var flowType = void 0;
64340                     if (!firstAntecedentType) {
64341                         // The first antecedent of a loop junction is always the non-looping control
64342                         // flow path that leads to the top.
64343                         flowType = firstAntecedentType = getTypeAtFlowNode(antecedent);
64344                     }
64345                     else {
64346                         // All but the first antecedent are the looping control flow paths that lead
64347                         // back to the loop junction. We track these on the flow loop stack.
64348                         flowLoopNodes[flowLoopCount] = flow;
64349                         flowLoopKeys[flowLoopCount] = key;
64350                         flowLoopTypes[flowLoopCount] = antecedentTypes;
64351                         flowLoopCount++;
64352                         var saveFlowTypeCache = flowTypeCache;
64353                         flowTypeCache = undefined;
64354                         flowType = getTypeAtFlowNode(antecedent);
64355                         flowTypeCache = saveFlowTypeCache;
64356                         flowLoopCount--;
64357                         // If we see a value appear in the cache it is a sign that control flow analysis
64358                         // was restarted and completed by checkExpressionCached. We can simply pick up
64359                         // the resulting type and bail out.
64360                         var cached_1 = cache.get(key);
64361                         if (cached_1) {
64362                             return cached_1;
64363                         }
64364                     }
64365                     var type = getTypeFromFlowType(flowType);
64366                     ts.pushIfUnique(antecedentTypes, type);
64367                     // If an antecedent type is not a subset of the declared type, we need to perform
64368                     // subtype reduction. This happens when a "foreign" type is injected into the control
64369                     // flow using the instanceof operator or a user defined type predicate.
64370                     if (!isTypeSubsetOf(type, declaredType)) {
64371                         subtypeReduction = true;
64372                     }
64373                     // If the type at a particular antecedent path is the declared type there is no
64374                     // reason to process more antecedents since the only possible outcome is subtypes
64375                     // that will be removed in the final union type anyway.
64376                     if (type === declaredType) {
64377                         break;
64378                     }
64379                 }
64380                 // The result is incomplete if the first antecedent (the non-looping control flow path)
64381                 // is incomplete.
64382                 var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */);
64383                 if (isIncomplete(firstAntecedentType)) {
64384                     return createFlowType(result, /*incomplete*/ true);
64385                 }
64386                 cache.set(key, result);
64387                 return result;
64388             }
64389             // At flow control branch or loop junctions, if the type along every antecedent code path
64390             // is an evolving array type, we construct a combined evolving array type. Otherwise we
64391             // finalize all evolving array types.
64392             function getUnionOrEvolvingArrayType(types, subtypeReduction) {
64393                 if (isEvolvingArrayTypeList(types)) {
64394                     return getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType)));
64395                 }
64396                 var result = getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
64397                 if (result !== declaredType && result.flags & declaredType.flags & 1048576 /* Union */ && ts.arraysEqual(result.types, declaredType.types)) {
64398                     return declaredType;
64399                 }
64400                 return result;
64401             }
64402             function isMatchingReferenceDiscriminant(expr, computedType) {
64403                 var type = declaredType.flags & 1048576 /* Union */ ? declaredType : computedType;
64404                 if (!(type.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) {
64405                     return false;
64406                 }
64407                 var name = getAccessedPropertyName(expr);
64408                 if (name === undefined) {
64409                     return false;
64410                 }
64411                 return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(type, name);
64412             }
64413             function narrowTypeByDiscriminant(type, access, narrowType) {
64414                 var propName = getAccessedPropertyName(access);
64415                 if (propName === undefined) {
64416                     return type;
64417                 }
64418                 var includesNullable = strictNullChecks && maybeTypeOfKind(type, 98304 /* Nullable */);
64419                 var removeNullable = includesNullable && ts.isOptionalChain(access);
64420                 var propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName);
64421                 if (!propType) {
64422                     return type;
64423                 }
64424                 propType = removeNullable ? getOptionalType(propType) : propType;
64425                 var narrowedPropType = narrowType(propType);
64426                 return filterType(type, function (t) {
64427                     var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName);
64428                     return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType);
64429                 });
64430             }
64431             function narrowTypeByTruthiness(type, expr, assumeTrue) {
64432                 if (isMatchingReference(reference, expr)) {
64433                     return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */);
64434                 }
64435                 if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) {
64436                     type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
64437                 }
64438                 if (isMatchingReferenceDiscriminant(expr, type)) {
64439                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); });
64440                 }
64441                 return type;
64442             }
64443             function isTypePresencePossible(type, propName, assumeTrue) {
64444                 if (getIndexInfoOfType(type, 0 /* String */)) {
64445                     return true;
64446                 }
64447                 var prop = getPropertyOfType(type, propName);
64448                 if (prop) {
64449                     return prop.flags & 16777216 /* Optional */ ? true : assumeTrue;
64450                 }
64451                 return !assumeTrue;
64452             }
64453             function narrowByInKeyword(type, literal, assumeTrue) {
64454                 if (type.flags & (1048576 /* Union */ | 524288 /* Object */)
64455                     || isThisTypeParameter(type)
64456                     || type.flags & 2097152 /* Intersection */ && ts.every(type.types, function (t) { return t.symbol !== globalThisSymbol; })) {
64457                     var propName_1 = ts.escapeLeadingUnderscores(literal.text);
64458                     return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); });
64459                 }
64460                 return type;
64461             }
64462             function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
64463                 switch (expr.operatorToken.kind) {
64464                     case 62 /* EqualsToken */:
64465                     case 74 /* BarBarEqualsToken */:
64466                     case 75 /* AmpersandAmpersandEqualsToken */:
64467                     case 76 /* QuestionQuestionEqualsToken */:
64468                         return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue);
64469                     case 34 /* EqualsEqualsToken */:
64470                     case 35 /* ExclamationEqualsToken */:
64471                     case 36 /* EqualsEqualsEqualsToken */:
64472                     case 37 /* ExclamationEqualsEqualsToken */:
64473                         var operator_1 = expr.operatorToken.kind;
64474                         var left_1 = getReferenceCandidate(expr.left);
64475                         var right_1 = getReferenceCandidate(expr.right);
64476                         if (left_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) {
64477                             return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue);
64478                         }
64479                         if (right_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) {
64480                             return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue);
64481                         }
64482                         if (isMatchingReference(reference, left_1)) {
64483                             return narrowTypeByEquality(type, operator_1, right_1, assumeTrue);
64484                         }
64485                         if (isMatchingReference(reference, right_1)) {
64486                             return narrowTypeByEquality(type, operator_1, left_1, assumeTrue);
64487                         }
64488                         if (strictNullChecks) {
64489                             if (optionalChainContainsReference(left_1, reference)) {
64490                                 type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue);
64491                             }
64492                             else if (optionalChainContainsReference(right_1, reference)) {
64493                                 type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue);
64494                             }
64495                         }
64496                         if (isMatchingReferenceDiscriminant(left_1, type)) {
64497                             return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); });
64498                         }
64499                         if (isMatchingReferenceDiscriminant(right_1, type)) {
64500                             return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); });
64501                         }
64502                         if (isMatchingConstructorReference(left_1)) {
64503                             return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue);
64504                         }
64505                         if (isMatchingConstructorReference(right_1)) {
64506                             return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue);
64507                         }
64508                         break;
64509                     case 101 /* InstanceOfKeyword */:
64510                         return narrowTypeByInstanceof(type, expr, assumeTrue);
64511                     case 100 /* InKeyword */:
64512                         var target = getReferenceCandidate(expr.right);
64513                         if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) {
64514                             return narrowByInKeyword(type, expr.left, assumeTrue);
64515                         }
64516                         break;
64517                     case 27 /* CommaToken */:
64518                         return narrowType(type, expr.right, assumeTrue);
64519                 }
64520                 return type;
64521             }
64522             function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) {
64523                 // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows:
64524                 // When operator is === and type of value excludes undefined, null and undefined is removed from type of obj in true branch.
64525                 // When operator is !== and type of value excludes undefined, null and undefined is removed from type of obj in false branch.
64526                 // When operator is == and type of value excludes null and undefined, null and undefined is removed from type of obj in true branch.
64527                 // When operator is != and type of value excludes null and undefined, null and undefined is removed from type of obj in false branch.
64528                 // When operator is === and type of value is undefined, null and undefined is removed from type of obj in false branch.
64529                 // When operator is !== and type of value is undefined, null and undefined is removed from type of obj in true branch.
64530                 // When operator is == and type of value is null or undefined, null and undefined is removed from type of obj in false branch.
64531                 // When operator is != and type of value is null or undefined, null and undefined is removed from type of obj in true branch.
64532                 var equalsOperator = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */;
64533                 var nullableFlags = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */;
64534                 var valueType = getTypeOfExpression(value);
64535                 // Note that we include any and unknown in the exclusion test because their domain includes null and undefined.
64536                 var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) ||
64537                     equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags)); });
64538                 return removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
64539             }
64540             function narrowTypeByEquality(type, operator, value, assumeTrue) {
64541                 if (type.flags & 1 /* Any */) {
64542                     return type;
64543                 }
64544                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
64545                     assumeTrue = !assumeTrue;
64546                 }
64547                 var valueType = getTypeOfExpression(value);
64548                 if ((type.flags & 2 /* Unknown */) && assumeTrue && (operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */)) {
64549                     if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
64550                         return valueType;
64551                     }
64552                     if (valueType.flags & 524288 /* Object */) {
64553                         return nonPrimitiveType;
64554                     }
64555                     return type;
64556                 }
64557                 if (valueType.flags & 98304 /* Nullable */) {
64558                     if (!strictNullChecks) {
64559                         return type;
64560                     }
64561                     var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */;
64562                     var facts = doubleEquals ?
64563                         assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ :
64564                         valueType.flags & 65536 /* Null */ ?
64565                             assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ :
64566                             assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
64567                     return getTypeWithFacts(type, facts);
64568                 }
64569                 if (assumeTrue) {
64570                     var filterFn = operator === 34 /* EqualsEqualsToken */ ?
64571                         (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) :
64572                         function (t) { return areTypesComparable(t, valueType); };
64573                     return replacePrimitivesWithLiterals(filterType(type, filterFn), valueType);
64574                 }
64575                 if (isUnitType(valueType)) {
64576                     var regularType_1 = getRegularTypeOfLiteralType(valueType);
64577                     return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; });
64578                 }
64579                 return type;
64580             }
64581             function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
64582                 // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands
64583                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
64584                     assumeTrue = !assumeTrue;
64585                 }
64586                 var target = getReferenceCandidate(typeOfExpr.expression);
64587                 if (!isMatchingReference(reference, target)) {
64588                     if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) {
64589                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
64590                     }
64591                     return type;
64592                 }
64593                 if (type.flags & 1 /* Any */ && literal.text === "function") {
64594                     return type;
64595                 }
64596                 if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") {
64597                     // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't
64598                     // need to check for the reverse typeof x === 'object' && x since that already narrows correctly.
64599                     if (typeOfExpr.parent.parent.kind === 216 /* BinaryExpression */) {
64600                         var expr = typeOfExpr.parent.parent;
64601                         if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) {
64602                             return nonPrimitiveType;
64603                         }
64604                     }
64605                     return getUnionType([nonPrimitiveType, nullType]);
64606                 }
64607                 var facts = assumeTrue ?
64608                     typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ :
64609                     typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */;
64610                 var impliedType = getImpliedTypeFromTypeofGuard(type, literal.text);
64611                 return getTypeWithFacts(assumeTrue && impliedType ? mapType(type, narrowUnionMemberByTypeof(impliedType)) : type, facts);
64612             }
64613             function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) {
64614                 var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck);
64615                 return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
64616             }
64617             function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
64618                 // We only narrow if all case expressions specify
64619                 // values with unit types, except for the case where
64620                 // `type` is unknown. In this instance we map object
64621                 // types to the nonPrimitive type and narrow with that.
64622                 var switchTypes = getSwitchClauseTypes(switchStatement);
64623                 if (!switchTypes.length) {
64624                     return type;
64625                 }
64626                 var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
64627                 var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
64628                 if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
64629                     var groundClauseTypes = void 0;
64630                     for (var i = 0; i < clauseTypes.length; i += 1) {
64631                         var t = clauseTypes[i];
64632                         if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
64633                             if (groundClauseTypes !== undefined) {
64634                                 groundClauseTypes.push(t);
64635                             }
64636                         }
64637                         else if (t.flags & 524288 /* Object */) {
64638                             if (groundClauseTypes === undefined) {
64639                                 groundClauseTypes = clauseTypes.slice(0, i);
64640                             }
64641                             groundClauseTypes.push(nonPrimitiveType);
64642                         }
64643                         else {
64644                             return type;
64645                         }
64646                     }
64647                     return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
64648                 }
64649                 var discriminantType = getUnionType(clauseTypes);
64650                 var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
64651                     replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
64652                 if (!hasDefaultClause) {
64653                     return caseType;
64654                 }
64655                 var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); });
64656                 return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
64657             }
64658             function getImpliedTypeFromTypeofGuard(type, text) {
64659                 switch (text) {
64660                     case "function":
64661                         return type.flags & 1 /* Any */ ? type : globalFunctionType;
64662                     case "object":
64663                         return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type;
64664                     default:
64665                         return typeofTypesByName.get(text);
64666                 }
64667             }
64668             // When narrowing a union type by a `typeof` guard using type-facts alone, constituent types that are
64669             // super-types of the implied guard will be retained in the final type: this is because type-facts only
64670             // filter. Instead, we would like to replace those union constituents with the more precise type implied by
64671             // the guard. For example: narrowing `{} | undefined` by `"boolean"` should produce the type `boolean`, not
64672             // the filtered type `{}`. For this reason we narrow constituents of the union individually, in addition to
64673             // filtering by type-facts.
64674             function narrowUnionMemberByTypeof(candidate) {
64675                 return function (type) {
64676                     if (isTypeSubtypeOf(type, candidate)) {
64677                         return type;
64678                     }
64679                     if (isTypeSubtypeOf(candidate, type)) {
64680                         return candidate;
64681                     }
64682                     if (type.flags & 465829888 /* Instantiable */) {
64683                         var constraint = getBaseConstraintOfType(type) || anyType;
64684                         if (isTypeSubtypeOf(candidate, constraint)) {
64685                             return getIntersectionType([type, candidate]);
64686                         }
64687                     }
64688                     return type;
64689                 };
64690             }
64691             function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) {
64692                 var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true);
64693                 if (!switchWitnesses.length) {
64694                     return type;
64695                 }
64696                 //  Equal start and end denotes implicit fallthrough; undefined marks explicit default clause
64697                 var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; });
64698                 var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd);
64699                 var clauseWitnesses;
64700                 var switchFacts;
64701                 if (defaultCaseLocation > -1) {
64702                     // We no longer need the undefined denoting an explicit default case. Remove the undefined and
64703                     // fix-up clauseStart and clauseEnd.  This means that we don't have to worry about undefined in the
64704                     // witness array.
64705                     var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; });
64706                     // The adjusted clause start and end after removing the `default` statement.
64707                     var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart;
64708                     var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd;
64709                     clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd);
64710                     switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause);
64711                 }
64712                 else {
64713                     clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd);
64714                     switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause);
64715                 }
64716                 if (hasDefaultClause) {
64717                     return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; });
64718                 }
64719                 /*
64720                   The implied type is the raw type suggested by a
64721                   value being caught in this clause.
64722
64723                   When the clause contains a default case we ignore
64724                   the implied type and try to narrow using any facts
64725                   we can learn: see `switchFacts`.
64726
64727                   Example:
64728                   switch (typeof x) {
64729                       case 'number':
64730                       case 'string': break;
64731                       default: break;
64732                       case 'number':
64733                       case 'boolean': break
64734                   }
64735
64736                   In the first clause (case `number` and `string`) the
64737                   implied type is number | string.
64738
64739                   In the default clause we de not compute an implied type.
64740
64741                   In the third clause (case `number` and `boolean`)
64742                   the naive implied type is number | boolean, however
64743                   we use the type facts to narrow the implied type to
64744                   boolean. We know that number cannot be selected
64745                   because it is caught in the first clause.
64746                 */
64747                 var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofGuard(type, text) || type; })), switchFacts);
64748                 return getTypeWithFacts(mapType(type, narrowUnionMemberByTypeof(impliedType)), switchFacts);
64749             }
64750             function isMatchingConstructorReference(expr) {
64751                 return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" ||
64752                     ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") &&
64753                     isMatchingReference(reference, expr.expression);
64754             }
64755             function narrowTypeByConstructor(type, operator, identifier, assumeTrue) {
64756                 // Do not narrow when checking inequality.
64757                 if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) {
64758                     return type;
64759                 }
64760                 // Get the type of the constructor identifier expression, if it is not a function then do not narrow.
64761                 var identifierType = getTypeOfExpression(identifier);
64762                 if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) {
64763                     return type;
64764                 }
64765                 // Get the prototype property of the type identifier so we can find out its type.
64766                 var prototypeProperty = getPropertyOfType(identifierType, "prototype");
64767                 if (!prototypeProperty) {
64768                     return type;
64769                 }
64770                 // Get the type of the prototype, if it is undefined, or the global `Object` or `Function` types then do not narrow.
64771                 var prototypeType = getTypeOfSymbol(prototypeProperty);
64772                 var candidate = !isTypeAny(prototypeType) ? prototypeType : undefined;
64773                 if (!candidate || candidate === globalObjectType || candidate === globalFunctionType) {
64774                     return type;
64775                 }
64776                 // If the type that is being narrowed is `any` then just return the `candidate` type since every type is a subtype of `any`.
64777                 if (isTypeAny(type)) {
64778                     return candidate;
64779                 }
64780                 // Filter out types that are not considered to be "constructed by" the `candidate` type.
64781                 return filterType(type, function (t) { return isConstructedBy(t, candidate); });
64782                 function isConstructedBy(source, target) {
64783                     // If either the source or target type are a class type then we need to check that they are the same exact type.
64784                     // This is because you may have a class `A` that defines some set of properties, and another class `B`
64785                     // that defines the same set of properties as class `A`, in that case they are structurally the same
64786                     // type, but when you do something like `instanceOfA.constructor === B` it will return false.
64787                     if (source.flags & 524288 /* Object */ && ts.getObjectFlags(source) & 1 /* Class */ ||
64788                         target.flags & 524288 /* Object */ && ts.getObjectFlags(target) & 1 /* Class */) {
64789                         return source.symbol === target.symbol;
64790                     }
64791                     // For all other types just check that the `source` type is a subtype of the `target` type.
64792                     return isTypeSubtypeOf(source, target);
64793                 }
64794             }
64795             function narrowTypeByInstanceof(type, expr, assumeTrue) {
64796                 var left = getReferenceCandidate(expr.left);
64797                 if (!isMatchingReference(reference, left)) {
64798                     if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) {
64799                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
64800                     }
64801                     return type;
64802                 }
64803                 // Check that right operand is a function type with a prototype property
64804                 var rightType = getTypeOfExpression(expr.right);
64805                 if (!isTypeDerivedFrom(rightType, globalFunctionType)) {
64806                     return type;
64807                 }
64808                 var targetType;
64809                 var prototypeProperty = getPropertyOfType(rightType, "prototype");
64810                 if (prototypeProperty) {
64811                     // Target type is type of the prototype property
64812                     var prototypePropertyType = getTypeOfSymbol(prototypeProperty);
64813                     if (!isTypeAny(prototypePropertyType)) {
64814                         targetType = prototypePropertyType;
64815                     }
64816                 }
64817                 // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
64818                 if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
64819                     return type;
64820                 }
64821                 if (!targetType) {
64822                     var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */);
64823                     targetType = constructSignatures.length ?
64824                         getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) :
64825                         emptyObjectType;
64826                 }
64827                 // We can't narrow a union based off instanceof without negated types see #31576 for more info
64828                 if (!assumeTrue && rightType.flags & 1048576 /* Union */) {
64829                     var nonConstructorTypeInUnion = ts.find(rightType.types, function (t) { return !isConstructorType(t); });
64830                     if (!nonConstructorTypeInUnion)
64831                         return type;
64832                 }
64833                 return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
64834             }
64835             function getNarrowedType(type, candidate, assumeTrue, isRelated) {
64836                 if (!assumeTrue) {
64837                     return filterType(type, function (t) { return !isRelated(t, candidate); });
64838                 }
64839                 // If the current type is a union type, remove all constituents that couldn't be instances of
64840                 // the candidate type. If one or more constituents remain, return a union of those.
64841                 if (type.flags & 1048576 /* Union */) {
64842                     var assignableType = filterType(type, function (t) { return isRelated(t, candidate); });
64843                     if (!(assignableType.flags & 131072 /* Never */)) {
64844                         return assignableType;
64845                     }
64846                 }
64847                 // If the candidate type is a subtype of the target type, narrow to the candidate type.
64848                 // Otherwise, if the target type is assignable to the candidate type, keep the target type.
64849                 // Otherwise, if the candidate type is assignable to the target type, narrow to the candidate
64850                 // type. Otherwise, the types are completely unrelated, so narrow to an intersection of the
64851                 // two types.
64852                 return isTypeSubtypeOf(candidate, type) ? candidate :
64853                     isTypeAssignableTo(type, candidate) ? type :
64854                         isTypeAssignableTo(candidate, type) ? candidate :
64855                             getIntersectionType([type, candidate]);
64856             }
64857             function narrowTypeByCallExpression(type, callExpression, assumeTrue) {
64858                 if (hasMatchingArgument(callExpression, reference)) {
64859                     var signature = assumeTrue || !ts.isCallChain(callExpression) ? getEffectsSignature(callExpression) : undefined;
64860                     var predicate = signature && getTypePredicateOfSignature(signature);
64861                     if (predicate && (predicate.kind === 0 /* This */ || predicate.kind === 1 /* Identifier */)) {
64862                         return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue);
64863                     }
64864                 }
64865                 return type;
64866             }
64867             function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) {
64868                 // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
64869                 if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) {
64870                     var predicateArgument = getTypePredicateArgument(predicate, callExpression);
64871                     if (predicateArgument) {
64872                         if (isMatchingReference(reference, predicateArgument)) {
64873                             return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
64874                         }
64875                         if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) &&
64876                             !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) {
64877                             type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
64878                         }
64879                         if (isMatchingReferenceDiscriminant(predicateArgument, type)) {
64880                             return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); });
64881                         }
64882                     }
64883                 }
64884                 return type;
64885             }
64886             // Narrow the given type based on the given expression having the assumed boolean value. The returned type
64887             // will be a subtype or the same type as the argument.
64888             function narrowType(type, expr, assumeTrue) {
64889                 // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a`
64890                 if (ts.isExpressionOfOptionalChainRoot(expr) ||
64891                     ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) {
64892                     return narrowTypeByOptionality(type, expr, assumeTrue);
64893                 }
64894                 switch (expr.kind) {
64895                     case 78 /* Identifier */:
64896                     case 107 /* ThisKeyword */:
64897                     case 105 /* SuperKeyword */:
64898                     case 201 /* PropertyAccessExpression */:
64899                     case 202 /* ElementAccessExpression */:
64900                         return narrowTypeByTruthiness(type, expr, assumeTrue);
64901                     case 203 /* CallExpression */:
64902                         return narrowTypeByCallExpression(type, expr, assumeTrue);
64903                     case 207 /* ParenthesizedExpression */:
64904                     case 225 /* NonNullExpression */:
64905                         return narrowType(type, expr.expression, assumeTrue);
64906                     case 216 /* BinaryExpression */:
64907                         return narrowTypeByBinaryExpression(type, expr, assumeTrue);
64908                     case 214 /* PrefixUnaryExpression */:
64909                         if (expr.operator === 53 /* ExclamationToken */) {
64910                             return narrowType(type, expr.operand, !assumeTrue);
64911                         }
64912                         break;
64913                 }
64914                 return type;
64915             }
64916             function narrowTypeByOptionality(type, expr, assumePresent) {
64917                 if (isMatchingReference(reference, expr)) {
64918                     return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */);
64919                 }
64920                 if (isMatchingReferenceDiscriminant(expr, type)) {
64921                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); });
64922                 }
64923                 return type;
64924             }
64925         }
64926         function getTypeOfSymbolAtLocation(symbol, location) {
64927             symbol = symbol.exportSymbol || symbol;
64928             // If we have an identifier or a property access at the given location, if the location is
64929             // an dotted name expression, and if the location is not an assignment target, obtain the type
64930             // of the expression (which will reflect control flow analysis). If the expression indeed
64931             // resolved to the given symbol, return the narrowed type.
64932             if (location.kind === 78 /* Identifier */) {
64933                 if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) {
64934                     location = location.parent;
64935                 }
64936                 if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) {
64937                     var type = getTypeOfExpression(location);
64938                     if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
64939                         return type;
64940                     }
64941                 }
64942             }
64943             // The location isn't a reference to the given symbol, meaning we're being asked
64944             // a hypothetical question of what type the symbol would have if there was a reference
64945             // to it at the given location. Since we have no control flow information for the
64946             // hypothetical reference (control flow information is created and attached by the
64947             // binder), we simply return the declared type of the symbol.
64948             return getTypeOfSymbol(symbol);
64949         }
64950         function getControlFlowContainer(node) {
64951             return ts.findAncestor(node.parent, function (node) {
64952                 return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
64953                     node.kind === 257 /* ModuleBlock */ ||
64954                     node.kind === 297 /* SourceFile */ ||
64955                     node.kind === 163 /* PropertyDeclaration */;
64956             });
64957         }
64958         // Check if a parameter is assigned anywhere within its declaring function.
64959         function isParameterAssigned(symbol) {
64960             var func = ts.getRootDeclaration(symbol.valueDeclaration).parent;
64961             var links = getNodeLinks(func);
64962             if (!(links.flags & 8388608 /* AssignmentsMarked */)) {
64963                 links.flags |= 8388608 /* AssignmentsMarked */;
64964                 if (!hasParentWithAssignmentsMarked(func)) {
64965                     markParameterAssignments(func);
64966                 }
64967             }
64968             return symbol.isAssigned || false;
64969         }
64970         function hasParentWithAssignmentsMarked(node) {
64971             return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); });
64972         }
64973         function markParameterAssignments(node) {
64974             if (node.kind === 78 /* Identifier */) {
64975                 if (ts.isAssignmentTarget(node)) {
64976                     var symbol = getResolvedSymbol(node);
64977                     if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 160 /* Parameter */) {
64978                         symbol.isAssigned = true;
64979                     }
64980                 }
64981             }
64982             else {
64983                 ts.forEachChild(node, markParameterAssignments);
64984             }
64985         }
64986         function isConstVariable(symbol) {
64987             return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType;
64988         }
64989         /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
64990         function removeOptionalityFromDeclaredType(declaredType, declaration) {
64991             if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) {
64992                 var annotationIncludesUndefined = strictNullChecks &&
64993                     declaration.kind === 160 /* Parameter */ &&
64994                     declaration.initializer &&
64995                     getFalsyFlags(declaredType) & 32768 /* Undefined */ &&
64996                     !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */);
64997                 popTypeResolution();
64998                 return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
64999             }
65000             else {
65001                 reportCircularityError(declaration.symbol);
65002                 return declaredType;
65003             }
65004         }
65005         function isConstraintPosition(node) {
65006             var parent = node.parent;
65007             return parent.kind === 201 /* PropertyAccessExpression */ ||
65008                 parent.kind === 203 /* CallExpression */ && parent.expression === node ||
65009                 parent.kind === 202 /* ElementAccessExpression */ && parent.expression === node ||
65010                 parent.kind === 198 /* BindingElement */ && parent.name === node && !!parent.initializer;
65011         }
65012         function typeHasNullableConstraint(type) {
65013             return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */);
65014         }
65015         function getConstraintForLocation(type, node) {
65016             // When a node is the left hand expression of a property access, element access, or call expression,
65017             // and the type of the node includes type variables with constraints that are nullable, we fetch the
65018             // apparent type of the node *before* performing control flow analysis such that narrowings apply to
65019             // the constraint type.
65020             if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
65021                 return mapType(getWidenedType(type), getBaseConstraintOrType);
65022             }
65023             return type;
65024         }
65025         function isExportOrExportExpression(location) {
65026             return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); });
65027         }
65028         function markAliasReferenced(symbol, location) {
65029             if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) {
65030                 var target = resolveAlias(symbol);
65031                 if (target.flags & 111551 /* Value */) {
65032                     // An alias resolving to a const enum cannot be elided if (1) 'isolatedModules' is enabled
65033                     // (because the const enum value will not be inlined), or if (2) the alias is an export
65034                     // of a const enum declaration that will be preserved.
65035                     if (compilerOptions.isolatedModules ||
65036                         ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) ||
65037                         !isConstEnumOrConstEnumOnlyModule(target)) {
65038                         markAliasSymbolAsReferenced(symbol);
65039                     }
65040                     else {
65041                         markConstEnumAliasAsReferenced(symbol);
65042                     }
65043                 }
65044             }
65045         }
65046         function checkIdentifier(node) {
65047             var symbol = getResolvedSymbol(node);
65048             if (symbol === unknownSymbol) {
65049                 return errorType;
65050             }
65051             // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects.
65052             // Although in down-level emit of arrow function, we emit it using function expression which means that
65053             // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects
65054             // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior.
65055             // To avoid that we will give an error to users if they use arguments objects in arrow function so that they
65056             // can explicitly bound arguments objects
65057             if (symbol === argumentsSymbol) {
65058                 var container = ts.getContainingFunction(node);
65059                 if (languageVersion < 2 /* ES2015 */) {
65060                     if (container.kind === 209 /* ArrowFunction */) {
65061                         error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
65062                     }
65063                     else if (ts.hasSyntacticModifier(container, 256 /* Async */)) {
65064                         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);
65065                     }
65066                 }
65067                 getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
65068                 return getTypeOfSymbol(symbol);
65069             }
65070             // We should only mark aliases as referenced if there isn't a local value declaration
65071             // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that
65072             if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) {
65073                 markAliasReferenced(symbol, node);
65074             }
65075             var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
65076             var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol;
65077             if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, sourceSymbol)) {
65078                 addDeprecatedSuggestion(node, sourceSymbol.declarations, node.escapedText);
65079             }
65080             var declaration = localOrExportSymbol.valueDeclaration;
65081             if (localOrExportSymbol.flags & 32 /* Class */) {
65082                 // Due to the emit for class decorators, any reference to the class from inside of the class body
65083                 // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
65084                 // behavior of class names in ES6.
65085                 if (declaration.kind === 252 /* ClassDeclaration */
65086                     && ts.nodeIsDecorated(declaration)) {
65087                     var container = ts.getContainingClass(node);
65088                     while (container !== undefined) {
65089                         if (container === declaration && container.name !== node) {
65090                             getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
65091                             getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
65092                             break;
65093                         }
65094                         container = ts.getContainingClass(container);
65095                     }
65096                 }
65097                 else if (declaration.kind === 221 /* ClassExpression */) {
65098                     // When we emit a class expression with static members that contain a reference
65099                     // to the constructor in the initializer, we will need to substitute that
65100                     // binding with an alias as the class name is not in scope.
65101                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
65102                     while (container.kind !== 297 /* SourceFile */) {
65103                         if (container.parent === declaration) {
65104                             if (container.kind === 163 /* PropertyDeclaration */ && ts.hasSyntacticModifier(container, 32 /* Static */)) {
65105                                 getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
65106                                 getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
65107                             }
65108                             break;
65109                         }
65110                         container = ts.getThisContainer(container, /*includeArrowFunctions*/ false);
65111                     }
65112                 }
65113             }
65114             checkNestedBlockScopedBinding(node, symbol);
65115             var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
65116             var assignmentKind = ts.getAssignmentTargetKind(node);
65117             if (assignmentKind) {
65118                 if (!(localOrExportSymbol.flags & 3 /* Variable */) &&
65119                     !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
65120                     error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol));
65121                     return errorType;
65122                 }
65123                 if (isReadonlySymbol(localOrExportSymbol)) {
65124                     if (localOrExportSymbol.flags & 3 /* Variable */) {
65125                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
65126                     }
65127                     else {
65128                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
65129                     }
65130                     return errorType;
65131                 }
65132             }
65133             var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
65134             // We only narrow variables and parameters occurring in a non-assignment position. For all other
65135             // entities we simply return the declared type.
65136             if (localOrExportSymbol.flags & 3 /* Variable */) {
65137                 if (assignmentKind === 1 /* Definite */) {
65138                     return type;
65139                 }
65140             }
65141             else if (isAlias) {
65142                 declaration = ts.find(symbol.declarations, isSomeImportDeclaration);
65143             }
65144             else {
65145                 return type;
65146             }
65147             if (!declaration) {
65148                 return type;
65149             }
65150             // The declaration container is the innermost function that encloses the declaration of the variable
65151             // or parameter. The flow container is the innermost function starting with which we analyze the control
65152             // flow graph to determine the control flow based type.
65153             var isParameter = ts.getRootDeclaration(declaration).kind === 160 /* Parameter */;
65154             var declarationContainer = getControlFlowContainer(declaration);
65155             var flowContainer = getControlFlowContainer(node);
65156             var isOuterVariable = flowContainer !== declarationContainer;
65157             var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
65158             var isModuleExports = symbol.flags & 134217728 /* ModuleExports */;
65159             // When the control flow originates in a function expression or arrow function and we are referencing
65160             // a const variable or parameter from an outer function, we extend the origin of the control flow
65161             // analysis to include the immediately enclosing function.
65162             while (flowContainer !== declarationContainer && (flowContainer.kind === 208 /* FunctionExpression */ ||
65163                 flowContainer.kind === 209 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
65164                 (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
65165                 flowContainer = getControlFlowContainer(flowContainer);
65166             }
65167             // We only look for uninitialized variables in strict null checking mode, and only when we can analyze
65168             // the entire control flow graph from the variable's declaration (i.e. when the flow container and
65169             // declaration container are the same).
65170             var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) ||
65171                 type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 ||
65172                     isInTypeQuery(node) || node.parent.kind === 270 /* ExportSpecifier */) ||
65173                 node.parent.kind === 225 /* NonNullExpression */ ||
65174                 declaration.kind === 249 /* VariableDeclaration */ && declaration.exclamationToken ||
65175                 declaration.flags & 8388608 /* Ambient */;
65176             var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) :
65177                 type === autoType || type === autoArrayType ? undefinedType :
65178                     getOptionalType(type);
65179             var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized);
65180             // A variable is considered uninitialized when it is possible to analyze the entire control flow graph
65181             // from declaration to use, and when the variable's declared type doesn't include undefined but the
65182             // control flow based type does include undefined.
65183             if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) {
65184                 if (flowType === autoType || flowType === autoArrayType) {
65185                     if (noImplicitAny) {
65186                         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));
65187                         error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
65188                     }
65189                     return convertAutoToAny(flowType);
65190                 }
65191             }
65192             else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
65193                 error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
65194                 // Return the declared type to reduce follow-on errors
65195                 return type;
65196             }
65197             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
65198         }
65199         function isInsideFunction(node, threshold) {
65200             return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); });
65201         }
65202         function getPartOfForStatementContainingNode(node, container) {
65203             return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; });
65204         }
65205         function checkNestedBlockScopedBinding(node, symbol) {
65206             if (languageVersion >= 2 /* ES2015 */ ||
65207                 (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
65208                 ts.isSourceFile(symbol.valueDeclaration) ||
65209                 symbol.valueDeclaration.parent.kind === 287 /* CatchClause */) {
65210                 return;
65211             }
65212             // 1. walk from the use site up to the declaration and check
65213             // if there is anything function like between declaration and use-site (is binding/class is captured in function).
65214             // 2. walk from the declaration up to the boundary of lexical environment and check
65215             // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement)
65216             var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
65217             var usedInFunction = isInsideFunction(node.parent, container);
65218             var current = container;
65219             var containedInIterationStatement = false;
65220             while (current && !ts.nodeStartsNewLexicalEnvironment(current)) {
65221                 if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) {
65222                     containedInIterationStatement = true;
65223                     break;
65224                 }
65225                 current = current.parent;
65226             }
65227             if (containedInIterationStatement) {
65228                 if (usedInFunction) {
65229                     // mark iteration statement as containing block-scoped binding captured in some function
65230                     var capturesBlockScopeBindingInLoopBody = true;
65231                     if (ts.isForStatement(container)) {
65232                         var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */);
65233                         if (varDeclList && varDeclList.parent === container) {
65234                             var part = getPartOfForStatementContainingNode(node.parent, container);
65235                             if (part) {
65236                                 var links = getNodeLinks(part);
65237                                 links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */;
65238                                 var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
65239                                 ts.pushIfUnique(capturedBindings, symbol);
65240                                 if (part === container.initializer) {
65241                                     capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body
65242                                 }
65243                             }
65244                         }
65245                     }
65246                     if (capturesBlockScopeBindingInLoopBody) {
65247                         getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
65248                     }
65249                 }
65250                 // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement.
65251                 // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back.
65252                 if (ts.isForStatement(container)) {
65253                     var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */);
65254                     if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) {
65255                         getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */;
65256                     }
65257                 }
65258                 // set 'declared inside loop' bit on the block-scoped binding
65259                 getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */;
65260             }
65261             if (usedInFunction) {
65262                 getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */;
65263             }
65264         }
65265         function isBindingCapturedByNode(node, decl) {
65266             var links = getNodeLinks(node);
65267             return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl));
65268         }
65269         function isAssignedInBodyOfForStatement(node, container) {
65270             // skip parenthesized nodes
65271             var current = node;
65272             while (current.parent.kind === 207 /* ParenthesizedExpression */) {
65273                 current = current.parent;
65274             }
65275             // check if node is used as LHS in some assignment expression
65276             var isAssigned = false;
65277             if (ts.isAssignmentTarget(current)) {
65278                 isAssigned = true;
65279             }
65280             else if ((current.parent.kind === 214 /* PrefixUnaryExpression */ || current.parent.kind === 215 /* PostfixUnaryExpression */)) {
65281                 var expr = current.parent;
65282                 isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */;
65283             }
65284             if (!isAssigned) {
65285                 return false;
65286             }
65287             // at this point we know that node is the target of assignment
65288             // now check that modification happens inside the statement part of the ForStatement
65289             return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; });
65290         }
65291         function captureLexicalThis(node, container) {
65292             getNodeLinks(node).flags |= 2 /* LexicalThis */;
65293             if (container.kind === 163 /* PropertyDeclaration */ || container.kind === 166 /* Constructor */) {
65294                 var classNode = container.parent;
65295                 getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
65296             }
65297             else {
65298                 getNodeLinks(container).flags |= 4 /* CaptureThis */;
65299             }
65300         }
65301         function findFirstSuperCall(node) {
65302             return ts.isSuperCall(node) ? node :
65303                 ts.isFunctionLike(node) ? undefined :
65304                     ts.forEachChild(node, findFirstSuperCall);
65305         }
65306         /**
65307          * Check if the given class-declaration extends null then return true.
65308          * Otherwise, return false
65309          * @param classDecl a class declaration to check if it extends null
65310          */
65311         function classDeclarationExtendsNull(classDecl) {
65312             var classSymbol = getSymbolOfNode(classDecl);
65313             var classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
65314             var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
65315             return baseConstructorType === nullWideningType;
65316         }
65317         function checkThisBeforeSuper(node, container, diagnosticMessage) {
65318             var containingClassDecl = container.parent;
65319             var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl);
65320             // If a containing class does not have extends clause or the class extends null
65321             // skip checking whether super statement is called before "this" accessing.
65322             if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
65323                 if (node.flowNode && !isPostSuperFlowNode(node.flowNode, /*noCacheCheck*/ false)) {
65324                     error(node, diagnosticMessage);
65325                 }
65326             }
65327         }
65328         function checkThisExpression(node) {
65329             // Stop at the first arrow function so that we can
65330             // tell whether 'this' needs to be captured.
65331             var container = ts.getThisContainer(node, /* includeArrowFunctions */ true);
65332             var capturedByArrowFunction = false;
65333             if (container.kind === 166 /* Constructor */) {
65334                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
65335             }
65336             // Now skip arrow functions to get the "real" owner of 'this'.
65337             if (container.kind === 209 /* ArrowFunction */) {
65338                 container = ts.getThisContainer(container, /* includeArrowFunctions */ false);
65339                 capturedByArrowFunction = true;
65340             }
65341             switch (container.kind) {
65342                 case 256 /* ModuleDeclaration */:
65343                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
65344                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
65345                     break;
65346                 case 255 /* EnumDeclaration */:
65347                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
65348                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
65349                     break;
65350                 case 166 /* Constructor */:
65351                     if (isInConstructorArgumentInitializer(node, container)) {
65352                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);
65353                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
65354                     }
65355                     break;
65356                 case 163 /* PropertyDeclaration */:
65357                 case 162 /* PropertySignature */:
65358                     if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
65359                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer);
65360                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
65361                     }
65362                     break;
65363                 case 158 /* ComputedPropertyName */:
65364                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
65365                     break;
65366             }
65367             // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope.
65368             if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
65369                 captureLexicalThis(node, container);
65370             }
65371             var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
65372             if (noImplicitThis) {
65373                 var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
65374                 if (type === globalThisType_1 && capturedByArrowFunction) {
65375                     error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
65376                 }
65377                 else if (!type) {
65378                     // With noImplicitThis, functions may not reference 'this' if it has type 'any'
65379                     var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
65380                     if (!ts.isSourceFile(container)) {
65381                         var outsideThis = tryGetThisTypeAt(container);
65382                         if (outsideThis && outsideThis !== globalThisType_1) {
65383                             ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
65384                         }
65385                     }
65386                 }
65387             }
65388             return type || anyType;
65389         }
65390         function tryGetThisTypeAt(node, includeGlobalThis, container) {
65391             if (includeGlobalThis === void 0) { includeGlobalThis = true; }
65392             if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
65393             var isInJS = ts.isInJSFile(node);
65394             if (ts.isFunctionLike(container) &&
65395                 (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) {
65396                 var thisType = getThisTypeOfDeclaration(container) || isInJS && getTypeForThisExpressionFromJSDoc(container);
65397                 // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated.
65398                 // If this is a function in a JS file, it might be a class method.
65399                 if (!thisType) {
65400                     var className = getClassNameFromPrototypeMethod(container);
65401                     if (isInJS && className) {
65402                         var classSymbol = checkExpression(className).symbol;
65403                         if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) {
65404                             thisType = getDeclaredTypeOfSymbol(classSymbol).thisType;
65405                         }
65406                     }
65407                     else if (isJSConstructor(container)) {
65408                         thisType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType;
65409                     }
65410                     thisType || (thisType = getContextualThisParameterType(container));
65411                 }
65412                 if (thisType) {
65413                     return getFlowTypeOfReference(node, thisType);
65414                 }
65415             }
65416             if (ts.isClassLike(container.parent)) {
65417                 var symbol = getSymbolOfNode(container.parent);
65418                 var type = ts.hasSyntacticModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
65419                 return getFlowTypeOfReference(node, type);
65420             }
65421             if (ts.isSourceFile(container)) {
65422                 // look up in the source file's locals or exports
65423                 if (container.commonJsModuleIndicator) {
65424                     var fileSymbol = getSymbolOfNode(container);
65425                     return fileSymbol && getTypeOfSymbol(fileSymbol);
65426                 }
65427                 else if (container.externalModuleIndicator) {
65428                     // TODO: Maybe issue a better error than 'object is possibly undefined'
65429                     return undefinedType;
65430                 }
65431                 else if (includeGlobalThis) {
65432                     return getTypeOfSymbol(globalThisSymbol);
65433                 }
65434             }
65435         }
65436         function getExplicitThisType(node) {
65437             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
65438             if (ts.isFunctionLike(container)) {
65439                 var signature = getSignatureFromDeclaration(container);
65440                 if (signature.thisParameter) {
65441                     return getExplicitTypeOfSymbol(signature.thisParameter);
65442                 }
65443             }
65444             if (ts.isClassLike(container.parent)) {
65445                 var symbol = getSymbolOfNode(container.parent);
65446                 return ts.hasSyntacticModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
65447             }
65448         }
65449         function getClassNameFromPrototypeMethod(container) {
65450             // Check if it's the RHS of a x.prototype.y = function [name]() { .... }
65451             if (container.kind === 208 /* FunctionExpression */ &&
65452                 ts.isBinaryExpression(container.parent) &&
65453                 ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
65454                 // Get the 'x' of 'x.prototype.y = container'
65455                 return container.parent // x.prototype.y = container
65456                     .left // x.prototype.y
65457                     .expression // x.prototype
65458                     .expression; // x
65459             }
65460             // x.prototype = { method() { } }
65461             else if (container.kind === 165 /* MethodDeclaration */ &&
65462                 container.parent.kind === 200 /* ObjectLiteralExpression */ &&
65463                 ts.isBinaryExpression(container.parent.parent) &&
65464                 ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
65465                 return container.parent.parent.left.expression;
65466             }
65467             // x.prototype = { method: function() { } }
65468             else if (container.kind === 208 /* FunctionExpression */ &&
65469                 container.parent.kind === 288 /* PropertyAssignment */ &&
65470                 container.parent.parent.kind === 200 /* ObjectLiteralExpression */ &&
65471                 ts.isBinaryExpression(container.parent.parent.parent) &&
65472                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
65473                 return container.parent.parent.parent.left.expression;
65474             }
65475             // Object.defineProperty(x, "method", { value: function() { } });
65476             // Object.defineProperty(x, "method", { set: (x: () => void) => void });
65477             // Object.defineProperty(x, "method", { get: () => function() { }) });
65478             else if (container.kind === 208 /* FunctionExpression */ &&
65479                 ts.isPropertyAssignment(container.parent) &&
65480                 ts.isIdentifier(container.parent.name) &&
65481                 (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") &&
65482                 ts.isObjectLiteralExpression(container.parent.parent) &&
65483                 ts.isCallExpression(container.parent.parent.parent) &&
65484                 container.parent.parent.parent.arguments[2] === container.parent.parent &&
65485                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
65486                 return container.parent.parent.parent.arguments[0].expression;
65487             }
65488             // Object.defineProperty(x, "method", { value() { } });
65489             // Object.defineProperty(x, "method", { set(x: () => void) {} });
65490             // Object.defineProperty(x, "method", { get() { return () => {} } });
65491             else if (ts.isMethodDeclaration(container) &&
65492                 ts.isIdentifier(container.name) &&
65493                 (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") &&
65494                 ts.isObjectLiteralExpression(container.parent) &&
65495                 ts.isCallExpression(container.parent.parent) &&
65496                 container.parent.parent.arguments[2] === container.parent &&
65497                 ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
65498                 return container.parent.parent.arguments[0].expression;
65499             }
65500         }
65501         function getTypeForThisExpressionFromJSDoc(node) {
65502             var jsdocType = ts.getJSDocType(node);
65503             if (jsdocType && jsdocType.kind === 308 /* JSDocFunctionType */) {
65504                 var jsDocFunctionType = jsdocType;
65505                 if (jsDocFunctionType.parameters.length > 0 &&
65506                     jsDocFunctionType.parameters[0].name &&
65507                     jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) {
65508                     return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type);
65509                 }
65510             }
65511             var thisTag = ts.getJSDocThisTag(node);
65512             if (thisTag && thisTag.typeExpression) {
65513                 return getTypeFromTypeNode(thisTag.typeExpression);
65514             }
65515         }
65516         function isInConstructorArgumentInitializer(node, constructorDecl) {
65517             return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 160 /* Parameter */ && n.parent === constructorDecl; });
65518         }
65519         function checkSuperExpression(node) {
65520             var isCallExpression = node.parent.kind === 203 /* CallExpression */ && node.parent.expression === node;
65521             var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true);
65522             var container = immediateContainer;
65523             var needToCaptureLexicalThis = false;
65524             // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
65525             if (!isCallExpression) {
65526                 while (container && container.kind === 209 /* ArrowFunction */) {
65527                     container = ts.getSuperContainer(container, /*stopOnFunctions*/ true);
65528                     needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
65529                 }
65530             }
65531             var canUseSuperExpression = isLegalUsageOfSuperExpression(container);
65532             var nodeCheckFlag = 0;
65533             if (!canUseSuperExpression) {
65534                 // issue more specific error if super is used in computed property name
65535                 // class A { foo() { return "1" }}
65536                 // class B {
65537                 //     [super.foo()]() {}
65538                 // }
65539                 var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 158 /* ComputedPropertyName */; });
65540                 if (current && current.kind === 158 /* ComputedPropertyName */) {
65541                     error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
65542                 }
65543                 else if (isCallExpression) {
65544                     error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
65545                 }
65546                 else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */)) {
65547                     error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
65548                 }
65549                 else {
65550                     error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
65551                 }
65552                 return errorType;
65553             }
65554             if (!isCallExpression && immediateContainer.kind === 166 /* Constructor */) {
65555                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
65556             }
65557             if (ts.hasSyntacticModifier(container, 32 /* Static */) || isCallExpression) {
65558                 nodeCheckFlag = 512 /* SuperStatic */;
65559             }
65560             else {
65561                 nodeCheckFlag = 256 /* SuperInstance */;
65562             }
65563             getNodeLinks(node).flags |= nodeCheckFlag;
65564             // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference.
65565             // This is due to the fact that we emit the body of an async function inside of a generator function. As generator
65566             // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper
65567             // uses an arrow function, which is permitted to reference `super`.
65568             //
65569             // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property
65570             // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value
65571             // of a property or indexed access, either as part of an assignment expression or destructuring assignment.
65572             //
65573             // The simplest case is reading a value, in which case we will emit something like the following:
65574             //
65575             //  // ts
65576             //  ...
65577             //  async asyncMethod() {
65578             //    let x = await super.asyncMethod();
65579             //    return x;
65580             //  }
65581             //  ...
65582             //
65583             //  // js
65584             //  ...
65585             //  asyncMethod() {
65586             //      const _super = Object.create(null, {
65587             //        asyncMethod: { get: () => super.asyncMethod },
65588             //      });
65589             //      return __awaiter(this, arguments, Promise, function *() {
65590             //          let x = yield _super.asyncMethod.call(this);
65591             //          return x;
65592             //      });
65593             //  }
65594             //  ...
65595             //
65596             // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases
65597             // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment:
65598             //
65599             //  // ts
65600             //  ...
65601             //  async asyncMethod(ar: Promise<any[]>) {
65602             //      [super.a, super.b] = await ar;
65603             //  }
65604             //  ...
65605             //
65606             //  // js
65607             //  ...
65608             //  asyncMethod(ar) {
65609             //      const _super = Object.create(null, {
65610             //        a: { get: () => super.a, set: (v) => super.a = v },
65611             //        b: { get: () => super.b, set: (v) => super.b = v }
65612             //      };
65613             //      return __awaiter(this, arguments, Promise, function *() {
65614             //          [_super.a, _super.b] = yield ar;
65615             //      });
65616             //  }
65617             //  ...
65618             //
65619             // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments
65620             // as a call expression cannot be used as the target of a destructuring assignment while a property access can.
65621             //
65622             // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations.
65623             if (container.kind === 165 /* MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* Async */)) {
65624                 if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) {
65625                     getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */;
65626                 }
65627                 else {
65628                     getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */;
65629                 }
65630             }
65631             if (needToCaptureLexicalThis) {
65632                 // call expressions are allowed only in constructors so they should always capture correct 'this'
65633                 // super property access expressions can also appear in arrow functions -
65634                 // in this case they should also use correct lexical this
65635                 captureLexicalThis(node.parent, container);
65636             }
65637             if (container.parent.kind === 200 /* ObjectLiteralExpression */) {
65638                 if (languageVersion < 2 /* ES2015 */) {
65639                     error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
65640                     return errorType;
65641                 }
65642                 else {
65643                     // for object literal assume that type of 'super' is 'any'
65644                     return anyType;
65645                 }
65646             }
65647             // at this point the only legal case for parent is ClassLikeDeclaration
65648             var classLikeDeclaration = container.parent;
65649             if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) {
65650                 error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class);
65651                 return errorType;
65652             }
65653             var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration));
65654             var baseClassType = classType && getBaseTypes(classType)[0];
65655             if (!baseClassType) {
65656                 return errorType;
65657             }
65658             if (container.kind === 166 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
65659                 // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
65660                 error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
65661                 return errorType;
65662             }
65663             return nodeCheckFlag === 512 /* SuperStatic */
65664                 ? getBaseConstructorTypeOfClass(classType)
65665                 : getTypeWithThisArgument(baseClassType, classType.thisType);
65666             function isLegalUsageOfSuperExpression(container) {
65667                 if (!container) {
65668                     return false;
65669                 }
65670                 if (isCallExpression) {
65671                     // TS 1.0 SPEC (April 2014): 4.8.1
65672                     // Super calls are only permitted in constructors of derived classes
65673                     return container.kind === 166 /* Constructor */;
65674                 }
65675                 else {
65676                     // TS 1.0 SPEC (April 2014)
65677                     // 'super' property access is allowed
65678                     // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
65679                     // - In a static member function or static member accessor
65680                     // topmost container must be something that is directly nested in the class declaration\object literal expression
65681                     if (ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */) {
65682                         if (ts.hasSyntacticModifier(container, 32 /* Static */)) {
65683                             return container.kind === 165 /* MethodDeclaration */ ||
65684                                 container.kind === 164 /* MethodSignature */ ||
65685                                 container.kind === 167 /* GetAccessor */ ||
65686                                 container.kind === 168 /* SetAccessor */;
65687                         }
65688                         else {
65689                             return container.kind === 165 /* MethodDeclaration */ ||
65690                                 container.kind === 164 /* MethodSignature */ ||
65691                                 container.kind === 167 /* GetAccessor */ ||
65692                                 container.kind === 168 /* SetAccessor */ ||
65693                                 container.kind === 163 /* PropertyDeclaration */ ||
65694                                 container.kind === 162 /* PropertySignature */ ||
65695                                 container.kind === 166 /* Constructor */;
65696                         }
65697                     }
65698                 }
65699                 return false;
65700             }
65701         }
65702         function getContainingObjectLiteral(func) {
65703             return (func.kind === 165 /* MethodDeclaration */ ||
65704                 func.kind === 167 /* GetAccessor */ ||
65705                 func.kind === 168 /* SetAccessor */) && func.parent.kind === 200 /* ObjectLiteralExpression */ ? func.parent :
65706                 func.kind === 208 /* FunctionExpression */ && func.parent.kind === 288 /* PropertyAssignment */ ? func.parent.parent :
65707                     undefined;
65708         }
65709         function getThisTypeArgument(type) {
65710             return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : undefined;
65711         }
65712         function getThisTypeFromContextualType(type) {
65713             return mapType(type, function (t) {
65714                 return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
65715             });
65716         }
65717         function getContextualThisParameterType(func) {
65718             if (func.kind === 209 /* ArrowFunction */) {
65719                 return undefined;
65720             }
65721             if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
65722                 var contextualSignature = getContextualSignature(func);
65723                 if (contextualSignature) {
65724                     var thisParameter = contextualSignature.thisParameter;
65725                     if (thisParameter) {
65726                         return getTypeOfSymbol(thisParameter);
65727                     }
65728                 }
65729             }
65730             var inJs = ts.isInJSFile(func);
65731             if (noImplicitThis || inJs) {
65732                 var containingLiteral = getContainingObjectLiteral(func);
65733                 if (containingLiteral) {
65734                     // We have an object literal method. Check if the containing object literal has a contextual type
65735                     // that includes a ThisType<T>. If so, T is the contextual type for 'this'. We continue looking in
65736                     // any directly enclosing object literals.
65737                     var contextualType = getApparentTypeOfContextualType(containingLiteral);
65738                     var literal = containingLiteral;
65739                     var type = contextualType;
65740                     while (type) {
65741                         var thisType = getThisTypeFromContextualType(type);
65742                         if (thisType) {
65743                             return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
65744                         }
65745                         if (literal.parent.kind !== 288 /* PropertyAssignment */) {
65746                             break;
65747                         }
65748                         literal = literal.parent.parent;
65749                         type = getApparentTypeOfContextualType(literal);
65750                     }
65751                     // There was no contextual ThisType<T> for the containing object literal, so the contextual type
65752                     // for 'this' is the non-null form of the contextual type for the containing object literal or
65753                     // the type of the object literal itself.
65754                     return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral));
65755                 }
65756                 // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the
65757                 // contextual type for 'this' is 'obj'.
65758                 var parent = ts.walkUpParenthesizedExpressions(func.parent);
65759                 if (parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) {
65760                     var target = parent.left;
65761                     if (ts.isAccessExpression(target)) {
65762                         var expression = target.expression;
65763                         // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }`
65764                         if (inJs && ts.isIdentifier(expression)) {
65765                             var sourceFile = ts.getSourceFileOfNode(parent);
65766                             if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
65767                                 return undefined;
65768                             }
65769                         }
65770                         return getWidenedType(checkExpressionCached(expression));
65771                     }
65772                 }
65773             }
65774             return undefined;
65775         }
65776         // Return contextual type of parameter or undefined if no contextual type is available
65777         function getContextuallyTypedParameterType(parameter) {
65778             var func = parameter.parent;
65779             if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
65780                 return undefined;
65781             }
65782             var iife = ts.getImmediatelyInvokedFunctionExpression(func);
65783             if (iife && iife.arguments) {
65784                 var args = getEffectiveCallArguments(iife);
65785                 var indexOfParameter = func.parameters.indexOf(parameter);
65786                 if (parameter.dotDotDotToken) {
65787                     return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined, 0 /* Normal */);
65788                 }
65789                 var links = getNodeLinks(iife);
65790                 var cached = links.resolvedSignature;
65791                 links.resolvedSignature = anySignature;
65792                 var type = indexOfParameter < args.length ?
65793                     getWidenedLiteralType(checkExpression(args[indexOfParameter])) :
65794                     parameter.initializer ? undefined : undefinedWideningType;
65795                 links.resolvedSignature = cached;
65796                 return type;
65797             }
65798             var contextualSignature = getContextualSignature(func);
65799             if (contextualSignature) {
65800                 var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0);
65801                 return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ?
65802                     getRestTypeAtPosition(contextualSignature, index) :
65803                     tryGetTypeAtPosition(contextualSignature, index);
65804             }
65805         }
65806         function getContextualTypeForVariableLikeDeclaration(declaration) {
65807             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
65808             if (typeNode) {
65809                 return getTypeFromTypeNode(typeNode);
65810             }
65811             switch (declaration.kind) {
65812                 case 160 /* Parameter */:
65813                     return getContextuallyTypedParameterType(declaration);
65814                 case 198 /* BindingElement */:
65815                     return getContextualTypeForBindingElement(declaration);
65816                 case 163 /* PropertyDeclaration */:
65817                     if (ts.hasSyntacticModifier(declaration, 32 /* Static */)) {
65818                         return getContextualTypeForStaticPropertyDeclaration(declaration);
65819                     }
65820                 // By default, do nothing and return undefined - only the above cases have context implied by a parent
65821             }
65822         }
65823         function getContextualTypeForBindingElement(declaration) {
65824             var parent = declaration.parent.parent;
65825             var name = declaration.propertyName || declaration.name;
65826             var parentType = getContextualTypeForVariableLikeDeclaration(parent) ||
65827                 parent.kind !== 198 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent);
65828             if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name))
65829                 return undefined;
65830             if (parent.name.kind === 197 /* ArrayBindingPattern */) {
65831                 var index = ts.indexOfNode(declaration.parent.elements, declaration);
65832                 if (index < 0)
65833                     return undefined;
65834                 return getContextualTypeForElementExpression(parentType, index);
65835             }
65836             var nameType = getLiteralTypeFromPropertyName(name);
65837             if (isTypeUsableAsPropertyName(nameType)) {
65838                 var text = getPropertyNameFromType(nameType);
65839                 return getTypeOfPropertyOfType(parentType, text);
65840             }
65841         }
65842         function getContextualTypeForStaticPropertyDeclaration(declaration) {
65843             var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent);
65844             if (!parentType)
65845                 return undefined;
65846             return getTypeOfPropertyOfContextualType(parentType, getSymbolOfNode(declaration).escapedName);
65847         }
65848         // In a variable, parameter or property declaration with a type annotation,
65849         //   the contextual type of an initializer expression is the type of the variable, parameter or property.
65850         // Otherwise, in a parameter declaration of a contextually typed function expression,
65851         //   the contextual type of an initializer expression is the contextual type of the parameter.
65852         // Otherwise, in a variable or parameter declaration with a binding pattern name,
65853         //   the contextual type of an initializer expression is the type implied by the binding pattern.
65854         // Otherwise, in a binding pattern inside a variable or parameter declaration,
65855         //   the contextual type of an initializer expression is the type annotation of the containing declaration, if present.
65856         function getContextualTypeForInitializerExpression(node, contextFlags) {
65857             var declaration = node.parent;
65858             if (ts.hasInitializer(declaration) && node === declaration.initializer) {
65859                 var result = getContextualTypeForVariableLikeDeclaration(declaration);
65860                 if (result) {
65861                     return result;
65862                 }
65863                 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
65864                     return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false);
65865                 }
65866             }
65867             return undefined;
65868         }
65869         function getContextualTypeForReturnExpression(node) {
65870             var func = ts.getContainingFunction(node);
65871             if (func) {
65872                 var contextualReturnType = getContextualReturnType(func);
65873                 if (contextualReturnType) {
65874                     var functionFlags = ts.getFunctionFlags(func);
65875                     if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function
65876                         var use = functionFlags & 2 /* Async */ ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
65877                         var iterationTypes = getIterationTypesOfIterable(contextualReturnType, use, /*errorNode*/ undefined);
65878                         if (!iterationTypes) {
65879                             return undefined;
65880                         }
65881                         contextualReturnType = iterationTypes.returnType;
65882                         // falls through to unwrap Promise for AsyncGenerators
65883                     }
65884                     if (functionFlags & 2 /* Async */) { // Async function or AsyncGenerator function
65885                         var contextualAwaitedType = mapType(contextualReturnType, getAwaitedType);
65886                         return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
65887                     }
65888                     return contextualReturnType; // Regular function or Generator function
65889                 }
65890             }
65891             return undefined;
65892         }
65893         function getContextualTypeForAwaitOperand(node, contextFlags) {
65894             var contextualType = getContextualType(node, contextFlags);
65895             if (contextualType) {
65896                 var contextualAwaitedType = getAwaitedType(contextualType);
65897                 return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
65898             }
65899             return undefined;
65900         }
65901         function getContextualTypeForYieldOperand(node) {
65902             var func = ts.getContainingFunction(node);
65903             if (func) {
65904                 var functionFlags = ts.getFunctionFlags(func);
65905                 var contextualReturnType = getContextualReturnType(func);
65906                 if (contextualReturnType) {
65907                     return node.asteriskToken
65908                         ? contextualReturnType
65909                         : getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
65910                 }
65911             }
65912             return undefined;
65913         }
65914         function isInParameterInitializerBeforeContainingFunction(node) {
65915             var inBindingInitializer = false;
65916             while (node.parent && !ts.isFunctionLike(node.parent)) {
65917                 if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
65918                     return true;
65919                 }
65920                 if (ts.isBindingElement(node.parent) && node.parent.initializer === node) {
65921                     inBindingInitializer = true;
65922                 }
65923                 node = node.parent;
65924             }
65925             return false;
65926         }
65927         function getContextualIterationType(kind, functionDecl) {
65928             var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* Async */);
65929             var contextualReturnType = getContextualReturnType(functionDecl);
65930             if (contextualReturnType) {
65931                 return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync)
65932                     || undefined;
65933             }
65934             return undefined;
65935         }
65936         function getContextualReturnType(functionDecl) {
65937             // If the containing function has a return type annotation, is a constructor, or is a get accessor whose
65938             // corresponding set accessor has a type annotation, return statements in the function are contextually typed
65939             var returnType = getReturnTypeFromAnnotation(functionDecl);
65940             if (returnType) {
65941                 return returnType;
65942             }
65943             // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature
65944             // and that call signature is non-generic, return statements are contextually typed by the return type of the signature
65945             var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
65946             if (signature && !isResolvingReturnTypeOfSignature(signature)) {
65947                 return getReturnTypeOfSignature(signature);
65948             }
65949             return undefined;
65950         }
65951         // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
65952         function getContextualTypeForArgument(callTarget, arg) {
65953             var args = getEffectiveCallArguments(callTarget);
65954             var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
65955             return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
65956         }
65957         function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
65958             // If we're already in the process of resolving the given signature, don't resolve again as
65959             // that could cause infinite recursion. Instead, return anySignature.
65960             var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
65961             if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
65962                 return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
65963             }
65964             return getTypeAtPosition(signature, argIndex);
65965         }
65966         function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
65967             if (template.parent.kind === 205 /* TaggedTemplateExpression */) {
65968                 return getContextualTypeForArgument(template.parent, substitutionExpression);
65969             }
65970             return undefined;
65971         }
65972         function getContextualTypeForBinaryOperand(node, contextFlags) {
65973             var binaryExpression = node.parent;
65974             var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right;
65975             switch (operatorToken.kind) {
65976                 case 62 /* EqualsToken */:
65977                 case 75 /* AmpersandAmpersandEqualsToken */:
65978                 case 74 /* BarBarEqualsToken */:
65979                 case 76 /* QuestionQuestionEqualsToken */:
65980                     return node === right ? getContextualTypeForAssignmentDeclaration(binaryExpression) : undefined;
65981                 case 56 /* BarBarToken */:
65982                 case 60 /* QuestionQuestionToken */:
65983                     // When an || expression has a contextual type, the operands are contextually typed by that type, except
65984                     // when that type originates in a binding pattern, the right operand is contextually typed by the type of
65985                     // the left operand. When an || expression has no contextual type, the right operand is contextually typed
65986                     // by the type of the left operand, except for the special case of Javascript declarations of the form
65987                     // `namespace.prop = namespace.prop || {}`.
65988                     var type = getContextualType(binaryExpression, contextFlags);
65989                     return node === right && (type && type.pattern || !type && !ts.isDefaultedExpandoInitializer(binaryExpression)) ?
65990                         getTypeOfExpression(left) : type;
65991                 case 55 /* AmpersandAmpersandToken */:
65992                 case 27 /* CommaToken */:
65993                     return node === right ? getContextualType(binaryExpression, contextFlags) : undefined;
65994                 default:
65995                     return undefined;
65996             }
65997         }
65998         // In an assignment expression, the right operand is contextually typed by the type of the left operand.
65999         // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand.
66000         function getContextualTypeForAssignmentDeclaration(binaryExpression) {
66001             var kind = ts.getAssignmentDeclarationKind(binaryExpression);
66002             switch (kind) {
66003                 case 0 /* None */:
66004                     return getTypeOfExpression(binaryExpression.left);
66005                 case 5 /* Property */:
66006                 case 1 /* ExportsProperty */:
66007                 case 6 /* Prototype */:
66008                 case 3 /* PrototypeProperty */:
66009                     if (isPossiblyAliasedThisProperty(binaryExpression, kind)) {
66010                         return getContextualTypeForThisPropertyAssignment(binaryExpression, kind);
66011                     }
66012                     // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration.
66013                     // See `bindStaticPropertyAssignment` in `binder.ts`.
66014                     else if (!binaryExpression.left.symbol) {
66015                         return getTypeOfExpression(binaryExpression.left);
66016                     }
66017                     else {
66018                         var decl = binaryExpression.left.symbol.valueDeclaration;
66019                         if (!decl) {
66020                             return undefined;
66021                         }
66022                         var lhs = ts.cast(binaryExpression.left, ts.isAccessExpression);
66023                         var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl);
66024                         if (overallAnnotation) {
66025                             return getTypeFromTypeNode(overallAnnotation);
66026                         }
66027                         else if (ts.isIdentifier(lhs.expression)) {
66028                             var id = lhs.expression;
66029                             var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true);
66030                             if (parentSymbol) {
66031                                 var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
66032                                 if (annotated) {
66033                                     var nameStr = ts.getElementOrPropertyAccessName(lhs);
66034                                     if (nameStr !== undefined) {
66035                                         return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr);
66036                                     }
66037                                 }
66038                                 return undefined;
66039                             }
66040                         }
66041                         return ts.isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left);
66042                     }
66043                 case 2 /* ModuleExports */:
66044                 case 4 /* ThisProperty */:
66045                     return getContextualTypeForThisPropertyAssignment(binaryExpression, kind);
66046                 case 7 /* ObjectDefinePropertyValue */:
66047                 case 8 /* ObjectDefinePropertyExports */:
66048                 case 9 /* ObjectDefinePrototypeProperty */:
66049                     return ts.Debug.fail("Does not apply");
66050                 default:
66051                     return ts.Debug.assertNever(kind);
66052             }
66053         }
66054         function isPossiblyAliasedThisProperty(declaration, kind) {
66055             if (kind === void 0) { kind = ts.getAssignmentDeclarationKind(declaration); }
66056             if (kind === 4 /* ThisProperty */) {
66057                 return true;
66058             }
66059             if (!ts.isInJSFile(declaration) || kind !== 5 /* Property */ || !ts.isIdentifier(declaration.left.expression)) {
66060                 return false;
66061             }
66062             var name = declaration.left.expression.escapedText;
66063             var symbol = resolveName(declaration.left, name, 111551 /* Value */, undefined, undefined, /*isUse*/ true, /*excludeGlobals*/ true);
66064             return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration);
66065         }
66066         function getContextualTypeForThisPropertyAssignment(binaryExpression, kind) {
66067             if (!binaryExpression.symbol)
66068                 return getTypeOfExpression(binaryExpression.left);
66069             if (binaryExpression.symbol.valueDeclaration) {
66070                 var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
66071                 if (annotated) {
66072                     var type = getTypeFromTypeNode(annotated);
66073                     if (type) {
66074                         return type;
66075                     }
66076                 }
66077             }
66078             if (kind === 2 /* ModuleExports */)
66079                 return undefined;
66080             var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression);
66081             if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) {
66082                 return undefined;
66083             }
66084             var thisType = checkThisExpression(thisAccess.expression);
66085             var nameStr = ts.getElementOrPropertyAccessName(thisAccess);
66086             return nameStr !== undefined && getTypeOfPropertyOfContextualType(thisType, nameStr) || undefined;
66087         }
66088         function isCircularMappedProperty(symbol) {
66089             return !!(ts.getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0);
66090         }
66091         function getTypeOfPropertyOfContextualType(type, name) {
66092             return mapType(type, function (t) {
66093                 if (isGenericMappedType(t)) {
66094                     var constraint = getConstraintTypeFromMappedType(t);
66095                     var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
66096                     var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
66097                     if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
66098                         return substituteIndexedMappedType(t, propertyNameType);
66099                     }
66100                 }
66101                 else if (t.flags & 3670016 /* StructuredType */) {
66102                     var prop = getPropertyOfType(t, name);
66103                     if (prop) {
66104                         return isCircularMappedProperty(prop) ? undefined : getTypeOfSymbol(prop);
66105                     }
66106                     if (isTupleType(t)) {
66107                         var restType = getRestTypeOfTupleType(t);
66108                         if (restType && isNumericLiteralName(name) && +name >= 0) {
66109                             return restType;
66110                         }
66111                     }
66112                     return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) ||
66113                         getIndexTypeOfContextualType(t, 0 /* String */);
66114                 }
66115                 return undefined;
66116             }, /*noReductions*/ true);
66117         }
66118         function getIndexTypeOfContextualType(type, kind) {
66119             return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true);
66120         }
66121         // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of
66122         // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one
66123         // exists. Otherwise, it is the type of the string index signature in T, if one exists.
66124         function getContextualTypeForObjectLiteralMethod(node, contextFlags) {
66125             ts.Debug.assert(ts.isObjectLiteralMethod(node));
66126             if (node.flags & 16777216 /* InWithStatement */) {
66127                 // We cannot answer semantic questions within a with block, do not proceed any further
66128                 return undefined;
66129             }
66130             return getContextualTypeForObjectLiteralElement(node, contextFlags);
66131         }
66132         function getContextualTypeForObjectLiteralElement(element, contextFlags) {
66133             var objectLiteral = element.parent;
66134             var type = getApparentTypeOfContextualType(objectLiteral, contextFlags);
66135             if (type) {
66136                 if (hasBindableName(element)) {
66137                     // For a (non-symbol) computed property, there is no reason to look up the name
66138                     // in the type. It will just be "__computed", which does not appear in any
66139                     // SymbolTable.
66140                     var symbolName_3 = getSymbolOfNode(element).escapedName;
66141                     var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3);
66142                     if (propertyType) {
66143                         return propertyType;
66144                     }
66145                 }
66146                 return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) ||
66147                     getIndexTypeOfContextualType(type, 0 /* String */);
66148             }
66149             return undefined;
66150         }
66151         // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is
66152         // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature,
66153         // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated
66154         // type of T.
66155         function getContextualTypeForElementExpression(arrayContextualType, index) {
66156             return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index)
66157                 || mapType(arrayContextualType, function (t) { return getIteratedTypeOrElementType(1 /* Element */, t, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false); }, 
66158                 /*noReductions*/ true));
66159         }
66160         // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type.
66161         function getContextualTypeForConditionalOperand(node, contextFlags) {
66162             var conditional = node.parent;
66163             return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined;
66164         }
66165         function getContextualTypeForChildJsxExpression(node, child) {
66166             var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
66167             // JSX expression is in children of JSX Element, we will look for an "children" attribute (we get the name from JSX.ElementAttributesProperty)
66168             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
66169             if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
66170                 return undefined;
66171             }
66172             var realChildren = ts.getSemanticJsxChildren(node.children);
66173             var childIndex = realChildren.indexOf(child);
66174             var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName);
66175             return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(childFieldType, function (t) {
66176                 if (isArrayLikeType(t)) {
66177                     return getIndexedAccessType(t, getLiteralType(childIndex));
66178                 }
66179                 else {
66180                     return t;
66181                 }
66182             }, /*noReductions*/ true));
66183         }
66184         function getContextualTypeForJsxExpression(node) {
66185             var exprParent = node.parent;
66186             return ts.isJsxAttributeLike(exprParent)
66187                 ? getContextualType(node)
66188                 : ts.isJsxElement(exprParent)
66189                     ? getContextualTypeForChildJsxExpression(exprParent, node)
66190                     : undefined;
66191         }
66192         function getContextualTypeForJsxAttribute(attribute) {
66193             // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
66194             // which is a type of the parameter of the signature we are trying out.
66195             // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName
66196             if (ts.isJsxAttribute(attribute)) {
66197                 var attributesType = getApparentTypeOfContextualType(attribute.parent);
66198                 if (!attributesType || isTypeAny(attributesType)) {
66199                     return undefined;
66200                 }
66201                 return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText);
66202             }
66203             else {
66204                 return getContextualType(attribute.parent);
66205             }
66206         }
66207         // Return true if the given expression is possibly a discriminant value. We limit the kinds of
66208         // expressions we check to those that don't depend on their contextual type in order not to cause
66209         // recursive (and possibly infinite) invocations of getContextualType.
66210         function isPossiblyDiscriminantValue(node) {
66211             switch (node.kind) {
66212                 case 10 /* StringLiteral */:
66213                 case 8 /* NumericLiteral */:
66214                 case 9 /* BigIntLiteral */:
66215                 case 14 /* NoSubstitutionTemplateLiteral */:
66216                 case 109 /* TrueKeyword */:
66217                 case 94 /* FalseKeyword */:
66218                 case 103 /* NullKeyword */:
66219                 case 78 /* Identifier */:
66220                 case 150 /* UndefinedKeyword */:
66221                     return true;
66222                 case 201 /* PropertyAccessExpression */:
66223                 case 207 /* ParenthesizedExpression */:
66224                     return isPossiblyDiscriminantValue(node.expression);
66225                 case 283 /* JsxExpression */:
66226                     return !node.expression || isPossiblyDiscriminantValue(node.expression);
66227             }
66228             return false;
66229         }
66230         function discriminateContextualTypeByObjectMembers(node, contextualType) {
66231             return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 288 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType);
66232         }
66233         function discriminateContextualTypeByJSXAttributes(node, contextualType) {
66234             return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 280 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer)); }), function (prop) { return [!prop.initializer ? (function () { return trueType; }) : (function () { return checkExpression(prop.initializer); }), prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType);
66235         }
66236         // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
66237         // be "pushed" onto a node using the contextualType property.
66238         function getApparentTypeOfContextualType(node, contextFlags) {
66239             var contextualType = ts.isObjectLiteralMethod(node) ?
66240                 getContextualTypeForObjectLiteralMethod(node, contextFlags) :
66241                 getContextualType(node, contextFlags);
66242             var instantiatedType = instantiateContextualType(contextualType, node, contextFlags);
66243             if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) {
66244                 var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true);
66245                 if (apparentType.flags & 1048576 /* Union */) {
66246                     if (ts.isObjectLiteralExpression(node)) {
66247                         return discriminateContextualTypeByObjectMembers(node, apparentType);
66248                     }
66249                     else if (ts.isJsxAttributes(node)) {
66250                         return discriminateContextualTypeByJSXAttributes(node, apparentType);
66251                     }
66252                 }
66253                 return apparentType;
66254             }
66255         }
66256         // If the given contextual type contains instantiable types and if a mapper representing
66257         // return type inferences is available, instantiate those types using that mapper.
66258         function instantiateContextualType(contextualType, node, contextFlags) {
66259             if (contextualType && maybeTypeOfKind(contextualType, 465829888 /* Instantiable */)) {
66260                 var inferenceContext = getInferenceContext(node);
66261                 // If no inferences have been made, nothing is gained from instantiating as type parameters
66262                 // would just be replaced with their defaults similar to the apparent type.
66263                 if (inferenceContext && ts.some(inferenceContext.inferences, hasInferenceCandidates)) {
66264                     // For contextual signatures we incorporate all inferences made so far, e.g. from return
66265                     // types as well as arguments to the left in a function call.
66266                     if (contextFlags && contextFlags & 1 /* Signature */) {
66267                         return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
66268                     }
66269                     // For other purposes (e.g. determining whether to produce literal types) we only
66270                     // incorporate inferences made from the return type in a function call.
66271                     if (inferenceContext.returnMapper) {
66272                         return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
66273                     }
66274                 }
66275             }
66276             return contextualType;
66277         }
66278         // This function is similar to instantiateType, except that (a) it only instantiates types that
66279         // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
66280         // no reductions on instantiated union types.
66281         function instantiateInstantiableTypes(type, mapper) {
66282             if (type.flags & 465829888 /* Instantiable */) {
66283                 return instantiateType(type, mapper);
66284             }
66285             if (type.flags & 1048576 /* Union */) {
66286                 return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
66287             }
66288             if (type.flags & 2097152 /* Intersection */) {
66289                 return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
66290             }
66291             return type;
66292         }
66293         /**
66294          * Whoa! Do you really want to use this function?
66295          *
66296          * Unless you're trying to get the *non-apparent* type for a
66297          * value-literal type or you're authoring relevant portions of this algorithm,
66298          * you probably meant to use 'getApparentTypeOfContextualType'.
66299          * Otherwise this may not be very useful.
66300          *
66301          * In cases where you *are* working on this function, you should understand
66302          * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'.
66303          *
66304          *   - Use 'getContextualType' when you are simply going to propagate the result to the expression.
66305          *   - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
66306          *
66307          * @param node the expression whose contextual type will be returned.
66308          * @returns the contextual type of an expression.
66309          */
66310         function getContextualType(node, contextFlags) {
66311             if (node.flags & 16777216 /* InWithStatement */) {
66312                 // We cannot answer semantic questions within a with block, do not proceed any further
66313                 return undefined;
66314             }
66315             if (node.contextualType) {
66316                 return node.contextualType;
66317             }
66318             var parent = node.parent;
66319             switch (parent.kind) {
66320                 case 249 /* VariableDeclaration */:
66321                 case 160 /* Parameter */:
66322                 case 163 /* PropertyDeclaration */:
66323                 case 162 /* PropertySignature */:
66324                 case 198 /* BindingElement */:
66325                     return getContextualTypeForInitializerExpression(node, contextFlags);
66326                 case 209 /* ArrowFunction */:
66327                 case 242 /* ReturnStatement */:
66328                     return getContextualTypeForReturnExpression(node);
66329                 case 219 /* YieldExpression */:
66330                     return getContextualTypeForYieldOperand(parent);
66331                 case 213 /* AwaitExpression */:
66332                     return getContextualTypeForAwaitOperand(parent, contextFlags);
66333                 case 203 /* CallExpression */:
66334                     if (parent.expression.kind === 99 /* ImportKeyword */) {
66335                         return stringType;
66336                     }
66337                 /* falls through */
66338                 case 204 /* NewExpression */:
66339                     return getContextualTypeForArgument(parent, node);
66340                 case 206 /* TypeAssertionExpression */:
66341                 case 224 /* AsExpression */:
66342                     return ts.isConstTypeReference(parent.type) ? tryFindWhenConstTypeReference(parent) : getTypeFromTypeNode(parent.type);
66343                 case 216 /* BinaryExpression */:
66344                     return getContextualTypeForBinaryOperand(node, contextFlags);
66345                 case 288 /* PropertyAssignment */:
66346                 case 289 /* ShorthandPropertyAssignment */:
66347                     return getContextualTypeForObjectLiteralElement(parent, contextFlags);
66348                 case 290 /* SpreadAssignment */:
66349                     return getApparentTypeOfContextualType(parent.parent, contextFlags);
66350                 case 199 /* ArrayLiteralExpression */: {
66351                     var arrayLiteral = parent;
66352                     var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags);
66353                     return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node));
66354                 }
66355                 case 217 /* ConditionalExpression */:
66356                     return getContextualTypeForConditionalOperand(node, contextFlags);
66357                 case 228 /* TemplateSpan */:
66358                     ts.Debug.assert(parent.parent.kind === 218 /* TemplateExpression */);
66359                     return getContextualTypeForSubstitutionExpression(parent.parent, node);
66360                 case 207 /* ParenthesizedExpression */: {
66361                     // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast.
66362                     var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined;
66363                     return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags);
66364                 }
66365                 case 225 /* NonNullExpression */:
66366                     return getContextualType(parent, contextFlags);
66367                 case 283 /* JsxExpression */:
66368                     return getContextualTypeForJsxExpression(parent);
66369                 case 280 /* JsxAttribute */:
66370                 case 282 /* JsxSpreadAttribute */:
66371                     return getContextualTypeForJsxAttribute(parent);
66372                 case 275 /* JsxOpeningElement */:
66373                 case 274 /* JsxSelfClosingElement */:
66374                     return getContextualJsxElementAttributesType(parent, contextFlags);
66375             }
66376             return undefined;
66377             function tryFindWhenConstTypeReference(node) {
66378                 return getContextualType(node);
66379             }
66380         }
66381         function getInferenceContext(node) {
66382             var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
66383             return ancestor && ancestor.inferenceContext;
66384         }
66385         function getContextualJsxElementAttributesType(node, contextFlags) {
66386             if (ts.isJsxOpeningElement(node) && node.parent.contextualType && contextFlags !== 4 /* Completions */) {
66387                 // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit
66388                 // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type
66389                 // (as below) instead!
66390                 return node.parent.contextualType;
66391             }
66392             return getContextualTypeForArgumentAtIndex(node, 0);
66393         }
66394         function getEffectiveFirstArgumentForJsxSignature(signature, node) {
66395             return getJsxReferenceKind(node) !== 0 /* Component */
66396                 ? getJsxPropsTypeFromCallSignature(signature, node)
66397                 : getJsxPropsTypeFromClassType(signature, node);
66398         }
66399         function getJsxPropsTypeFromCallSignature(sig, context) {
66400             var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType);
66401             propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
66402             var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
66403             if (intrinsicAttribs !== errorType) {
66404                 propsType = intersectTypes(intrinsicAttribs, propsType);
66405             }
66406             return propsType;
66407         }
66408         function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
66409             if (sig.unionSignatures) {
66410                 // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input
66411                 // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature,
66412                 // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur
66413                 // 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.
66414                 // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane.
66415                 var results = [];
66416                 for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) {
66417                     var signature = _a[_i];
66418                     var instance = getReturnTypeOfSignature(signature);
66419                     if (isTypeAny(instance)) {
66420                         return instance;
66421                     }
66422                     var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation);
66423                     if (!propType) {
66424                         return;
66425                     }
66426                     results.push(propType);
66427                 }
66428                 return getIntersectionType(results);
66429             }
66430             var instanceType = getReturnTypeOfSignature(sig);
66431             return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
66432         }
66433         function getStaticTypeOfReferencedJsxConstructor(context) {
66434             if (isJsxIntrinsicIdentifier(context.tagName)) {
66435                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context);
66436                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
66437                 return getOrCreateTypeFromSignature(fakeSignature);
66438             }
66439             var tagType = checkExpressionCached(context.tagName);
66440             if (tagType.flags & 128 /* StringLiteral */) {
66441                 var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context);
66442                 if (!result) {
66443                     return errorType;
66444                 }
66445                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
66446                 return getOrCreateTypeFromSignature(fakeSignature);
66447             }
66448             return tagType;
66449         }
66450         function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
66451             var managedSym = getJsxLibraryManagedAttributes(ns);
66452             if (managedSym) {
66453                 var declaredManagedType = getDeclaredTypeOfSymbol(managedSym); // fetches interface type, or initializes symbol links type parmaeters
66454                 var ctorType = getStaticTypeOfReferencedJsxConstructor(context);
66455                 if (managedSym.flags & 524288 /* TypeAlias */) {
66456                     var params = getSymbolLinks(managedSym).typeParameters;
66457                     if (ts.length(params) >= 2) {
66458                         var args = fillMissingTypeArguments([ctorType, attributesType], params, 2, ts.isInJSFile(context));
66459                         return getTypeAliasInstantiation(managedSym, args);
66460                     }
66461                 }
66462                 if (ts.length(declaredManagedType.typeParameters) >= 2) {
66463                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context));
66464                     return createTypeReference(declaredManagedType, args);
66465                 }
66466             }
66467             return attributesType;
66468         }
66469         function getJsxPropsTypeFromClassType(sig, context) {
66470             var ns = getJsxNamespaceAt(context);
66471             var forcedLookupLocation = getJsxElementPropertiesName(ns);
66472             var attributesType = forcedLookupLocation === undefined
66473                 // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type
66474                 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType)
66475                 : forcedLookupLocation === ""
66476                     // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
66477                     ? getReturnTypeOfSignature(sig)
66478                     // Otherwise get the type of the property on the signature return type
66479                     : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
66480             if (!attributesType) {
66481                 // There is no property named 'props' on this instance type
66482                 if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) {
66483                     error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation));
66484                 }
66485                 return unknownType;
66486             }
66487             attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
66488             if (isTypeAny(attributesType)) {
66489                 // Props is of type 'any' or unknown
66490                 return attributesType;
66491             }
66492             else {
66493                 // Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
66494                 var apparentAttributesType = attributesType;
66495                 var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
66496                 if (intrinsicClassAttribs !== errorType) {
66497                     var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
66498                     var hostClassType = getReturnTypeOfSignature(sig);
66499                     apparentAttributesType = intersectTypes(typeParams
66500                         ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context)))
66501                         : intrinsicClassAttribs, apparentAttributesType);
66502                 }
66503                 var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
66504                 if (intrinsicAttribs !== errorType) {
66505                     apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
66506                 }
66507                 return apparentAttributesType;
66508             }
66509         }
66510         // If the given type is an object or union type with a single signature, and if that signature has at
66511         // least as many parameters as the given function, return the signature. Otherwise return undefined.
66512         function getContextualCallSignature(type, node) {
66513             var signatures = getSignaturesOfType(type, 0 /* Call */);
66514             if (signatures.length === 1) {
66515                 var signature = signatures[0];
66516                 if (!isAritySmaller(signature, node)) {
66517                     return signature;
66518                 }
66519             }
66520         }
66521         /** If the contextual signature has fewer parameters than the function expression, do not use it */
66522         function isAritySmaller(signature, target) {
66523             var targetParameterCount = 0;
66524             for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
66525                 var param = target.parameters[targetParameterCount];
66526                 if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
66527                     break;
66528                 }
66529             }
66530             if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) {
66531                 targetParameterCount--;
66532             }
66533             return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
66534         }
66535         function isFunctionExpressionOrArrowFunction(node) {
66536             return node.kind === 208 /* FunctionExpression */ || node.kind === 209 /* ArrowFunction */;
66537         }
66538         function getContextualSignatureForFunctionLikeDeclaration(node) {
66539             // Only function expressions, arrow functions, and object literal methods are contextually typed.
66540             return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node)
66541                 ? getContextualSignature(node)
66542                 : undefined;
66543         }
66544         // Return the contextual signature for a given expression node. A contextual type provides a
66545         // contextual signature if it has a single call signature and if that call signature is non-generic.
66546         // If the contextual type is a union type, get the signature from each type possible and if they are
66547         // all identical ignoring their return type, the result is same signature but with return type as
66548         // union type of return types from these signatures
66549         function getContextualSignature(node) {
66550             ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
66551             var typeTagSignature = getSignatureOfTypeTag(node);
66552             if (typeTagSignature) {
66553                 return typeTagSignature;
66554             }
66555             var type = getApparentTypeOfContextualType(node, 1 /* Signature */);
66556             if (!type) {
66557                 return undefined;
66558             }
66559             if (!(type.flags & 1048576 /* Union */)) {
66560                 return getContextualCallSignature(type, node);
66561             }
66562             var signatureList;
66563             var types = type.types;
66564             for (var _i = 0, types_20 = types; _i < types_20.length; _i++) {
66565                 var current = types_20[_i];
66566                 var signature = getContextualCallSignature(current, node);
66567                 if (signature) {
66568                     if (!signatureList) {
66569                         // This signature will contribute to contextual union signature
66570                         signatureList = [signature];
66571                     }
66572                     else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
66573                         // Signatures aren't identical, do not use
66574                         return undefined;
66575                     }
66576                     else {
66577                         // Use this signature for contextual union signature
66578                         signatureList.push(signature);
66579                     }
66580                 }
66581             }
66582             // Result is union of signatures collected (return type is union of return types of this signature set)
66583             if (signatureList) {
66584                 return signatureList.length === 1 ? signatureList[0] : createUnionSignature(signatureList[0], signatureList);
66585             }
66586         }
66587         function checkSpreadExpression(node, checkMode) {
66588             if (languageVersion < 2 /* ES2015 */) {
66589                 checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */);
66590             }
66591             var arrayOrIterableType = checkExpression(node.expression, checkMode);
66592             return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression);
66593         }
66594         function checkSyntheticExpression(node) {
66595             return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type;
66596         }
66597         function hasDefaultValue(node) {
66598             return (node.kind === 198 /* BindingElement */ && !!node.initializer) ||
66599                 (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */);
66600         }
66601         function checkArrayLiteral(node, checkMode, forceTuple) {
66602             var elements = node.elements;
66603             var elementCount = elements.length;
66604             var elementTypes = [];
66605             var elementFlags = [];
66606             var contextualType = getApparentTypeOfContextualType(node);
66607             var inDestructuringPattern = ts.isAssignmentTarget(node);
66608             var inConstContext = isConstContext(node);
66609             for (var i = 0; i < elementCount; i++) {
66610                 var e = elements[i];
66611                 if (e.kind === 220 /* SpreadElement */) {
66612                     if (languageVersion < 2 /* ES2015 */) {
66613                         checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */);
66614                     }
66615                     var spreadType = checkExpression(e.expression, checkMode, forceTuple);
66616                     if (isArrayLikeType(spreadType)) {
66617                         elementTypes.push(spreadType);
66618                         elementFlags.push(8 /* Variadic */);
66619                     }
66620                     else if (inDestructuringPattern) {
66621                         // Given the following situation:
66622                         //    var c: {};
66623                         //    [...c] = ["", 0];
66624                         //
66625                         // c is represented in the tree as a spread element in an array literal.
66626                         // But c really functions as a rest element, and its purpose is to provide
66627                         // a contextual type for the right hand side of the assignment. Therefore,
66628                         // instead of calling checkExpression on "...c", which will give an error
66629                         // if c is not iterable/array-like, we need to act as if we are trying to
66630                         // get the contextual element type from it. So we do something similar to
66631                         // getContextualTypeForElementExpression, which will crucially not error
66632                         // if there is no index type / iterated type.
66633                         var restElementType = getIndexTypeOfType(spreadType, 1 /* Number */) ||
66634                             getIteratedTypeOrElementType(65 /* Destructuring */, spreadType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false) ||
66635                             unknownType;
66636                         elementTypes.push(restElementType);
66637                         elementFlags.push(4 /* Rest */);
66638                     }
66639                     else {
66640                         elementTypes.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, e.expression));
66641                         elementFlags.push(4 /* Rest */);
66642                     }
66643                 }
66644                 else {
66645                     var elementContextualType = getContextualTypeForElementExpression(contextualType, elementTypes.length);
66646                     var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple);
66647                     elementTypes.push(type);
66648                     elementFlags.push(1 /* Required */);
66649                 }
66650             }
66651             if (inDestructuringPattern) {
66652                 return createTupleType(elementTypes, elementFlags);
66653             }
66654             if (forceTuple || inConstContext || contextualType && forEachType(contextualType, isTupleLikeType)) {
66655                 return createArrayLiteralType(createTupleType(elementTypes, elementFlags, /*readonly*/ inConstContext));
66656             }
66657             return createArrayLiteralType(createArrayType(elementTypes.length ?
66658                 getUnionType(ts.sameMap(elementTypes, function (t, i) { return elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessTypeOrUndefined(t, numberType) || anyType : t; }), 2 /* Subtype */) :
66659                 strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext));
66660         }
66661         function createArrayLiteralType(type) {
66662             if (!(ts.getObjectFlags(type) & 4 /* Reference */)) {
66663                 return type;
66664             }
66665             var literalType = type.literalType;
66666             if (!literalType) {
66667                 literalType = type.literalType = cloneTypeReference(type);
66668                 literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
66669             }
66670             return literalType;
66671         }
66672         function isNumericName(name) {
66673             switch (name.kind) {
66674                 case 158 /* ComputedPropertyName */:
66675                     return isNumericComputedName(name);
66676                 case 78 /* Identifier */:
66677                     return isNumericLiteralName(name.escapedText);
66678                 case 8 /* NumericLiteral */:
66679                 case 10 /* StringLiteral */:
66680                     return isNumericLiteralName(name.text);
66681                 default:
66682                     return false;
66683             }
66684         }
66685         function isNumericComputedName(name) {
66686             // It seems odd to consider an expression of type Any to result in a numeric name,
66687             // but this behavior is consistent with checkIndexedAccess
66688             return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */);
66689         }
66690         function isInfinityOrNaNString(name) {
66691             return name === "Infinity" || name === "-Infinity" || name === "NaN";
66692         }
66693         function isNumericLiteralName(name) {
66694             // The intent of numeric names is that
66695             //     - they are names with text in a numeric form, and that
66696             //     - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
66697             //         acquired by applying the abstract 'ToNumber' operation on the name's text.
66698             //
66699             // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
66700             // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
66701             //
66702             // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
66703             // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
66704             // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
66705             // because their 'ToString' representation is not equal to their original text.
66706             // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
66707             //
66708             // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
66709             // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
66710             // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
66711             //
66712             // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
66713             // This is desired behavior, because when indexing with them as numeric entities, you are indexing
66714             // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
66715             return (+name).toString() === name;
66716         }
66717         function checkComputedPropertyName(node) {
66718             var links = getNodeLinks(node.expression);
66719             if (!links.resolvedType) {
66720                 links.resolvedType = checkExpression(node.expression);
66721                 // This will allow types number, string, symbol or any. It will also allow enums, the unknown
66722                 // type, and any union of these types (like string | number).
66723                 if (links.resolvedType.flags & 98304 /* Nullable */ ||
66724                     !isTypeAssignableToKind(links.resolvedType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) &&
66725                         !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
66726                     error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
66727                 }
66728                 else {
66729                     checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true);
66730                 }
66731             }
66732             return links.resolvedType;
66733         }
66734         function isSymbolWithNumericName(symbol) {
66735             var _a;
66736             var firstDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a[0];
66737             return isNumericLiteralName(symbol.escapedName) || (firstDecl && ts.isNamedDeclaration(firstDecl) && isNumericName(firstDecl.name));
66738         }
66739         function getObjectLiteralIndexInfo(node, offset, properties, kind) {
66740             var propTypes = [];
66741             for (var i = offset; i < properties.length; i++) {
66742                 if (kind === 0 /* String */ || isSymbolWithNumericName(properties[i])) {
66743                     propTypes.push(getTypeOfSymbol(properties[i]));
66744                 }
66745             }
66746             var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
66747             return createIndexInfo(unionType, isConstContext(node));
66748         }
66749         function getImmediateAliasedSymbol(symbol) {
66750             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
66751             var links = getSymbolLinks(symbol);
66752             if (!links.immediateTarget) {
66753                 var node = getDeclarationOfAliasSymbol(symbol);
66754                 if (!node)
66755                     return ts.Debug.fail();
66756                 links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
66757             }
66758             return links.immediateTarget;
66759         }
66760         function checkObjectLiteral(node, checkMode) {
66761             var inDestructuringPattern = ts.isAssignmentTarget(node);
66762             // Grammar checking
66763             checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
66764             var allPropertiesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
66765             var propertiesTable = ts.createSymbolTable();
66766             var propertiesArray = [];
66767             var spread = emptyObjectType;
66768             var contextualType = getApparentTypeOfContextualType(node);
66769             var contextualTypeHasPattern = contextualType && contextualType.pattern &&
66770                 (contextualType.pattern.kind === 196 /* ObjectBindingPattern */ || contextualType.pattern.kind === 200 /* ObjectLiteralExpression */);
66771             var inConstContext = isConstContext(node);
66772             var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
66773             var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
66774             var enumTag = ts.getJSDocEnumTag(node);
66775             var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
66776             var objectFlags = freshObjectLiteralFlag;
66777             var patternWithComputedProperties = false;
66778             var hasComputedStringProperty = false;
66779             var hasComputedNumberProperty = false;
66780             // Spreads may cause an early bail; ensure computed names are always checked (this is cached)
66781             // As otherwise they may not be checked until exports for the type at this position are retrieved,
66782             // which may never occur.
66783             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
66784                 var elem = _a[_i];
66785                 if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) {
66786                     checkComputedPropertyName(elem.name);
66787                 }
66788             }
66789             var offset = 0;
66790             for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
66791                 var memberDecl = _c[_b];
66792                 var member = getSymbolOfNode(memberDecl);
66793                 var computedNameType = memberDecl.name && memberDecl.name.kind === 158 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ?
66794                     checkComputedPropertyName(memberDecl.name) : undefined;
66795                 if (memberDecl.kind === 288 /* PropertyAssignment */ ||
66796                     memberDecl.kind === 289 /* ShorthandPropertyAssignment */ ||
66797                     ts.isObjectLiteralMethod(memberDecl)) {
66798                     var type = memberDecl.kind === 288 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) :
66799                         // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring
66800                         // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`.
66801                         // we don't want to say "could not find 'a'".
66802                         memberDecl.kind === 289 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) :
66803                             checkObjectLiteralMethod(memberDecl, checkMode);
66804                     if (isInJavascript) {
66805                         var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
66806                         if (jsDocType) {
66807                             checkTypeAssignableTo(type, jsDocType, memberDecl);
66808                             type = jsDocType;
66809                         }
66810                         else if (enumTag && enumTag.typeExpression) {
66811                             checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
66812                         }
66813                     }
66814                     objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */;
66815                     var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
66816                     var prop = nameType ?
66817                         createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) :
66818                         createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
66819                     if (nameType) {
66820                         prop.nameType = nameType;
66821                     }
66822                     if (inDestructuringPattern) {
66823                         // If object literal is an assignment pattern and if the assignment pattern specifies a default value
66824                         // for the property, make the property optional.
66825                         var isOptional = (memberDecl.kind === 288 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
66826                             (memberDecl.kind === 289 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
66827                         if (isOptional) {
66828                             prop.flags |= 16777216 /* Optional */;
66829                         }
66830                     }
66831                     else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
66832                         // If object literal is contextually typed by the implied type of a binding pattern, and if the
66833                         // binding pattern specifies a default value for the property, make the property optional.
66834                         var impliedProp = getPropertyOfType(contextualType, member.escapedName);
66835                         if (impliedProp) {
66836                             prop.flags |= impliedProp.flags & 16777216 /* Optional */;
66837                         }
66838                         else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) {
66839                             error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
66840                         }
66841                     }
66842                     prop.declarations = member.declarations;
66843                     prop.parent = member.parent;
66844                     if (member.valueDeclaration) {
66845                         prop.valueDeclaration = member.valueDeclaration;
66846                     }
66847                     prop.type = type;
66848                     prop.target = member;
66849                     member = prop;
66850                     allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop);
66851                 }
66852                 else if (memberDecl.kind === 290 /* SpreadAssignment */) {
66853                     if (languageVersion < 2 /* ES2015 */) {
66854                         checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
66855                     }
66856                     if (propertiesArray.length > 0) {
66857                         spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
66858                         propertiesArray = [];
66859                         propertiesTable = ts.createSymbolTable();
66860                         hasComputedStringProperty = false;
66861                         hasComputedNumberProperty = false;
66862                     }
66863                     var type = getReducedType(checkExpression(memberDecl.expression));
66864                     if (!isValidSpreadType(type)) {
66865                         error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
66866                         return errorType;
66867                     }
66868                     if (allPropertiesTable) {
66869                         checkSpreadPropOverrides(type, allPropertiesTable, memberDecl);
66870                     }
66871                     spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
66872                     offset = propertiesArray.length;
66873                     continue;
66874                 }
66875                 else {
66876                     // TypeScript 1.0 spec (April 2014)
66877                     // A get accessor declaration is processed in the same manner as
66878                     // an ordinary function declaration(section 6.1) with no parameters.
66879                     // A set accessor declaration is processed in the same manner
66880                     // as an ordinary function declaration with a single parameter and a Void return type.
66881                     ts.Debug.assert(memberDecl.kind === 167 /* GetAccessor */ || memberDecl.kind === 168 /* SetAccessor */);
66882                     checkNodeDeferred(memberDecl);
66883                 }
66884                 if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) {
66885                     if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
66886                         if (isTypeAssignableTo(computedNameType, numberType)) {
66887                             hasComputedNumberProperty = true;
66888                         }
66889                         else {
66890                             hasComputedStringProperty = true;
66891                         }
66892                         if (inDestructuringPattern) {
66893                             patternWithComputedProperties = true;
66894                         }
66895                     }
66896                 }
66897                 else {
66898                     propertiesTable.set(member.escapedName, member);
66899                 }
66900                 propertiesArray.push(member);
66901             }
66902             // If object literal is contextually typed by the implied type of a binding pattern, augment the result
66903             // type with those properties for which the binding pattern specifies a default value.
66904             // If the object literal is spread into another object literal, skip this step and let the top-level object
66905             // literal handle it instead.
66906             if (contextualTypeHasPattern && node.parent.kind !== 290 /* SpreadAssignment */) {
66907                 for (var _d = 0, _e = getPropertiesOfType(contextualType); _d < _e.length; _d++) {
66908                     var prop = _e[_d];
66909                     if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) {
66910                         if (!(prop.flags & 16777216 /* Optional */)) {
66911                             error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
66912                         }
66913                         propertiesTable.set(prop.escapedName, prop);
66914                         propertiesArray.push(prop);
66915                     }
66916                 }
66917             }
66918             if (spread !== emptyObjectType) {
66919                 if (propertiesArray.length > 0) {
66920                     spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
66921                     propertiesArray = [];
66922                     propertiesTable = ts.createSymbolTable();
66923                     hasComputedStringProperty = false;
66924                     hasComputedNumberProperty = false;
66925                 }
66926                 // remap the raw emptyObjectType fed in at the top into a fresh empty object literal type, unique to this use site
66927                 return mapType(spread, function (t) { return t === emptyObjectType ? createObjectLiteralType() : t; });
66928             }
66929             return createObjectLiteralType();
66930             function createObjectLiteralType() {
66931                 var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
66932                 var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
66933                 var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
66934                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
66935                 if (isJSObjectLiteral) {
66936                     result.objectFlags |= 16384 /* JSLiteral */;
66937                 }
66938                 if (patternWithComputedProperties) {
66939                     result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
66940                 }
66941                 if (inDestructuringPattern) {
66942                     result.pattern = node;
66943                 }
66944                 return result;
66945             }
66946         }
66947         function isValidSpreadType(type) {
66948             if (type.flags & 465829888 /* Instantiable */) {
66949                 var constraint = getBaseConstraintOfType(type);
66950                 if (constraint !== undefined) {
66951                     return isValidSpreadType(constraint);
66952                 }
66953             }
66954             return !!(type.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ||
66955                 getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) ||
66956                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType));
66957         }
66958         function checkJsxSelfClosingElementDeferred(node) {
66959             checkJsxOpeningLikeElementOrOpeningFragment(node);
66960         }
66961         function checkJsxSelfClosingElement(node, _checkMode) {
66962             checkNodeDeferred(node);
66963             return getJsxElementTypeAt(node) || anyType;
66964         }
66965         function checkJsxElementDeferred(node) {
66966             // Check attributes
66967             checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
66968             // Perform resolution on the closing tag so that rename/go to definition/etc work
66969             if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) {
66970                 getIntrinsicTagSymbol(node.closingElement);
66971             }
66972             else {
66973                 checkExpression(node.closingElement.tagName);
66974             }
66975             checkJsxChildren(node);
66976         }
66977         function checkJsxElement(node, _checkMode) {
66978             checkNodeDeferred(node);
66979             return getJsxElementTypeAt(node) || anyType;
66980         }
66981         function checkJsxFragment(node) {
66982             checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
66983             // by default, jsx:'react' will use jsxFactory = React.createElement and jsxFragmentFactory = React.Fragment
66984             // if jsxFactory compiler option is provided, ensure jsxFragmentFactory compiler option or @jsxFrag pragma is provided too
66985             var nodeSourceFile = ts.getSourceFileOfNode(node);
66986             if (ts.getJSXTransformEnabled(compilerOptions) && (compilerOptions.jsxFactory || nodeSourceFile.pragmas.has("jsx"))
66987                 && !compilerOptions.jsxFragmentFactory && !nodeSourceFile.pragmas.has("jsxfrag")) {
66988                 error(node, compilerOptions.jsxFactory
66989                     ? ts.Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option
66990                     : ts.Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments);
66991             }
66992             checkJsxChildren(node);
66993             return getJsxElementTypeAt(node) || anyType;
66994         }
66995         function isUnhyphenatedJsxName(name) {
66996             return !ts.stringContains(name, "-");
66997         }
66998         /**
66999          * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name
67000          */
67001         function isJsxIntrinsicIdentifier(tagName) {
67002             return tagName.kind === 78 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText);
67003         }
67004         function checkJsxAttribute(node, checkMode) {
67005             return node.initializer
67006                 ? checkExpressionForMutableLocation(node.initializer, checkMode)
67007                 : trueType; // <Elem attr /> is sugar for <Elem attr={true} />
67008         }
67009         /**
67010          * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element.
67011          *
67012          * @param openingLikeElement a JSX opening-like element
67013          * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable
67014          * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property.
67015          * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral,
67016          * which also calls getSpreadType.
67017          */
67018         function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) {
67019             var attributes = openingLikeElement.attributes;
67020             var allAttributesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
67021             var attributesTable = ts.createSymbolTable();
67022             var spread = emptyJsxObjectType;
67023             var hasSpreadAnyType = false;
67024             var typeToIntersect;
67025             var explicitlySpecifyChildrenAttribute = false;
67026             var objectFlags = 4096 /* JsxAttributes */;
67027             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
67028             for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
67029                 var attributeDecl = _a[_i];
67030                 var member = attributeDecl.symbol;
67031                 if (ts.isJsxAttribute(attributeDecl)) {
67032                     var exprType = checkJsxAttribute(attributeDecl, checkMode);
67033                     objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */;
67034                     var attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName);
67035                     attributeSymbol.declarations = member.declarations;
67036                     attributeSymbol.parent = member.parent;
67037                     if (member.valueDeclaration) {
67038                         attributeSymbol.valueDeclaration = member.valueDeclaration;
67039                     }
67040                     attributeSymbol.type = exprType;
67041                     attributeSymbol.target = member;
67042                     attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
67043                     allAttributesTable === null || allAttributesTable === void 0 ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol);
67044                     if (attributeDecl.name.escapedText === jsxChildrenPropertyName) {
67045                         explicitlySpecifyChildrenAttribute = true;
67046                     }
67047                 }
67048                 else {
67049                     ts.Debug.assert(attributeDecl.kind === 282 /* JsxSpreadAttribute */);
67050                     if (attributesTable.size > 0) {
67051                         spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
67052                         attributesTable = ts.createSymbolTable();
67053                     }
67054                     var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode));
67055                     if (isTypeAny(exprType)) {
67056                         hasSpreadAnyType = true;
67057                     }
67058                     if (isValidSpreadType(exprType)) {
67059                         spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
67060                         if (allAttributesTable) {
67061                             checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl);
67062                         }
67063                     }
67064                     else {
67065                         typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
67066                     }
67067                 }
67068             }
67069             if (!hasSpreadAnyType) {
67070                 if (attributesTable.size > 0) {
67071                     spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
67072                 }
67073             }
67074             // Handle children attribute
67075             var parent = openingLikeElement.parent.kind === 273 /* JsxElement */ ? openingLikeElement.parent : undefined;
67076             // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement
67077             if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) {
67078                 var childrenTypes = checkJsxChildren(parent, checkMode);
67079                 if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
67080                     // Error if there is a attribute named "children" explicitly specified and children element.
67081                     // This is because children element will overwrite the value from attributes.
67082                     // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread.
67083                     if (explicitlySpecifyChildrenAttribute) {
67084                         error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName));
67085                     }
67086                     var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes);
67087                     var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName);
67088                     // 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
67089                     var childrenPropSymbol = createSymbol(4 /* Property */, jsxChildrenPropertyName);
67090                     childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] :
67091                         childrenContextualType && forEachType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) :
67092                             createArrayType(getUnionType(childrenTypes));
67093                     // Fake up a property declaration for the children
67094                     childrenPropSymbol.valueDeclaration = ts.factory.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined);
67095                     ts.setParent(childrenPropSymbol.valueDeclaration, attributes);
67096                     childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
67097                     var childPropMap = ts.createSymbolTable();
67098                     childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
67099                     spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
67100                 }
67101             }
67102             if (hasSpreadAnyType) {
67103                 return anyType;
67104             }
67105             if (typeToIntersect && spread !== emptyJsxObjectType) {
67106                 return getIntersectionType([typeToIntersect, spread]);
67107             }
67108             return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread);
67109             /**
67110              * Create anonymous type from given attributes symbol table.
67111              * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable
67112              * @param attributesTable a symbol table of attributes property
67113              */
67114             function createJsxAttributesType() {
67115                 objectFlags |= freshObjectLiteralFlag;
67116                 var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
67117                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
67118                 return result;
67119             }
67120         }
67121         function checkJsxChildren(node, checkMode) {
67122             var childrenTypes = [];
67123             for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
67124                 var child = _a[_i];
67125                 // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
67126                 // because then type of children property will have constituent of string type.
67127                 if (child.kind === 11 /* JsxText */) {
67128                     if (!child.containsOnlyTriviaWhiteSpaces) {
67129                         childrenTypes.push(stringType);
67130                     }
67131                 }
67132                 else if (child.kind === 283 /* JsxExpression */ && !child.expression) {
67133                     continue; // empty jsx expressions don't *really* count as present children
67134                 }
67135                 else {
67136                     childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
67137                 }
67138             }
67139             return childrenTypes;
67140         }
67141         function checkSpreadPropOverrides(type, props, spread) {
67142             for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
67143                 var right = _a[_i];
67144                 var left = props.get(right.escapedName);
67145                 var rightType = getTypeOfSymbol(right);
67146                 if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 3 /* AnyOrUnknown */) && right.flags & 16777216 /* Optional */)) {
67147                     var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName));
67148                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property));
67149                 }
67150             }
67151         }
67152         /**
67153          * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element.
67154          * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used)
67155          * @param node a JSXAttributes to be resolved of its type
67156          */
67157         function checkJsxAttributes(node, checkMode) {
67158             return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
67159         }
67160         function getJsxType(name, location) {
67161             var namespace = getJsxNamespaceAt(location);
67162             var exports = namespace && getExportsOfSymbol(namespace);
67163             var typeSymbol = exports && getSymbol(exports, name, 788968 /* Type */);
67164             return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
67165         }
67166         /**
67167          * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
67168          * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
67169          * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
67170          * May also return unknownSymbol if both of these lookups fail.
67171          */
67172         function getIntrinsicTagSymbol(node) {
67173             var links = getNodeLinks(node);
67174             if (!links.resolvedSymbol) {
67175                 var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
67176                 if (intrinsicElementsType !== errorType) {
67177                     // Property case
67178                     if (!ts.isIdentifier(node.tagName))
67179                         return ts.Debug.fail();
67180                     var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
67181                     if (intrinsicProp) {
67182                         links.jsxFlags |= 1 /* IntrinsicNamedElement */;
67183                         return links.resolvedSymbol = intrinsicProp;
67184                     }
67185                     // Intrinsic string indexer case
67186                     var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
67187                     if (indexSignatureType) {
67188                         links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
67189                         return links.resolvedSymbol = intrinsicElementsType.symbol;
67190                     }
67191                     // Wasn't found
67192                     error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements);
67193                     return links.resolvedSymbol = unknownSymbol;
67194                 }
67195                 else {
67196                     if (noImplicitAny) {
67197                         error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
67198                     }
67199                     return links.resolvedSymbol = unknownSymbol;
67200                 }
67201             }
67202             return links.resolvedSymbol;
67203         }
67204         function getJsxNamespaceContainerForImplicitImport(location) {
67205             var file = location && ts.getSourceFileOfNode(location);
67206             var links = file && getNodeLinks(file);
67207             if (links && links.jsxImplicitImportContainer === false) {
67208                 return undefined;
67209             }
67210             if (links && links.jsxImplicitImportContainer) {
67211                 return links.jsxImplicitImportContainer;
67212             }
67213             var runtimeImportSpecifier = ts.getJSXRuntimeImport(ts.getJSXImplicitImportBase(compilerOptions, file), compilerOptions);
67214             if (!runtimeImportSpecifier) {
67215                 return undefined;
67216             }
67217             var isClassic = ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.Classic;
67218             var errorMessage = isClassic
67219                 ? ts.Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option
67220                 : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations;
67221             var mod = resolveExternalModule(location, runtimeImportSpecifier, errorMessage, location);
67222             var result = mod && mod !== unknownSymbol ? getMergedSymbol(resolveSymbol(mod)) : undefined;
67223             if (links) {
67224                 links.jsxImplicitImportContainer = result || false;
67225             }
67226             return result;
67227         }
67228         function getJsxNamespaceAt(location) {
67229             var links = location && getNodeLinks(location);
67230             if (links && links.jsxNamespace) {
67231                 return links.jsxNamespace;
67232             }
67233             if (!links || links.jsxNamespace !== false) {
67234                 var resolvedNamespace = getJsxNamespaceContainerForImplicitImport(location);
67235                 if (!resolvedNamespace || resolvedNamespace === unknownSymbol) {
67236                     var namespaceName = getJsxNamespace(location);
67237                     resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
67238                 }
67239                 if (resolvedNamespace) {
67240                     var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
67241                     if (candidate && candidate !== unknownSymbol) {
67242                         if (links) {
67243                             links.jsxNamespace = candidate;
67244                         }
67245                         return candidate;
67246                     }
67247                 }
67248                 if (links) {
67249                     links.jsxNamespace = false;
67250                 }
67251             }
67252             // JSX global fallback
67253             var s = resolveSymbol(getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined));
67254             if (s === unknownSymbol) {
67255                 return undefined; // TODO: GH#18217
67256             }
67257             return s; // TODO: GH#18217
67258         }
67259         /**
67260          * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
67261          * Get a single property from that container if existed. Report an error if there are more than one property.
67262          *
67263          * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
67264          *          if other string is given or the container doesn't exist, return undefined.
67265          */
67266         function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
67267             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
67268             var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 788968 /* Type */);
67269             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
67270             var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
67271             // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute
67272             var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
67273             if (propertiesOfJsxElementAttribPropInterface) {
67274                 // Element Attributes has zero properties, so the element attributes type will be the class instance type
67275                 if (propertiesOfJsxElementAttribPropInterface.length === 0) {
67276                     return "";
67277                 }
67278                 // Element Attributes has one property, so the element attributes type will be the type of the corresponding
67279                 // property of the class instance type
67280                 else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
67281                     return propertiesOfJsxElementAttribPropInterface[0].escapedName;
67282                 }
67283                 else if (propertiesOfJsxElementAttribPropInterface.length > 1) {
67284                     // More than one property on ElementAttributesProperty is an error
67285                     error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer));
67286                 }
67287             }
67288             return undefined;
67289         }
67290         function getJsxLibraryManagedAttributes(jsxNamespace) {
67291             // JSX.LibraryManagedAttributes [symbol]
67292             return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */);
67293         }
67294         /// e.g. "props" for React.d.ts,
67295         /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all
67296         ///     non-intrinsic elements' attributes type is 'any'),
67297         /// or '' if it has 0 properties (which means every
67298         ///     non-intrinsic elements' attributes type is the element instance type)
67299         function getJsxElementPropertiesName(jsxNamespace) {
67300             return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
67301         }
67302         function getJsxElementChildrenPropertyName(jsxNamespace) {
67303             return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
67304         }
67305         function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
67306             if (elementType.flags & 4 /* String */) {
67307                 return [anySignature];
67308             }
67309             else if (elementType.flags & 128 /* StringLiteral */) {
67310                 var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
67311                 if (!intrinsicType) {
67312                     error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
67313                     return ts.emptyArray;
67314                 }
67315                 else {
67316                     var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
67317                     return [fakeSignature];
67318                 }
67319             }
67320             var apparentElemType = getApparentType(elementType);
67321             // Resolve the signatures, preferring constructor
67322             var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
67323             if (signatures.length === 0) {
67324                 // No construct signatures, try call signatures
67325                 signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
67326             }
67327             if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
67328                 // If each member has some combination of new/call signatures; make a union signature list for those
67329                 signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
67330             }
67331             return signatures;
67332         }
67333         function getIntrinsicAttributesTypeFromStringLiteralType(type, location) {
67334             // 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
67335             // For example:
67336             //      var CustomTag: "h1" = "h1";
67337             //      <CustomTag> Hello World </CustomTag>
67338             var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location);
67339             if (intrinsicElementsType !== errorType) {
67340                 var stringLiteralTypeName = type.value;
67341                 var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
67342                 if (intrinsicProp) {
67343                     return getTypeOfSymbol(intrinsicProp);
67344                 }
67345                 var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
67346                 if (indexSignatureType) {
67347                     return indexSignatureType;
67348                 }
67349                 return undefined;
67350             }
67351             // If we need to report an error, we already done so here. So just return any to prevent any more error downstream
67352             return anyType;
67353         }
67354         function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) {
67355             if (refKind === 1 /* Function */) {
67356                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
67357                 if (sfcReturnConstraint) {
67358                     checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
67359                 }
67360             }
67361             else if (refKind === 0 /* Component */) {
67362                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
67363                 if (classConstraint) {
67364                     // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that
67365                     checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
67366                 }
67367             }
67368             else { // Mixed
67369                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
67370                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
67371                 if (!sfcReturnConstraint || !classConstraint) {
67372                     return;
67373                 }
67374                 var combined = getUnionType([sfcReturnConstraint, classConstraint]);
67375                 checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
67376             }
67377             function generateInitialErrorChain() {
67378                 var componentName = ts.getTextOfNode(openingLikeElement.tagName);
67379                 return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName);
67380             }
67381         }
67382         /**
67383          * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
67384          * The function is intended to be called from a function which has checked that the opening element is an intrinsic element.
67385          * @param node an intrinsic JSX opening-like element
67386          */
67387         function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
67388             ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
67389             var links = getNodeLinks(node);
67390             if (!links.resolvedJsxElementAttributesType) {
67391                 var symbol = getIntrinsicTagSymbol(node);
67392                 if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
67393                     return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol);
67394                 }
67395                 else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
67396                     return links.resolvedJsxElementAttributesType =
67397                         getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */);
67398                 }
67399                 else {
67400                     return links.resolvedJsxElementAttributesType = errorType;
67401                 }
67402             }
67403             return links.resolvedJsxElementAttributesType;
67404         }
67405         function getJsxElementClassTypeAt(location) {
67406             var type = getJsxType(JsxNames.ElementClass, location);
67407             if (type === errorType)
67408                 return undefined;
67409             return type;
67410         }
67411         function getJsxElementTypeAt(location) {
67412             return getJsxType(JsxNames.Element, location);
67413         }
67414         function getJsxStatelessElementTypeAt(location) {
67415             var jsxElementType = getJsxElementTypeAt(location);
67416             if (jsxElementType) {
67417                 return getUnionType([jsxElementType, nullType]);
67418             }
67419         }
67420         /**
67421          * Returns all the properties of the Jsx.IntrinsicElements interface
67422          */
67423         function getJsxIntrinsicTagNamesAt(location) {
67424             var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
67425             return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
67426         }
67427         function checkJsxPreconditions(errorNode) {
67428             // Preconditions for using JSX
67429             if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
67430                 error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
67431             }
67432             if (getJsxElementTypeAt(errorNode) === undefined) {
67433                 if (noImplicitAny) {
67434                     error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
67435                 }
67436             }
67437         }
67438         function checkJsxOpeningLikeElementOrOpeningFragment(node) {
67439             var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node);
67440             if (isNodeOpeningLikeElement) {
67441                 checkGrammarJsxElement(node);
67442             }
67443             checkJsxPreconditions(node);
67444             if (!getJsxNamespaceContainerForImplicitImport(node)) {
67445                 // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
67446                 // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
67447                 var jsxFactoryRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
67448                 var jsxFactoryNamespace = getJsxNamespace(node);
67449                 var jsxFactoryLocation = isNodeOpeningLikeElement ? node.tagName : node;
67450                 // allow null as jsxFragmentFactory
67451                 var jsxFactorySym = void 0;
67452                 if (!(ts.isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) {
67453                     jsxFactorySym = resolveName(jsxFactoryLocation, jsxFactoryNamespace, 111551 /* Value */, jsxFactoryRefErr, jsxFactoryNamespace, /*isUse*/ true);
67454                 }
67455                 if (jsxFactorySym) {
67456                     // Mark local symbol as referenced here because it might not have been marked
67457                     // if jsx emit was not jsxFactory as there wont be error being emitted
67458                     jsxFactorySym.isReferenced = 67108863 /* All */;
67459                     // If react/jsxFactory symbol is alias, mark it as refereced
67460                     if (jsxFactorySym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(jsxFactorySym)) {
67461                         markAliasSymbolAsReferenced(jsxFactorySym);
67462                     }
67463                 }
67464             }
67465             if (isNodeOpeningLikeElement) {
67466                 var jsxOpeningLikeNode = node;
67467                 var sig = getResolvedSignature(jsxOpeningLikeNode);
67468                 checkDeprecatedSignature(sig, node);
67469                 checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode);
67470             }
67471         }
67472         /**
67473          * Check if a property with the given name is known anywhere in the given type. In an object type, a property
67474          * is considered known if
67475          * 1. the object type is empty and the check is for assignability, or
67476          * 2. if the object type has index signatures, or
67477          * 3. if the property is actually declared in the object type
67478          *    (this means that 'toString', for example, is not usually a known property).
67479          * 4. In a union or intersection type,
67480          *    a property is considered known if it is known in any constituent type.
67481          * @param targetType a type to search a given name in
67482          * @param name a property name to search
67483          * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType
67484          */
67485         function isKnownProperty(targetType, name, isComparingJsxAttributes) {
67486             if (targetType.flags & 524288 /* Object */) {
67487                 var resolved = resolveStructuredTypeMembers(targetType);
67488                 if (resolved.stringIndexInfo ||
67489                     resolved.numberIndexInfo && isNumericLiteralName(name) ||
67490                     getPropertyOfObjectType(targetType, name) ||
67491                     isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) {
67492                     // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
67493                     return true;
67494                 }
67495             }
67496             else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) {
67497                 for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) {
67498                     var t = _a[_i];
67499                     if (isKnownProperty(t, name, isComparingJsxAttributes)) {
67500                         return true;
67501                     }
67502                 }
67503             }
67504             return false;
67505         }
67506         function isExcessPropertyCheckTarget(type) {
67507             return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) ||
67508                 type.flags & 67108864 /* NonPrimitive */ ||
67509                 type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) ||
67510                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget));
67511         }
67512         function checkJsxExpression(node, checkMode) {
67513             checkGrammarJsxExpression(node);
67514             if (node.expression) {
67515                 var type = checkExpression(node.expression, checkMode);
67516                 if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
67517                     error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type);
67518                 }
67519                 return type;
67520             }
67521             else {
67522                 return errorType;
67523             }
67524         }
67525         function getDeclarationNodeFlagsFromSymbol(s) {
67526             return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0;
67527         }
67528         /**
67529          * Return whether this symbol is a member of a prototype somewhere
67530          * Note that this is not tracked well within the compiler, so the answer may be incorrect.
67531          */
67532         function isPrototypeProperty(symbol) {
67533             if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
67534                 return true;
67535             }
67536             if (ts.isInJSFile(symbol.valueDeclaration)) {
67537                 var parent = symbol.valueDeclaration.parent;
67538                 return parent && ts.isBinaryExpression(parent) &&
67539                     ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */;
67540             }
67541         }
67542         /**
67543          * Check whether the requested property access is valid.
67544          * Returns true if node is a valid property access, and false otherwise.
67545          * @param node The node to be checked.
67546          * @param isSuper True if the access is from `super.`.
67547          * @param type The type of the object whose property is being accessed. (Not the type of the property.)
67548          * @param prop The symbol for the property being accessed.
67549          */
67550         function checkPropertyAccessibility(node, isSuper, type, prop) {
67551             var flags = ts.getDeclarationModifierFlagsFromSymbol(prop);
67552             var errorNode = node.kind === 157 /* QualifiedName */ ? node.right : node.kind === 195 /* ImportType */ ? node : node.name;
67553             if (isSuper) {
67554                 // TS 1.0 spec (April 2014): 4.8.2
67555                 // - In a constructor, instance member function, instance member accessor, or
67556                 //   instance member variable initializer where this references a derived class instance,
67557                 //   a super property access is permitted and must specify a public instance member function of the base class.
67558                 // - In a static member function or static member accessor
67559                 //   where this references the constructor function object of a derived class,
67560                 //   a super property access is permitted and must specify a public static member function of the base class.
67561                 if (languageVersion < 2 /* ES2015 */) {
67562                     if (symbolHasNonMethodDeclaration(prop)) {
67563                         error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
67564                         return false;
67565                     }
67566                 }
67567                 if (flags & 128 /* Abstract */) {
67568                     // A method cannot be accessed in a super property access if the method is abstract.
67569                     // This error could mask a private property access error. But, a member
67570                     // cannot simultaneously be private and abstract, so this will trigger an
67571                     // additional error elsewhere.
67572                     error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
67573                     return false;
67574                 }
67575             }
67576             // Referencing abstract properties within their own constructors is not allowed
67577             if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) {
67578                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
67579                 if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) {
67580                     error(errorNode, ts.Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), ts.getTextOfIdentifierOrLiteral(declaringClassDeclaration.name)); // TODO: GH#18217
67581                     return false;
67582                 }
67583             }
67584             if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) {
67585                 if (!ts.getContainingClass(node)) {
67586                     error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
67587                     return false;
67588                 }
67589                 return true;
67590             }
67591             // Public properties are otherwise accessible.
67592             if (!(flags & 24 /* NonPublicAccessibilityModifier */)) {
67593                 return true;
67594             }
67595             // Property is known to be private or protected at this point
67596             // Private property is accessible if the property is within the declaring class
67597             if (flags & 8 /* Private */) {
67598                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
67599                 if (!isNodeWithinClass(node, declaringClassDeclaration)) {
67600                     error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
67601                     return false;
67602                 }
67603                 return true;
67604             }
67605             // Property is known to be protected at this point
67606             // All protected properties of a supertype are accessible in a super access
67607             if (isSuper) {
67608                 return true;
67609             }
67610             // Find the first enclosing class that has the declaring classes of the protected constituents
67611             // of the property as base classes
67612             var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) {
67613                 var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
67614                 return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
67615             });
67616             // A protected property is accessible if the property is within the declaring class or classes derived from it
67617             if (!enclosingClass) {
67618                 // allow PropertyAccessibility if context is in function with this parameter
67619                 // static member access is disallow
67620                 var thisParameter = void 0;
67621                 if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) {
67622                     error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
67623                     return false;
67624                 }
67625                 var thisType = getTypeFromTypeNode(thisParameter.type);
67626                 enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType).target;
67627             }
67628             // No further restrictions for static properties
67629             if (flags & 32 /* Static */) {
67630                 return true;
67631             }
67632             if (type.flags & 262144 /* TypeParameter */) {
67633                 // get the original type -- represented as the type constraint of the 'this' type
67634                 type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined
67635             }
67636             if (!type || !hasBaseType(type, enclosingClass)) {
67637                 error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
67638                 return false;
67639             }
67640             return true;
67641         }
67642         function getThisParameterFromNodeContext(node) {
67643             var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false);
67644             return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined;
67645         }
67646         function symbolHasNonMethodDeclaration(symbol) {
67647             return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); });
67648         }
67649         function checkNonNullExpression(node) {
67650             return checkNonNullType(checkExpression(node), node);
67651         }
67652         function isNullableType(type) {
67653             return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */);
67654         }
67655         function getNonNullableTypeIfNeeded(type) {
67656             return isNullableType(type) ? getNonNullableType(type) : type;
67657         }
67658         function reportObjectPossiblyNullOrUndefinedError(node, flags) {
67659             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
67660                 ts.Diagnostics.Object_is_possibly_null_or_undefined :
67661                 ts.Diagnostics.Object_is_possibly_undefined :
67662                 ts.Diagnostics.Object_is_possibly_null);
67663         }
67664         function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) {
67665             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
67666                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined :
67667                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined :
67668                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null);
67669         }
67670         function checkNonNullTypeWithReporter(type, node, reportError) {
67671             if (strictNullChecks && type.flags & 2 /* Unknown */) {
67672                 error(node, ts.Diagnostics.Object_is_of_type_unknown);
67673                 return errorType;
67674             }
67675             var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */;
67676             if (kind) {
67677                 reportError(node, kind);
67678                 var t = getNonNullableType(type);
67679                 return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t;
67680             }
67681             return type;
67682         }
67683         function checkNonNullType(type, node) {
67684             return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError);
67685         }
67686         function checkNonNullNonVoidType(type, node) {
67687             var nonNullType = checkNonNullType(type, node);
67688             if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) {
67689                 error(node, ts.Diagnostics.Object_is_possibly_undefined);
67690             }
67691             return nonNullType;
67692         }
67693         function checkPropertyAccessExpression(node) {
67694             return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) :
67695                 checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name);
67696         }
67697         function checkPropertyAccessChain(node) {
67698             var leftType = checkExpression(node.expression);
67699             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
67700             return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType);
67701         }
67702         function checkQualifiedName(node) {
67703             return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right);
67704         }
67705         function isMethodAccessForCall(node) {
67706             while (node.parent.kind === 207 /* ParenthesizedExpression */) {
67707                 node = node.parent;
67708             }
67709             return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node;
67710         }
67711         // Lookup the private identifier lexically.
67712         function lookupSymbolForPrivateIdentifierDeclaration(propName, location) {
67713             for (var containingClass = ts.getContainingClass(location); !!containingClass; containingClass = ts.getContainingClass(containingClass)) {
67714                 var symbol = containingClass.symbol;
67715                 var name = ts.getSymbolNameForPrivateIdentifier(symbol, propName);
67716                 var prop = (symbol.members && symbol.members.get(name)) || (symbol.exports && symbol.exports.get(name));
67717                 if (prop) {
67718                     return prop;
67719                 }
67720             }
67721         }
67722         function getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) {
67723             return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
67724         }
67725         function checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedIdentifier) {
67726             // Either the identifier could not be looked up in the lexical scope OR the lexically scoped identifier did not exist on the type.
67727             // Find a private identifier with the same description on the type.
67728             var propertyOnType;
67729             var properties = getPropertiesOfType(leftType);
67730             if (properties) {
67731                 ts.forEach(properties, function (symbol) {
67732                     var decl = symbol.valueDeclaration;
67733                     if (decl && ts.isNamedDeclaration(decl) && ts.isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) {
67734                         propertyOnType = symbol;
67735                         return true;
67736                     }
67737                 });
67738             }
67739             var diagName = diagnosticName(right);
67740             if (propertyOnType) {
67741                 var typeValueDecl = propertyOnType.valueDeclaration;
67742                 var typeClass_1 = ts.getContainingClass(typeValueDecl);
67743                 ts.Debug.assert(!!typeClass_1);
67744                 // We found a private identifier property with the same description.
67745                 // Either:
67746                 // - There is a lexically scoped private identifier AND it shadows the one we found on the type.
67747                 // - It is an attempt to access the private identifier outside of the class.
67748                 if (lexicallyScopedIdentifier) {
67749                     var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration;
67750                     var lexicalClass = ts.getContainingClass(lexicalValueDecl);
67751                     ts.Debug.assert(!!lexicalClass);
67752                     if (ts.findAncestor(lexicalClass, function (n) { return typeClass_1 === n; })) {
67753                         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));
67754                         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));
67755                         return true;
67756                     }
67757                 }
67758                 error(right, ts.Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, diagnosticName(typeClass_1.name || anon));
67759                 return true;
67760             }
67761             return false;
67762         }
67763         function isThisPropertyAccessInConstructor(node, prop) {
67764             return (isConstructorDeclaredProperty(prop) || ts.isThisProperty(node) && isAutoTypedProperty(prop))
67765                 && ts.getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop);
67766         }
67767         function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) {
67768             var parentSymbol = getNodeLinks(left).resolvedSymbol;
67769             var assignmentKind = ts.getAssignmentTargetKind(node);
67770             var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType);
67771             if (ts.isPrivateIdentifier(right)) {
67772                 checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */);
67773             }
67774             var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType;
67775             var prop;
67776             if (ts.isPrivateIdentifier(right)) {
67777                 var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
67778                 if (isAnyLike) {
67779                     if (lexicallyScopedSymbol) {
67780                         return apparentType;
67781                     }
67782                     if (!ts.getContainingClass(right)) {
67783                         grammarErrorOnNode(right, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
67784                         return anyType;
67785                     }
67786                 }
67787                 prop = lexicallyScopedSymbol ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol) : undefined;
67788                 // Check for private-identifier-specific shadowing and lexical-scoping errors.
67789                 if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) {
67790                     return errorType;
67791                 }
67792             }
67793             else {
67794                 if (isAnyLike) {
67795                     if (ts.isIdentifier(left) && parentSymbol) {
67796                         markAliasReferenced(parentSymbol, node);
67797                     }
67798                     return apparentType;
67799                 }
67800                 prop = getPropertyOfType(apparentType, right.escapedText);
67801             }
67802             // In `Foo.Bar.Baz`, 'Foo' is not referenced if 'Bar' is a const enum or a module containing only const enums.
67803             // The exceptions are:
67804             //   1. if 'isolatedModules' is enabled, because the const enum value will not be inlined, and
67805             //   2. if 'preserveConstEnums' is enabled and the expression is itself an export, e.g. `export = Foo.Bar.Baz`.
67806             if (ts.isIdentifier(left) && parentSymbol && (compilerOptions.isolatedModules || !(prop && isConstEnumOrConstEnumOnlyModule(prop)) || ts.shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(node))) {
67807                 markAliasReferenced(parentSymbol, node);
67808             }
67809             var propType;
67810             if (!prop) {
67811                 var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getIndexInfoOfType(apparentType, 0 /* String */) : undefined;
67812                 if (!(indexInfo && indexInfo.type)) {
67813                     if (isJSLiteralType(leftType)) {
67814                         return anyType;
67815                     }
67816                     if (leftType.symbol === globalThisSymbol) {
67817                         if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
67818                             error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
67819                         }
67820                         else if (noImplicitAny) {
67821                             error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
67822                         }
67823                         return anyType;
67824                     }
67825                     if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
67826                         reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType);
67827                     }
67828                     return errorType;
67829                 }
67830                 if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) {
67831                     error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
67832                 }
67833                 propType = (compilerOptions.noUncheckedIndexedAccess && !ts.isAssignmentTarget(node)) ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type;
67834                 if (compilerOptions.noPropertyAccessFromIndexSignature && ts.isPropertyAccessExpression(node)) {
67835                     error(right, ts.Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0, ts.unescapeLeadingUnderscores(right.escapedText));
67836                 }
67837             }
67838             else {
67839                 if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) {
67840                     addDeprecatedSuggestion(right, prop.declarations, right.escapedText);
67841                 }
67842                 checkPropertyNotUsedBeforeDeclaration(prop, node, right);
67843                 markPropertyAsReferenced(prop, node, left.kind === 107 /* ThisKeyword */);
67844                 getNodeLinks(node).resolvedSymbol = prop;
67845                 checkPropertyAccessibility(node, left.kind === 105 /* SuperKeyword */, apparentType, prop);
67846                 if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) {
67847                     error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
67848                     return errorType;
67849                 }
67850                 propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node);
67851             }
67852             return getFlowTypeOfAccessExpression(node, prop, propType, right);
67853         }
67854         function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) {
67855             // Only compute control flow type if this is a property access expression that isn't an
67856             // assignment target, and the referenced property was declared as a variable, property,
67857             // accessor, or optional method.
67858             var assignmentKind = ts.getAssignmentTargetKind(node);
67859             if (assignmentKind === 1 /* Definite */ ||
67860                 prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) {
67861                 return propType;
67862             }
67863             if (propType === autoType) {
67864                 return getFlowTypeOfProperty(node, prop);
67865             }
67866             // If strict null checks and strict property initialization checks are enabled, if we have
67867             // a this.xxx property access, if the property is an instance property without an initializer,
67868             // and if we are in a constructor of the same class as the property declaration, assume that
67869             // the property is uninitialized at the top of the control flow.
67870             var assumeUninitialized = false;
67871             if (strictNullChecks && strictPropertyInitialization && ts.isAccessExpression(node) && node.expression.kind === 107 /* ThisKeyword */) {
67872                 var declaration = prop && prop.valueDeclaration;
67873                 if (declaration && isInstancePropertyWithoutInitializer(declaration)) {
67874                     var flowContainer = getControlFlowContainer(node);
67875                     if (flowContainer.kind === 166 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) {
67876                         assumeUninitialized = true;
67877                     }
67878                 }
67879             }
67880             else if (strictNullChecks && prop && prop.valueDeclaration &&
67881                 ts.isPropertyAccessExpression(prop.valueDeclaration) &&
67882                 ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) &&
67883                 getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
67884                 assumeUninitialized = true;
67885             }
67886             var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
67887             if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
67888                 error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217
67889                 // Return the declared type to reduce follow-on errors
67890                 return propType;
67891             }
67892             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
67893         }
67894         function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
67895             var valueDeclaration = prop.valueDeclaration;
67896             if (!valueDeclaration || ts.getSourceFileOfNode(node).isDeclarationFile) {
67897                 return;
67898             }
67899             var diagnosticMessage;
67900             var declarationName = ts.idText(right);
67901             if (isInPropertyInitializer(node)
67902                 && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression))
67903                 && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)
67904                 && !isPropertyDeclaredInAncestorClass(prop)) {
67905                 diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
67906             }
67907             else if (valueDeclaration.kind === 252 /* ClassDeclaration */ &&
67908                 node.parent.kind !== 173 /* TypeReference */ &&
67909                 !(valueDeclaration.flags & 8388608 /* Ambient */) &&
67910                 !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
67911                 diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
67912             }
67913             if (diagnosticMessage) {
67914                 ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
67915             }
67916         }
67917         function isInPropertyInitializer(node) {
67918             return !!ts.findAncestor(node, function (node) {
67919                 switch (node.kind) {
67920                     case 163 /* PropertyDeclaration */:
67921                         return true;
67922                     case 288 /* PropertyAssignment */:
67923                     case 165 /* MethodDeclaration */:
67924                     case 167 /* GetAccessor */:
67925                     case 168 /* SetAccessor */:
67926                     case 290 /* SpreadAssignment */:
67927                     case 158 /* ComputedPropertyName */:
67928                     case 228 /* TemplateSpan */:
67929                     case 283 /* JsxExpression */:
67930                     case 280 /* JsxAttribute */:
67931                     case 281 /* JsxAttributes */:
67932                     case 282 /* JsxSpreadAttribute */:
67933                     case 275 /* JsxOpeningElement */:
67934                     case 223 /* ExpressionWithTypeArguments */:
67935                     case 286 /* HeritageClause */:
67936                         return false;
67937                     default:
67938                         return ts.isExpressionNode(node) ? false : "quit";
67939                 }
67940             });
67941         }
67942         /**
67943          * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass.
67944          * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration.
67945          */
67946         function isPropertyDeclaredInAncestorClass(prop) {
67947             if (!(prop.parent.flags & 32 /* Class */)) {
67948                 return false;
67949             }
67950             var classType = getTypeOfSymbol(prop.parent);
67951             while (true) {
67952                 classType = classType.symbol && getSuperClass(classType);
67953                 if (!classType) {
67954                     return false;
67955                 }
67956                 var superProperty = getPropertyOfType(classType, prop.escapedName);
67957                 if (superProperty && superProperty.valueDeclaration) {
67958                     return true;
67959                 }
67960             }
67961         }
67962         function getSuperClass(classType) {
67963             var x = getBaseTypes(classType);
67964             if (x.length === 0) {
67965                 return undefined;
67966             }
67967             return getIntersectionType(x);
67968         }
67969         function reportNonexistentProperty(propNode, containingType) {
67970             var errorInfo;
67971             var relatedInfo;
67972             if (!ts.isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) {
67973                 for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
67974                     var subtype = _a[_i];
67975                     if (!getPropertyOfType(subtype, propNode.escapedText) && !getIndexInfoOfType(subtype, 0 /* String */)) {
67976                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype));
67977                         break;
67978                     }
67979                 }
67980             }
67981             if (typeHasStaticProperty(propNode.escapedText, containingType)) {
67982                 var propName = ts.declarationNameToString(propNode);
67983                 var typeName = typeToString(containingType);
67984                 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);
67985             }
67986             else {
67987                 var promisedType = getPromisedTypeOfPromise(containingType);
67988                 if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
67989                     errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
67990                     relatedInfo = ts.createDiagnosticForNode(propNode, ts.Diagnostics.Did_you_forget_to_use_await);
67991                 }
67992                 else {
67993                     var missingProperty = ts.declarationNameToString(propNode);
67994                     var container = typeToString(containingType);
67995                     var libSuggestion = getSuggestedLibForNonExistentProperty(missingProperty, containingType);
67996                     if (libSuggestion !== undefined) {
67997                         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);
67998                     }
67999                     else {
68000                         var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
68001                         if (suggestion !== undefined) {
68002                             var suggestedName = ts.symbolName(suggestion);
68003                             errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, missingProperty, container, suggestedName);
68004                             relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName);
68005                         }
68006                         else {
68007                             errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container);
68008                         }
68009                     }
68010                 }
68011             }
68012             var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
68013             if (relatedInfo) {
68014                 ts.addRelatedInfo(resultDiagnostic, relatedInfo);
68015             }
68016             diagnostics.add(resultDiagnostic);
68017         }
68018         function typeHasStaticProperty(propName, containingType) {
68019             var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
68020             return prop !== undefined && prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */);
68021         }
68022         function getSuggestedLibForNonExistentName(name) {
68023             var missingName = diagnosticName(name);
68024             var allFeatures = ts.getScriptTargetFeatures();
68025             var libTargets = ts.getOwnKeys(allFeatures);
68026             for (var _i = 0, libTargets_1 = libTargets; _i < libTargets_1.length; _i++) {
68027                 var libTarget = libTargets_1[_i];
68028                 var containingTypes = ts.getOwnKeys(allFeatures[libTarget]);
68029                 if (containingTypes !== undefined && ts.contains(containingTypes, missingName)) {
68030                     return libTarget;
68031                 }
68032             }
68033         }
68034         function getSuggestedLibForNonExistentProperty(missingProperty, containingType) {
68035             var container = getApparentType(containingType).symbol;
68036             if (!container) {
68037                 return undefined;
68038             }
68039             var allFeatures = ts.getScriptTargetFeatures();
68040             var libTargets = ts.getOwnKeys(allFeatures);
68041             for (var _i = 0, libTargets_2 = libTargets; _i < libTargets_2.length; _i++) {
68042                 var libTarget = libTargets_2[_i];
68043                 var featuresOfLib = allFeatures[libTarget];
68044                 var featuresOfContainingType = featuresOfLib[ts.symbolName(container)];
68045                 if (featuresOfContainingType !== undefined && ts.contains(featuresOfContainingType, missingProperty)) {
68046                     return libTarget;
68047                 }
68048             }
68049         }
68050         function getSuggestedSymbolForNonexistentProperty(name, containingType) {
68051             return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */);
68052         }
68053         function getSuggestedSymbolForNonexistentJSXAttribute(name, containingType) {
68054             var strName = ts.isString(name) ? name : ts.idText(name);
68055             var properties = getPropertiesOfType(containingType);
68056             var jsxSpecific = strName === "for" ? ts.find(properties, function (x) { return ts.symbolName(x) === "htmlFor"; })
68057                 : strName === "class" ? ts.find(properties, function (x) { return ts.symbolName(x) === "className"; })
68058                     : undefined;
68059             return jsxSpecific !== null && jsxSpecific !== void 0 ? jsxSpecific : getSpellingSuggestionForName(strName, properties, 111551 /* Value */);
68060         }
68061         function getSuggestionForNonexistentProperty(name, containingType) {
68062             var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
68063             return suggestion && ts.symbolName(suggestion);
68064         }
68065         function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
68066             ts.Debug.assert(outerName !== undefined, "outername should always be defined");
68067             var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) {
68068                 ts.Debug.assertEqual(outerName, name, "name should equal outerName");
68069                 var symbol = getSymbol(symbols, name, meaning);
68070                 // 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
68071                 // So the table *contains* `x` but `x` isn't actually in scope.
68072                 // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion.
68073                 return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning);
68074             });
68075             return result;
68076         }
68077         function getSuggestionForNonexistentSymbol(location, outerName, meaning) {
68078             var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning);
68079             return symbolResult && ts.symbolName(symbolResult);
68080         }
68081         function getSuggestedSymbolForNonexistentModule(name, targetModule) {
68082             return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
68083         }
68084         function getSuggestionForNonexistentExport(name, targetModule) {
68085             var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule);
68086             return suggestion && ts.symbolName(suggestion);
68087         }
68088         function getSuggestionForNonexistentIndexSignature(objectType, expr, keyedType) {
68089             // check if object type has setter or getter
68090             function hasProp(name) {
68091                 var prop = getPropertyOfObjectType(objectType, name);
68092                 if (prop) {
68093                     var s = getSingleCallSignature(getTypeOfSymbol(prop));
68094                     return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0));
68095                 }
68096                 return false;
68097             }
68098             ;
68099             var suggestedMethod = ts.isAssignmentTarget(expr) ? "set" : "get";
68100             if (!hasProp(suggestedMethod)) {
68101                 return undefined;
68102             }
68103             var suggestion = ts.tryGetPropertyAccessOrIdentifierToString(expr.expression);
68104             if (suggestion === undefined) {
68105                 suggestion = suggestedMethod;
68106             }
68107             else {
68108                 suggestion += "." + suggestedMethod;
68109             }
68110             return suggestion;
68111         }
68112         /**
68113          * 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.
68114          * Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
68115          *
68116          * If there is a candidate that's the same except for case, return that.
68117          * If there is a candidate that's within one edit of the name, return that.
68118          * Otherwise, return the candidate with the smallest Levenshtein distance,
68119          *    except for candidates:
68120          *      * With no name
68121          *      * Whose meaning doesn't match the `meaning` parameter.
68122          *      * Whose length differs from the target name by more than 0.34 of the length of the name.
68123          *      * Whose levenshtein distance is more than 0.4 of the length of the name
68124          *        (0.4 allows 1 substitution/transposition for every 5 characters,
68125          *         and 1 insertion/deletion at 3 characters)
68126          */
68127         function getSpellingSuggestionForName(name, symbols, meaning) {
68128             return ts.getSpellingSuggestion(name, symbols, getCandidateName);
68129             function getCandidateName(candidate) {
68130                 var candidateName = ts.symbolName(candidate);
68131                 if (ts.startsWith(candidateName, "\"")) {
68132                     return undefined;
68133                 }
68134                 if (candidate.flags & meaning) {
68135                     return candidateName;
68136                 }
68137                 if (candidate.flags & 2097152 /* Alias */) {
68138                     var alias = tryResolveAlias(candidate);
68139                     if (alias && alias.flags & meaning) {
68140                         return candidateName;
68141                     }
68142                 }
68143                 return undefined;
68144             }
68145         }
68146         function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) {
68147             var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration;
68148             if (!valueDeclaration) {
68149                 return;
68150             }
68151             var hasPrivateModifier = ts.hasEffectiveModifier(valueDeclaration, 8 /* Private */);
68152             var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name);
68153             if (!hasPrivateModifier && !hasPrivateIdentifier) {
68154                 return;
68155             }
68156             if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) {
68157                 return;
68158             }
68159             if (isThisAccess) {
68160                 // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters).
68161                 var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration);
68162                 if (containingMethod && containingMethod.symbol === prop) {
68163                     return;
68164                 }
68165             }
68166             (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */;
68167         }
68168         function isValidPropertyAccess(node, propertyName) {
68169             switch (node.kind) {
68170                 case 201 /* PropertyAccessExpression */:
68171                     return isValidPropertyAccessWithType(node, node.expression.kind === 105 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
68172                 case 157 /* QualifiedName */:
68173                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left)));
68174                 case 195 /* ImportType */:
68175                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node));
68176             }
68177         }
68178         function isValidPropertyAccessForCompletions(node, type, property) {
68179             return isValidPropertyAccessWithType(node, node.kind === 201 /* PropertyAccessExpression */ && node.expression.kind === 105 /* SuperKeyword */, property.escapedName, type);
68180             // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context.
68181         }
68182         function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
68183             if (type === errorType || isTypeAny(type)) {
68184                 return true;
68185             }
68186             var prop = getPropertyOfType(type, propertyName);
68187             if (prop) {
68188                 if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) {
68189                     var declClass_1 = ts.getContainingClass(prop.valueDeclaration);
68190                     return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; });
68191                 }
68192                 return checkPropertyAccessibility(node, isSuper, type, prop);
68193             }
68194             // In js files properties of unions are allowed in completion
68195             return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); });
68196         }
68197         /**
68198          * Return the symbol of the for-in variable declared or referenced by the given for-in statement.
68199          */
68200         function getForInVariableSymbol(node) {
68201             var initializer = node.initializer;
68202             if (initializer.kind === 250 /* VariableDeclarationList */) {
68203                 var variable = initializer.declarations[0];
68204                 if (variable && !ts.isBindingPattern(variable.name)) {
68205                     return getSymbolOfNode(variable);
68206                 }
68207             }
68208             else if (initializer.kind === 78 /* Identifier */) {
68209                 return getResolvedSymbol(initializer);
68210             }
68211             return undefined;
68212         }
68213         /**
68214          * Return true if the given type is considered to have numeric property names.
68215          */
68216         function hasNumericPropertyNames(type) {
68217             return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */);
68218         }
68219         /**
68220          * Return true if given node is an expression consisting of an identifier (possibly parenthesized)
68221          * that references a for-in variable for an object with numeric property names.
68222          */
68223         function isForInVariableForNumericPropertyNames(expr) {
68224             var e = ts.skipParentheses(expr);
68225             if (e.kind === 78 /* Identifier */) {
68226                 var symbol = getResolvedSymbol(e);
68227                 if (symbol.flags & 3 /* Variable */) {
68228                     var child = expr;
68229                     var node = expr.parent;
68230                     while (node) {
68231                         if (node.kind === 238 /* ForInStatement */ &&
68232                             child === node.statement &&
68233                             getForInVariableSymbol(node) === symbol &&
68234                             hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
68235                             return true;
68236                         }
68237                         child = node;
68238                         node = node.parent;
68239                     }
68240                 }
68241             }
68242             return false;
68243         }
68244         function checkIndexedAccess(node) {
68245             return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) :
68246                 checkElementAccessExpression(node, checkNonNullExpression(node.expression));
68247         }
68248         function checkElementAccessChain(node) {
68249             var exprType = checkExpression(node.expression);
68250             var nonOptionalType = getOptionalExpressionType(exprType, node.expression);
68251             return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType);
68252         }
68253         function checkElementAccessExpression(node, exprType) {
68254             var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType;
68255             var indexExpression = node.argumentExpression;
68256             var indexType = checkExpression(indexExpression);
68257             if (objectType === errorType || objectType === silentNeverType) {
68258                 return objectType;
68259             }
68260             if (isConstEnumObjectType(objectType) && !ts.isStringLiteralLike(indexExpression)) {
68261                 error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
68262                 return errorType;
68263             }
68264             var effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType;
68265             var accessFlags = ts.isAssignmentTarget(node) ?
68266                 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) :
68267                 0 /* None */;
68268             var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, /*noUncheckedIndexedAccessCandidate*/ undefined, node, accessFlags | 16 /* ExpressionPosition */) || errorType;
68269             return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node);
68270         }
68271         function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) {
68272             if (expressionType === errorType) {
68273                 // There is already an error, so no need to report one.
68274                 return false;
68275             }
68276             if (!ts.isWellKnownSymbolSyntactically(expression)) {
68277                 return false;
68278             }
68279             // Make sure the property type is the primitive symbol type
68280             if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) {
68281                 if (reportError) {
68282                     error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression));
68283                 }
68284                 return false;
68285             }
68286             // The name is Symbol.<someName>, so make sure Symbol actually resolves to the
68287             // global Symbol object
68288             var leftHandSide = expression.expression;
68289             var leftHandSideSymbol = getResolvedSymbol(leftHandSide);
68290             if (!leftHandSideSymbol) {
68291                 return false;
68292             }
68293             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true);
68294             if (!globalESSymbol) {
68295                 // Already errored when we tried to look up the symbol
68296                 return false;
68297             }
68298             if (leftHandSideSymbol !== globalESSymbol) {
68299                 if (reportError) {
68300                     error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object);
68301                 }
68302                 return false;
68303             }
68304             return true;
68305         }
68306         function callLikeExpressionMayHaveTypeArguments(node) {
68307             return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node);
68308         }
68309         function resolveUntypedCall(node) {
68310             if (callLikeExpressionMayHaveTypeArguments(node)) {
68311                 // Check type arguments even though we will give an error that untyped calls may not accept type arguments.
68312                 // This gets us diagnostics for the type arguments and marks them as referenced.
68313                 ts.forEach(node.typeArguments, checkSourceElement);
68314             }
68315             if (node.kind === 205 /* TaggedTemplateExpression */) {
68316                 checkExpression(node.template);
68317             }
68318             else if (ts.isJsxOpeningLikeElement(node)) {
68319                 checkExpression(node.attributes);
68320             }
68321             else if (node.kind !== 161 /* Decorator */) {
68322                 ts.forEach(node.arguments, function (argument) {
68323                     checkExpression(argument);
68324                 });
68325             }
68326             return anySignature;
68327         }
68328         function resolveErrorCall(node) {
68329             resolveUntypedCall(node);
68330             return unknownSignature;
68331         }
68332         // Re-order candidate signatures into the result array. Assumes the result array to be empty.
68333         // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order
68334         // A nit here is that we reorder only signatures that belong to the same symbol,
68335         // so order how inherited signatures are processed is still preserved.
68336         // interface A { (x: string): void }
68337         // interface B extends A { (x: 'foo'): string }
68338         // const b: B;
68339         // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
68340         function reorderCandidates(signatures, result, callChainFlags) {
68341             var lastParent;
68342             var lastSymbol;
68343             var cutoffIndex = 0;
68344             var index;
68345             var specializedIndex = -1;
68346             var spliceIndex;
68347             ts.Debug.assert(!result.length);
68348             for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
68349                 var signature = signatures_7[_i];
68350                 var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
68351                 var parent = signature.declaration && signature.declaration.parent;
68352                 if (!lastSymbol || symbol === lastSymbol) {
68353                     if (lastParent && parent === lastParent) {
68354                         index = index + 1;
68355                     }
68356                     else {
68357                         lastParent = parent;
68358                         index = cutoffIndex;
68359                     }
68360                 }
68361                 else {
68362                     // current declaration belongs to a different symbol
68363                     // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
68364                     index = cutoffIndex = result.length;
68365                     lastParent = parent;
68366                 }
68367                 lastSymbol = symbol;
68368                 // specialized signatures always need to be placed before non-specialized signatures regardless
68369                 // of the cutoff position; see GH#1133
68370                 if (signatureHasLiteralTypes(signature)) {
68371                     specializedIndex++;
68372                     spliceIndex = specializedIndex;
68373                     // The cutoff index always needs to be greater than or equal to the specialized signature index
68374                     // in order to prevent non-specialized signatures from being added before a specialized
68375                     // signature.
68376                     cutoffIndex++;
68377                 }
68378                 else {
68379                     spliceIndex = index;
68380                 }
68381                 result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature);
68382             }
68383         }
68384         function isSpreadArgument(arg) {
68385             return !!arg && (arg.kind === 220 /* SpreadElement */ || arg.kind === 227 /* SyntheticExpression */ && arg.isSpread);
68386         }
68387         function getSpreadArgumentIndex(args) {
68388             return ts.findIndex(args, isSpreadArgument);
68389         }
68390         function acceptsVoid(t) {
68391             return !!(t.flags & 16384 /* Void */);
68392         }
68393         function acceptsVoidUndefinedUnknownOrAny(t) {
68394             return !!(t.flags & (16384 /* Void */ | 32768 /* Undefined */ | 2 /* Unknown */ | 1 /* Any */));
68395         }
68396         function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) {
68397             if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
68398             var argCount;
68399             var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
68400             var effectiveParameterCount = getParameterCount(signature);
68401             var effectiveMinimumArguments = getMinArgumentCount(signature);
68402             if (node.kind === 205 /* TaggedTemplateExpression */) {
68403                 argCount = args.length;
68404                 if (node.template.kind === 218 /* TemplateExpression */) {
68405                     // If a tagged template expression lacks a tail literal, the call is incomplete.
68406                     // Specifically, a template only can end in a TemplateTail or a Missing literal.
68407                     var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span.
68408                     callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
68409                 }
68410                 else {
68411                     // If the template didn't end in a backtick, or its beginning occurred right prior to EOF,
68412                     // then this might actually turn out to be a TemplateHead in the future;
68413                     // so we consider the call to be incomplete.
68414                     var templateLiteral = node.template;
68415                     ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */);
68416                     callIsIncomplete = !!templateLiteral.isUnterminated;
68417                 }
68418             }
68419             else if (node.kind === 161 /* Decorator */) {
68420                 argCount = getDecoratorArgumentCount(node, signature);
68421             }
68422             else if (ts.isJsxOpeningLikeElement(node)) {
68423                 callIsIncomplete = node.attributes.end === node.end;
68424                 if (callIsIncomplete) {
68425                     return true;
68426                 }
68427                 argCount = effectiveMinimumArguments === 0 ? args.length : 1;
68428                 effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type
68429                 effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked
68430             }
68431             else if (!node.arguments) {
68432                 // This only happens when we have something of the form: 'new C'
68433                 ts.Debug.assert(node.kind === 204 /* NewExpression */);
68434                 return getMinArgumentCount(signature) === 0;
68435             }
68436             else {
68437                 argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
68438                 // If we are missing the close parenthesis, the call is incomplete.
68439                 callIsIncomplete = node.arguments.end === node.end;
68440                 // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
68441                 var spreadArgIndex = getSpreadArgumentIndex(args);
68442                 if (spreadArgIndex >= 0) {
68443                     return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
68444                 }
68445             }
68446             // Too many arguments implies incorrect arity.
68447             if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) {
68448                 return false;
68449             }
68450             // If the call is incomplete, we should skip the lower bound check.
68451             // JSX signatures can have extra parameters provided by the library which we don't check
68452             if (callIsIncomplete || argCount >= effectiveMinimumArguments) {
68453                 return true;
68454             }
68455             for (var i = argCount; i < effectiveMinimumArguments; i++) {
68456                 var type = getTypeAtPosition(signature, i);
68457                 if (filterType(type, ts.isInJSFile(node) && !strictNullChecks ? acceptsVoidUndefinedUnknownOrAny : acceptsVoid).flags & 131072 /* Never */) {
68458                     return false;
68459                 }
68460             }
68461             return true;
68462         }
68463         function hasCorrectTypeArgumentArity(signature, typeArguments) {
68464             // If the user supplied type arguments, but the number of type arguments does not match
68465             // the declared number of type parameters, the call has an incorrect arity.
68466             var numTypeParameters = ts.length(signature.typeParameters);
68467             var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
68468             return !ts.some(typeArguments) ||
68469                 (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters);
68470         }
68471         // If type has a single call signature and no other members, return that signature. Otherwise, return undefined.
68472         function getSingleCallSignature(type) {
68473             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false);
68474         }
68475         function getSingleCallOrConstructSignature(type) {
68476             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false) ||
68477                 getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ false);
68478         }
68479         function getSingleSignature(type, kind, allowMembers) {
68480             if (type.flags & 524288 /* Object */) {
68481                 var resolved = resolveStructuredTypeMembers(type);
68482                 if (allowMembers || resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
68483                     if (kind === 0 /* Call */ && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) {
68484                         return resolved.callSignatures[0];
68485                     }
68486                     if (kind === 1 /* Construct */ && resolved.constructSignatures.length === 1 && resolved.callSignatures.length === 0) {
68487                         return resolved.constructSignatures[0];
68488                     }
68489                 }
68490             }
68491             return undefined;
68492         }
68493         // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
68494         function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
68495             var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
68496             // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
68497             // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
68498             // for T but leave it possible to later infer '[any]' back to A.
68499             var restType = getEffectiveRestType(contextualSignature);
68500             var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
68501             var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
68502             applyToParameterTypes(sourceSignature, signature, function (source, target) {
68503                 // Type parameters from outer context referenced by source type are fixed by instantiation of the source type
68504                 inferTypes(context.inferences, source, target);
68505             });
68506             if (!inferenceContext) {
68507                 applyToReturnTypes(contextualSignature, signature, function (source, target) {
68508                     inferTypes(context.inferences, source, target, 64 /* ReturnType */);
68509                 });
68510             }
68511             return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
68512         }
68513         function inferJsxTypeArguments(node, signature, checkMode, context) {
68514             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
68515             var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
68516             inferTypes(context.inferences, checkAttrType, paramType);
68517             return getInferredTypes(context);
68518         }
68519         function getThisArgumentType(thisArgumentNode) {
68520             if (!thisArgumentNode) {
68521                 return voidType;
68522             }
68523             var thisArgumentType = checkExpression(thisArgumentNode);
68524             return ts.isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) :
68525                 ts.isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) :
68526                     thisArgumentType;
68527         }
68528         function inferTypeArguments(node, signature, args, checkMode, context) {
68529             if (ts.isJsxOpeningLikeElement(node)) {
68530                 return inferJsxTypeArguments(node, signature, checkMode, context);
68531             }
68532             // If a contextual type is available, infer from that type to the return type of the call expression. For
68533             // example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
68534             // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the
68535             // return type of 'wrap'.
68536             if (node.kind !== 161 /* Decorator */) {
68537                 var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* SkipBindingPatterns */ : 0 /* None */);
68538                 if (contextualType) {
68539                     // We clone the inference context to avoid disturbing a resolution in progress for an
68540                     // outer call expression. Effectively we just want a snapshot of whatever has been
68541                     // inferred for any outer call expression so far.
68542                     var outerContext = getInferenceContext(node);
68543                     var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* NoDefault */));
68544                     var instantiatedType = instantiateType(contextualType, outerMapper);
68545                     // If the contextual type is a generic function type with a single call signature, we
68546                     // instantiate the type with its own type parameters and type arguments. This ensures that
68547                     // the type parameters are not erased to type any during type inference such that they can
68548                     // be inferred as actual types from the contextual type. For example:
68549                     //   declare function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[];
68550                     //   const boxElements: <A>(a: A[]) => { value: A }[] = arrayMap(value => ({ value }));
68551                     // Above, the type of the 'value' parameter is inferred to be 'A'.
68552                     var contextualSignature = getSingleCallSignature(instantiatedType);
68553                     var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ?
68554                         getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) :
68555                         instantiatedType;
68556                     var inferenceTargetType = getReturnTypeOfSignature(signature);
68557                     // Inferences made from return types have lower priority than all other inferences.
68558                     inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64 /* ReturnType */);
68559                     // Create a type mapper for instantiating generic contextual types using the inferences made
68560                     // from the return type. We need a separate inference pass here because (a) instantiation of
68561                     // the source type uses the outer context's return mapper (which excludes inferences made from
68562                     // outer arguments), and (b) we don't want any further inferences going into this context.
68563                     var returnContext = createInferenceContext(signature.typeParameters, signature, context.flags);
68564                     var returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper);
68565                     inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType);
68566                     context.returnMapper = ts.some(returnContext.inferences, hasInferenceCandidates) ? getMapperFromContext(cloneInferredPartOfContext(returnContext)) : undefined;
68567                 }
68568             }
68569             var restType = getNonArrayRestType(signature);
68570             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
68571             if (restType && restType.flags & 262144 /* TypeParameter */) {
68572                 var info = ts.find(context.inferences, function (info) { return info.typeParameter === restType; });
68573                 if (info) {
68574                     info.impliedArity = ts.findIndex(args, isSpreadArgument, argCount) < 0 ? args.length - argCount : undefined;
68575                 }
68576             }
68577             var thisType = getThisTypeOfSignature(signature);
68578             if (thisType) {
68579                 var thisArgumentNode = getThisArgumentOfCall(node);
68580                 inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType);
68581             }
68582             for (var i = 0; i < argCount; i++) {
68583                 var arg = args[i];
68584                 if (arg.kind !== 222 /* OmittedExpression */) {
68585                     var paramType = getTypeAtPosition(signature, i);
68586                     var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
68587                     inferTypes(context.inferences, argType, paramType);
68588                 }
68589             }
68590             if (restType) {
68591                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context, checkMode);
68592                 inferTypes(context.inferences, spreadType, restType);
68593             }
68594             return getInferredTypes(context);
68595         }
68596         function getMutableArrayOrTupleType(type) {
68597             return type.flags & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) :
68598                 type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type :
68599                     isTupleType(type) ? createTupleType(getTypeArguments(type), type.target.elementFlags, /*readonly*/ false, type.target.labeledElementDeclarations) :
68600                         createTupleType([type], [8 /* Variadic */]);
68601         }
68602         function getSpreadArgumentType(args, index, argCount, restType, context, checkMode) {
68603             if (index >= argCount - 1) {
68604                 var arg = args[argCount - 1];
68605                 if (isSpreadArgument(arg)) {
68606                     // We are inferring from a spread expression in the last argument position, i.e. both the parameter
68607                     // and the argument are ...x forms.
68608                     return getMutableArrayOrTupleType(arg.kind === 227 /* SyntheticExpression */ ? arg.type :
68609                         checkExpressionWithContextualType(arg.expression, restType, context, checkMode));
68610                 }
68611             }
68612             var types = [];
68613             var flags = [];
68614             var names = [];
68615             for (var i = index; i < argCount; i++) {
68616                 var arg = args[i];
68617                 if (isSpreadArgument(arg)) {
68618                     var spreadType = arg.kind === 227 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression);
68619                     if (isArrayLikeType(spreadType)) {
68620                         types.push(spreadType);
68621                         flags.push(8 /* Variadic */);
68622                     }
68623                     else {
68624                         types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 220 /* SpreadElement */ ? arg.expression : arg));
68625                         flags.push(4 /* Rest */);
68626                     }
68627                 }
68628                 else {
68629                     var contextualType = getIndexedAccessType(restType, getLiteralType(i - index));
68630                     var argType = checkExpressionWithContextualType(arg, contextualType, context, checkMode);
68631                     var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */);
68632                     types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
68633                     flags.push(1 /* Required */);
68634                 }
68635                 if (arg.kind === 227 /* SyntheticExpression */ && arg.tupleNameSource) {
68636                     names.push(arg.tupleNameSource);
68637                 }
68638             }
68639             return createTupleType(types, flags, /*readonly*/ false, ts.length(names) === ts.length(types) ? names : undefined);
68640         }
68641         function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) {
68642             var isJavascript = ts.isInJSFile(signature.declaration);
68643             var typeParameters = signature.typeParameters;
68644             var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
68645             var mapper;
68646             for (var i = 0; i < typeArgumentNodes.length; i++) {
68647                 ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments");
68648                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
68649                 if (constraint) {
68650                     var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
68651                     var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
68652                     if (!mapper) {
68653                         mapper = createTypeMapper(typeParameters, typeArgumentTypes);
68654                     }
68655                     var typeArgument = typeArgumentTypes[i];
68656                     if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
68657                         return undefined;
68658                     }
68659                 }
68660             }
68661             return typeArgumentTypes;
68662         }
68663         function getJsxReferenceKind(node) {
68664             if (isJsxIntrinsicIdentifier(node.tagName)) {
68665                 return 2 /* Mixed */;
68666             }
68667             var tagType = getApparentType(checkExpression(node.tagName));
68668             if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) {
68669                 return 0 /* Component */;
68670             }
68671             if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) {
68672                 return 1 /* Function */;
68673             }
68674             return 2 /* Mixed */;
68675         }
68676         /**
68677          * Check if the given signature can possibly be a signature called by the JSX opening-like element.
68678          * @param node a JSX opening-like element we are trying to figure its call signature
68679          * @param signature a candidate signature we are trying whether it is a call signature
68680          * @param relation a relationship to check parameter and argument type
68681          */
68682         function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer) {
68683             // Stateless function components can have maximum of three arguments: "props", "context", and "updater".
68684             // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
68685             // can be specified by users through attributes property.
68686             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
68687             var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
68688             return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes, 
68689             /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
68690             function checkTagNameDoesNotExpectTooManyArguments() {
68691                 var _a;
68692                 if (getJsxNamespaceContainerForImplicitImport(node)) {
68693                     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)
68694                 }
68695                 var tagType = ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node) && !isJsxIntrinsicIdentifier(node.tagName) ? checkExpression(node.tagName) : undefined;
68696                 if (!tagType) {
68697                     return true;
68698                 }
68699                 var tagCallSignatures = getSignaturesOfType(tagType, 0 /* Call */);
68700                 if (!ts.length(tagCallSignatures)) {
68701                     return true;
68702                 }
68703                 var factory = getJsxFactoryEntity(node);
68704                 if (!factory) {
68705                     return true;
68706                 }
68707                 var factorySymbol = resolveEntityName(factory, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, node);
68708                 if (!factorySymbol) {
68709                     return true;
68710                 }
68711                 var factoryType = getTypeOfSymbol(factorySymbol);
68712                 var callSignatures = getSignaturesOfType(factoryType, 0 /* Call */);
68713                 if (!ts.length(callSignatures)) {
68714                     return true;
68715                 }
68716                 var hasFirstParamSignatures = false;
68717                 var maxParamCount = 0;
68718                 // Check that _some_ first parameter expects a FC-like thing, and that some overload of the SFC expects an acceptable number of arguments
68719                 for (var _i = 0, callSignatures_1 = callSignatures; _i < callSignatures_1.length; _i++) {
68720                     var sig = callSignatures_1[_i];
68721                     var firstparam = getTypeAtPosition(sig, 0);
68722                     var signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */);
68723                     if (!ts.length(signaturesOfParam))
68724                         continue;
68725                     for (var _b = 0, signaturesOfParam_1 = signaturesOfParam; _b < signaturesOfParam_1.length; _b++) {
68726                         var paramSig = signaturesOfParam_1[_b];
68727                         hasFirstParamSignatures = true;
68728                         if (hasEffectiveRestParameter(paramSig)) {
68729                             return true; // some signature has a rest param, so function components can have an arbitrary number of arguments
68730                         }
68731                         var paramCount = getParameterCount(paramSig);
68732                         if (paramCount > maxParamCount) {
68733                             maxParamCount = paramCount;
68734                         }
68735                     }
68736                 }
68737                 if (!hasFirstParamSignatures) {
68738                     // Not a single signature had a first parameter which expected a signature - for back compat, and
68739                     // to guard against generic factories which won't have signatures directly, do not error
68740                     return true;
68741                 }
68742                 var absoluteMinArgCount = Infinity;
68743                 for (var _c = 0, tagCallSignatures_1 = tagCallSignatures; _c < tagCallSignatures_1.length; _c++) {
68744                     var tagSig = tagCallSignatures_1[_c];
68745                     var tagRequiredArgCount = getMinArgumentCount(tagSig);
68746                     if (tagRequiredArgCount < absoluteMinArgCount) {
68747                         absoluteMinArgCount = tagRequiredArgCount;
68748                     }
68749                 }
68750                 if (absoluteMinArgCount <= maxParamCount) {
68751                     return true; // some signature accepts the number of arguments the function component provides
68752                 }
68753                 if (reportErrors) {
68754                     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);
68755                     var tagNameDeclaration = (_a = getSymbolAtLocation(node.tagName)) === null || _a === void 0 ? void 0 : _a.valueDeclaration;
68756                     if (tagNameDeclaration) {
68757                         ts.addRelatedInfo(diag, ts.createDiagnosticForNode(tagNameDeclaration, ts.Diagnostics._0_is_declared_here, ts.entityNameToString(node.tagName)));
68758                     }
68759                     if (errorOutputContainer && errorOutputContainer.skipLogging) {
68760                         (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
68761                     }
68762                     if (!errorOutputContainer.skipLogging) {
68763                         diagnostics.add(diag);
68764                     }
68765                 }
68766                 return false;
68767             }
68768         }
68769         function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors, containingMessageChain) {
68770             var errorOutputContainer = { errors: undefined, skipLogging: true };
68771             if (ts.isJsxOpeningLikeElement(node)) {
68772                 if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer)) {
68773                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "jsx should have errors when reporting errors");
68774                     return errorOutputContainer.errors || ts.emptyArray;
68775                 }
68776                 return undefined;
68777             }
68778             var thisType = getThisTypeOfSignature(signature);
68779             if (thisType && thisType !== voidType && node.kind !== 204 /* NewExpression */) {
68780                 // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType
68781                 // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
68782                 // If the expression is a new expression, then the check is skipped.
68783                 var thisArgumentNode = getThisArgumentOfCall(node);
68784                 var thisArgumentType = getThisArgumentType(thisArgumentNode);
68785                 var errorNode = reportErrors ? (thisArgumentNode || node) : undefined;
68786                 var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
68787                 if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) {
68788                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "this parameter should have errors when reporting errors");
68789                     return errorOutputContainer.errors || ts.emptyArray;
68790                 }
68791             }
68792             var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
68793             var restType = getNonArrayRestType(signature);
68794             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
68795             for (var i = 0; i < argCount; i++) {
68796                 var arg = args[i];
68797                 if (arg.kind !== 222 /* OmittedExpression */) {
68798                     var paramType = getTypeAtPosition(signature, i);
68799                     var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
68800                     // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
68801                     // we obtain the regular type of any object literal arguments because we may not have inferred complete
68802                     // parameter types yet and therefore excess property checks may yield false positives (see #17041).
68803                     var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
68804                     if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage, containingMessageChain, errorOutputContainer)) {
68805                         ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "parameter should have errors when reporting errors");
68806                         maybeAddMissingAwaitInfo(arg, checkArgType, paramType);
68807                         return errorOutputContainer.errors || ts.emptyArray;
68808                     }
68809                 }
68810             }
68811             if (restType) {
68812                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined, checkMode);
68813                 var restArgCount = args.length - argCount;
68814                 var errorNode = !reportErrors ? undefined :
68815                     restArgCount === 0 ? node :
68816                         restArgCount === 1 ? args[argCount] :
68817                             ts.setTextRangePosEnd(createSyntheticExpression(node, spreadType), args[argCount].pos, args[args.length - 1].end);
68818                 if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ undefined, errorOutputContainer)) {
68819                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
68820                     maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
68821                     return errorOutputContainer.errors || ts.emptyArray;
68822                 }
68823             }
68824             return undefined;
68825             function maybeAddMissingAwaitInfo(errorNode, source, target) {
68826                 if (errorNode && reportErrors && errorOutputContainer.errors && errorOutputContainer.errors.length) {
68827                     // Bail if target is Promise-like---something else is wrong
68828                     if (getAwaitedTypeOfPromise(target)) {
68829                         return;
68830                     }
68831                     var awaitedTypeOfSource = getAwaitedTypeOfPromise(source);
68832                     if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) {
68833                         ts.addRelatedInfo(errorOutputContainer.errors[0], ts.createDiagnosticForNode(errorNode, ts.Diagnostics.Did_you_forget_to_use_await));
68834                     }
68835                 }
68836             }
68837         }
68838         /**
68839          * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise.
68840          */
68841         function getThisArgumentOfCall(node) {
68842             if (node.kind === 203 /* CallExpression */) {
68843                 var callee = ts.skipOuterExpressions(node.expression);
68844                 if (ts.isAccessExpression(callee)) {
68845                     return callee.expression;
68846                 }
68847             }
68848         }
68849         function createSyntheticExpression(parent, type, isSpread, tupleNameSource) {
68850             var result = ts.parseNodeFactory.createSyntheticExpression(type, isSpread, tupleNameSource);
68851             ts.setTextRange(result, parent);
68852             ts.setParent(result, parent);
68853             return result;
68854         }
68855         /**
68856          * Returns the effective arguments for an expression that works like a function invocation.
68857          */
68858         function getEffectiveCallArguments(node) {
68859             if (node.kind === 205 /* TaggedTemplateExpression */) {
68860                 var template = node.template;
68861                 var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
68862                 if (template.kind === 218 /* TemplateExpression */) {
68863                     ts.forEach(template.templateSpans, function (span) {
68864                         args_3.push(span.expression);
68865                     });
68866                 }
68867                 return args_3;
68868             }
68869             if (node.kind === 161 /* Decorator */) {
68870                 return getEffectiveDecoratorArguments(node);
68871             }
68872             if (ts.isJsxOpeningLikeElement(node)) {
68873                 return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray;
68874             }
68875             var args = node.arguments || ts.emptyArray;
68876             var spreadIndex = getSpreadArgumentIndex(args);
68877             if (spreadIndex >= 0) {
68878                 // Create synthetic arguments from spreads of tuple types.
68879                 var effectiveArgs_1 = args.slice(0, spreadIndex);
68880                 var _loop_20 = function (i) {
68881                     var arg = args[i];
68882                     // We can call checkExpressionCached because spread expressions never have a contextual type.
68883                     var spreadType = arg.kind === 220 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression));
68884                     if (spreadType && isTupleType(spreadType)) {
68885                         ts.forEach(getTypeArguments(spreadType), function (t, i) {
68886                             var _a;
68887                             var flags = spreadType.target.elementFlags[i];
68888                             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]);
68889                             effectiveArgs_1.push(syntheticArg);
68890                         });
68891                     }
68892                     else {
68893                         effectiveArgs_1.push(arg);
68894                     }
68895                 };
68896                 for (var i = spreadIndex; i < args.length; i++) {
68897                     _loop_20(i);
68898                 }
68899                 return effectiveArgs_1;
68900             }
68901             return args;
68902         }
68903         /**
68904          * Returns the synthetic argument list for a decorator invocation.
68905          */
68906         function getEffectiveDecoratorArguments(node) {
68907             var parent = node.parent;
68908             var expr = node.expression;
68909             switch (parent.kind) {
68910                 case 252 /* ClassDeclaration */:
68911                 case 221 /* ClassExpression */:
68912                     // For a class decorator, the `target` is the type of the class (e.g. the
68913                     // "static" or "constructor" side of the class).
68914                     return [
68915                         createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent)))
68916                     ];
68917                 case 160 /* Parameter */:
68918                     // A parameter declaration decorator will have three arguments (see
68919                     // `ParameterDecorator` in core.d.ts).
68920                     var func = parent.parent;
68921                     return [
68922                         createSyntheticExpression(expr, parent.parent.kind === 166 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType),
68923                         createSyntheticExpression(expr, anyType),
68924                         createSyntheticExpression(expr, numberType)
68925                     ];
68926                 case 163 /* PropertyDeclaration */:
68927                 case 165 /* MethodDeclaration */:
68928                 case 167 /* GetAccessor */:
68929                 case 168 /* SetAccessor */:
68930                     // A method or accessor declaration decorator will have two or three arguments (see
68931                     // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators
68932                     // for ES3, we will only pass two arguments.
68933                     var hasPropDesc = parent.kind !== 163 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */;
68934                     return [
68935                         createSyntheticExpression(expr, getParentTypeOfClassElement(parent)),
68936                         createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)),
68937                         createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType)
68938                     ];
68939             }
68940             return ts.Debug.fail();
68941         }
68942         /**
68943          * Returns the argument count for a decorator node that works like a function invocation.
68944          */
68945         function getDecoratorArgumentCount(node, signature) {
68946             switch (node.parent.kind) {
68947                 case 252 /* ClassDeclaration */:
68948                 case 221 /* ClassExpression */:
68949                     return 1;
68950                 case 163 /* PropertyDeclaration */:
68951                     return 2;
68952                 case 165 /* MethodDeclaration */:
68953                 case 167 /* GetAccessor */:
68954                 case 168 /* SetAccessor */:
68955                     // For ES3 or decorators with only two parameters we supply only two arguments
68956                     return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3;
68957                 case 160 /* Parameter */:
68958                     return 3;
68959                 default:
68960                     return ts.Debug.fail();
68961             }
68962         }
68963         function getDiagnosticSpanForCallNode(node, doNotIncludeArguments) {
68964             var start;
68965             var length;
68966             var sourceFile = ts.getSourceFileOfNode(node);
68967             if (ts.isPropertyAccessExpression(node.expression)) {
68968                 var nameSpan = ts.getErrorSpanForNode(sourceFile, node.expression.name);
68969                 start = nameSpan.start;
68970                 length = doNotIncludeArguments ? nameSpan.length : node.end - start;
68971             }
68972             else {
68973                 var expressionSpan = ts.getErrorSpanForNode(sourceFile, node.expression);
68974                 start = expressionSpan.start;
68975                 length = doNotIncludeArguments ? expressionSpan.length : node.end - start;
68976             }
68977             return { start: start, length: length, sourceFile: sourceFile };
68978         }
68979         function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) {
68980             if (ts.isCallExpression(node)) {
68981                 var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_6 = _a.length;
68982                 return ts.createFileDiagnostic(sourceFile, start, length_6, message, arg0, arg1, arg2, arg3);
68983             }
68984             else {
68985                 return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3);
68986             }
68987         }
68988         function isPromiseResolveArityError(node) {
68989             if (!ts.isCallExpression(node) || !ts.isIdentifier(node.expression))
68990                 return false;
68991             var symbol = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, undefined, undefined, false);
68992             var decl = symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration;
68993             if (!decl || !ts.isParameter(decl) || !isFunctionExpressionOrArrowFunction(decl.parent) || !ts.isNewExpression(decl.parent.parent) || !ts.isIdentifier(decl.parent.parent.expression)) {
68994                 return false;
68995             }
68996             var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
68997             if (!globalPromiseSymbol)
68998                 return false;
68999             var constructorSymbol = getSymbolAtLocation(decl.parent.parent.expression, /*ignoreErrors*/ true);
69000             return constructorSymbol === globalPromiseSymbol;
69001         }
69002         function getArgumentArityError(node, signatures, args) {
69003             var min = Number.POSITIVE_INFINITY;
69004             var max = Number.NEGATIVE_INFINITY;
69005             var belowArgCount = Number.NEGATIVE_INFINITY;
69006             var aboveArgCount = Number.POSITIVE_INFINITY;
69007             var argCount = args.length;
69008             var closestSignature;
69009             for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
69010                 var sig = signatures_8[_i];
69011                 var minCount = getMinArgumentCount(sig);
69012                 var maxCount = getParameterCount(sig);
69013                 if (minCount < argCount && minCount > belowArgCount)
69014                     belowArgCount = minCount;
69015                 if (argCount < maxCount && maxCount < aboveArgCount)
69016                     aboveArgCount = maxCount;
69017                 if (minCount < min) {
69018                     min = minCount;
69019                     closestSignature = sig;
69020                 }
69021                 max = Math.max(max, maxCount);
69022             }
69023             var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter);
69024             var paramRange = hasRestParameter ? min :
69025                 min < max ? min + "-" + max :
69026                     min;
69027             var hasSpreadArgument = getSpreadArgumentIndex(args) > -1;
69028             if (argCount <= max && hasSpreadArgument) {
69029                 argCount--;
69030             }
69031             var spanArray;
69032             var related;
69033             var error = hasRestParameter || hasSpreadArgument ?
69034                 hasRestParameter && hasSpreadArgument ?
69035                     ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
69036                     hasRestParameter ?
69037                         ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
69038                         ts.Diagnostics.Expected_0_arguments_but_got_1_or_more :
69039                 paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ?
69040                     ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise :
69041                     ts.Diagnostics.Expected_0_arguments_but_got_1;
69042             if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
69043                 var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
69044                 if (paramDecl) {
69045                     related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided :
69046                         ts.isRestParameter(paramDecl) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined);
69047                 }
69048             }
69049             if (min < argCount && argCount < max) {
69050                 return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
69051             }
69052             if (!hasSpreadArgument && argCount < min) {
69053                 var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount);
69054                 return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
69055             }
69056             if (hasRestParameter || hasSpreadArgument) {
69057                 spanArray = ts.factory.createNodeArray(args);
69058                 if (hasSpreadArgument && argCount) {
69059                     var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
69060                     spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
69061                 }
69062             }
69063             else {
69064                 spanArray = ts.factory.createNodeArray(args.slice(max));
69065             }
69066             var pos = ts.first(spanArray).pos;
69067             var end = ts.last(spanArray).end;
69068             if (end === pos) {
69069                 end++;
69070             }
69071             ts.setTextRangePosEnd(spanArray, pos, end);
69072             var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
69073             return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
69074         }
69075         function getTypeArgumentArityError(node, signatures, typeArguments) {
69076             var argCount = typeArguments.length;
69077             // No overloads exist
69078             if (signatures.length === 1) {
69079                 var sig = signatures[0];
69080                 var min_1 = getMinTypeArgumentCount(sig.typeParameters);
69081                 var max = ts.length(sig.typeParameters);
69082                 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);
69083             }
69084             // Overloads exist
69085             var belowArgCount = -Infinity;
69086             var aboveArgCount = Infinity;
69087             for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) {
69088                 var sig = signatures_9[_i];
69089                 var min_2 = getMinTypeArgumentCount(sig.typeParameters);
69090                 var max = ts.length(sig.typeParameters);
69091                 if (min_2 > argCount) {
69092                     aboveArgCount = Math.min(aboveArgCount, min_2);
69093                 }
69094                 else if (max < argCount) {
69095                     belowArgCount = Math.max(belowArgCount, max);
69096                 }
69097             }
69098             if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) {
69099                 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);
69100             }
69101             return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
69102         }
69103         function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) {
69104             var isTaggedTemplate = node.kind === 205 /* TaggedTemplateExpression */;
69105             var isDecorator = node.kind === 161 /* Decorator */;
69106             var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
69107             var reportErrors = !candidatesOutArray && produceDiagnostics;
69108             var typeArguments;
69109             if (!isDecorator) {
69110                 typeArguments = node.typeArguments;
69111                 // We already perform checking on the type arguments on the class declaration itself.
69112                 if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 105 /* SuperKeyword */) {
69113                     ts.forEach(typeArguments, checkSourceElement);
69114                 }
69115             }
69116             var candidates = candidatesOutArray || [];
69117             // reorderCandidates fills up the candidates array directly
69118             reorderCandidates(signatures, candidates, callChainFlags);
69119             if (!candidates.length) {
69120                 if (reportErrors) {
69121                     diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures));
69122                 }
69123                 return resolveErrorCall(node);
69124             }
69125             var args = getEffectiveCallArguments(node);
69126             // The excludeArgument array contains true for each context sensitive argument (an argument
69127             // is context sensitive it is susceptible to a one-time permanent contextual typing).
69128             //
69129             // The idea is that we will perform type argument inference & assignability checking once
69130             // without using the susceptible parameters that are functions, and once more for those
69131             // parameters, contextually typing each as we go along.
69132             //
69133             // For a tagged template, then the first argument be 'undefined' if necessary because it
69134             // represents a TemplateStringsArray.
69135             //
69136             // For a decorator, no arguments are susceptible to contextual typing due to the fact
69137             // decorators are applied to a declaration by the emitter, and not to an expression.
69138             var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
69139             var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
69140             // The following variables are captured and modified by calls to chooseOverload.
69141             // If overload resolution or type argument inference fails, we want to report the
69142             // best error possible. The best error is one which says that an argument was not
69143             // assignable to a parameter. This implies that everything else about the overload
69144             // was fine. So if there is any overload that is only incorrect because of an
69145             // argument, we will report an error on that one.
69146             //
69147             //     function foo(s: string): void;
69148             //     function foo(n: number): void; // Report argument error on this overload
69149             //     function foo(): void;
69150             //     foo(true);
69151             //
69152             // If none of the overloads even made it that far, there are two possibilities.
69153             // There was a problem with type arguments for some overload, in which case
69154             // report an error on that. Or none of the overloads even had correct arity,
69155             // in which case give an arity error.
69156             //
69157             //     function foo<T extends string>(x: T): void; // Report type argument error
69158             //     function foo(): void;
69159             //     foo<number>(0);
69160             //
69161             var candidatesForArgumentError;
69162             var candidateForArgumentArityError;
69163             var candidateForTypeArgumentError;
69164             var result;
69165             // If we are in signature help, a trailing comma indicates that we intend to provide another argument,
69166             // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
69167             var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 203 /* CallExpression */ && node.arguments.hasTrailingComma;
69168             // Section 4.12.1:
69169             // if the candidate list contains one or more signatures for which the type of each argument
69170             // expression is a subtype of each corresponding parameter type, the return type of the first
69171             // of those signatures becomes the return type of the function call.
69172             // Otherwise, the return type of the first signature in the candidate list becomes the return
69173             // type of the function call.
69174             //
69175             // Whether the call is an error is determined by assignability of the arguments. The subtype pass
69176             // is just important for choosing the best signature. So in the case where there is only one
69177             // signature, the subtype pass is useless. So skipping it is an optimization.
69178             if (candidates.length > 1) {
69179                 result = chooseOverload(candidates, subtypeRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma);
69180             }
69181             if (!result) {
69182                 result = chooseOverload(candidates, assignableRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma);
69183             }
69184             if (result) {
69185                 return result;
69186             }
69187             // No signatures were applicable. Now report errors based on the last applicable signature with
69188             // no arguments excluded from assignability checks.
69189             // If candidate is undefined, it means that no candidates had a suitable arity. In that case,
69190             // skip the checkApplicableSignature check.
69191             if (reportErrors) {
69192                 if (candidatesForArgumentError) {
69193                     if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) {
69194                         var last_2 = candidatesForArgumentError[candidatesForArgumentError.length - 1];
69195                         var chain_1;
69196                         if (candidatesForArgumentError.length > 3) {
69197                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.The_last_overload_gave_the_following_error);
69198                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.No_overload_matches_this_call);
69199                         }
69200                         var diags = getSignatureApplicabilityError(node, args, last_2, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, function () { return chain_1; });
69201                         if (diags) {
69202                             for (var _i = 0, diags_1 = diags; _i < diags_1.length; _i++) {
69203                                 var d = diags_1[_i];
69204                                 if (last_2.declaration && candidatesForArgumentError.length > 3) {
69205                                     ts.addRelatedInfo(d, ts.createDiagnosticForNode(last_2.declaration, ts.Diagnostics.The_last_overload_is_declared_here));
69206                                 }
69207                                 addImplementationSuccessElaboration(last_2, d);
69208                                 diagnostics.add(d);
69209                             }
69210                         }
69211                         else {
69212                             ts.Debug.fail("No error for last overload signature");
69213                         }
69214                     }
69215                     else {
69216                         var allDiagnostics = [];
69217                         var max = 0;
69218                         var min_3 = Number.MAX_VALUE;
69219                         var minIndex = 0;
69220                         var i_1 = 0;
69221                         var _loop_21 = function (c) {
69222                             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)); };
69223                             var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2);
69224                             if (diags_2) {
69225                                 if (diags_2.length <= min_3) {
69226                                     min_3 = diags_2.length;
69227                                     minIndex = i_1;
69228                                 }
69229                                 max = Math.max(max, diags_2.length);
69230                                 allDiagnostics.push(diags_2);
69231                             }
69232                             else {
69233                                 ts.Debug.fail("No error for 3 or fewer overload signatures");
69234                             }
69235                             i_1++;
69236                         };
69237                         for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) {
69238                             var c = candidatesForArgumentError_1[_a];
69239                             _loop_21(c);
69240                         }
69241                         var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics);
69242                         ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures");
69243                         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);
69244                         // 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
69245                         // arrays and the emptyArray singleton where possible, which is decidedly not what we want while we're still constructing this diagnostic
69246                         var related = __spreadArray([], ts.flatMap(diags_3, function (d) { return d.relatedInformation; }));
69247                         var diag = void 0;
69248                         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; })) {
69249                             var _b = diags_3[0], file = _b.file, start = _b.start, length_7 = _b.length;
69250                             diag = { file: file, start: start, length: length_7, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related };
69251                         }
69252                         else {
69253                             diag = ts.createDiagnosticForNodeFromMessageChain(node, chain, related);
69254                         }
69255                         addImplementationSuccessElaboration(candidatesForArgumentError[0], diag);
69256                         diagnostics.add(diag);
69257                     }
69258                 }
69259                 else if (candidateForArgumentArityError) {
69260                     diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
69261                 }
69262                 else if (candidateForTypeArgumentError) {
69263                     checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError);
69264                 }
69265                 else {
69266                     var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); });
69267                     if (signaturesWithCorrectTypeArgumentArity.length === 0) {
69268                         diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
69269                     }
69270                     else if (!isDecorator) {
69271                         diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
69272                     }
69273                     else if (fallbackError) {
69274                         diagnostics.add(getDiagnosticForCallNode(node, fallbackError));
69275                     }
69276                 }
69277             }
69278             return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);
69279             function addImplementationSuccessElaboration(failed, diagnostic) {
69280                 var _a, _b;
69281                 var oldCandidatesForArgumentError = candidatesForArgumentError;
69282                 var oldCandidateForArgumentArityError = candidateForArgumentArityError;
69283                 var oldCandidateForTypeArgumentError = candidateForTypeArgumentError;
69284                 var failedSignatureDeclarations = ((_b = (_a = failed.declaration) === null || _a === void 0 ? void 0 : _a.symbol) === null || _b === void 0 ? void 0 : _b.declarations) || ts.emptyArray;
69285                 var isOverload = failedSignatureDeclarations.length > 1;
69286                 var implDecl = isOverload ? ts.find(failedSignatureDeclarations, function (d) { return ts.isFunctionLikeDeclaration(d) && ts.nodeIsPresent(d.body); }) : undefined;
69287                 if (implDecl) {
69288                     var candidate = getSignatureFromDeclaration(implDecl);
69289                     var isSingleNonGenericCandidate_1 = !candidate.typeParameters;
69290                     if (chooseOverload([candidate], assignableRelation, isSingleNonGenericCandidate_1)) {
69291                         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));
69292                     }
69293                 }
69294                 candidatesForArgumentError = oldCandidatesForArgumentError;
69295                 candidateForArgumentArityError = oldCandidateForArgumentArityError;
69296                 candidateForTypeArgumentError = oldCandidateForTypeArgumentError;
69297             }
69298             function chooseOverload(candidates, relation, isSingleNonGenericCandidate, signatureHelpTrailingComma) {
69299                 if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
69300                 candidatesForArgumentError = undefined;
69301                 candidateForArgumentArityError = undefined;
69302                 candidateForTypeArgumentError = undefined;
69303                 if (isSingleNonGenericCandidate) {
69304                     var candidate = candidates[0];
69305                     if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
69306                         return undefined;
69307                     }
69308                     if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
69309                         candidatesForArgumentError = [candidate];
69310                         return undefined;
69311                     }
69312                     return candidate;
69313                 }
69314                 for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
69315                     var candidate = candidates[candidateIndex];
69316                     if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
69317                         continue;
69318                     }
69319                     var checkCandidate = void 0;
69320                     var inferenceContext = void 0;
69321                     if (candidate.typeParameters) {
69322                         var typeArgumentTypes = void 0;
69323                         if (ts.some(typeArguments)) {
69324                             typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
69325                             if (!typeArgumentTypes) {
69326                                 candidateForTypeArgumentError = candidate;
69327                                 continue;
69328                             }
69329                         }
69330                         else {
69331                             inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
69332                             typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
69333                             argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
69334                         }
69335                         checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
69336                         // If the original signature has a generic rest type, instantiation may produce a
69337                         // signature with different arity and we need to perform another arity check.
69338                         if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
69339                             candidateForArgumentArityError = checkCandidate;
69340                             continue;
69341                         }
69342                     }
69343                     else {
69344                         checkCandidate = candidate;
69345                     }
69346                     if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
69347                         // Give preference to error candidates that have no rest parameters (as they are more specific)
69348                         (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
69349                         continue;
69350                     }
69351                     if (argCheckMode) {
69352                         // If one or more context sensitive arguments were excluded, we start including
69353                         // them now (and keeping do so for any subsequent candidates) and perform a second
69354                         // round of type inference and applicability checking for this particular candidate.
69355                         argCheckMode = 0 /* Normal */;
69356                         if (inferenceContext) {
69357                             var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
69358                             checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
69359                             // If the original signature has a generic rest type, instantiation may produce a
69360                             // signature with different arity and we need to perform another arity check.
69361                             if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
69362                                 candidateForArgumentArityError = checkCandidate;
69363                                 continue;
69364                             }
69365                         }
69366                         if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
69367                             // Give preference to error candidates that have no rest parameters (as they are more specific)
69368                             (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
69369                             continue;
69370                         }
69371                     }
69372                     candidates[candidateIndex] = checkCandidate;
69373                     return checkCandidate;
69374                 }
69375                 return undefined;
69376             }
69377         }
69378         // No signature was applicable. We have already reported the errors for the invalid signature.
69379         function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
69380             ts.Debug.assert(candidates.length > 0); // Else should not have called this.
69381             checkNodeDeferred(node);
69382             // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine.
69383             // Don't do this if there is a `candidatesOutArray`,
69384             // because then we want the chosen best candidate to be one of the overloads, not a combination.
69385             return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
69386                 ? pickLongestCandidateSignature(node, candidates, args)
69387                 : createUnionOfSignaturesForOverloadFailure(candidates);
69388         }
69389         function createUnionOfSignaturesForOverloadFailure(candidates) {
69390             var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; });
69391             var thisParameter;
69392             if (thisParameters.length) {
69393                 thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
69394             }
69395             var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max;
69396             var parameters = [];
69397             var _loop_22 = function (i) {
69398                 var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ?
69399                     i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) :
69400                     i < s.parameters.length ? s.parameters[i] : undefined; });
69401                 ts.Debug.assert(symbols.length !== 0);
69402                 parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); })));
69403             };
69404             for (var i = 0; i < maxNonRestParam; i++) {
69405                 _loop_22(i);
69406             }
69407             var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; });
69408             var flags = 0 /* None */;
69409             if (restParameterSymbols.length !== 0) {
69410                 var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
69411                 parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
69412                 flags |= 1 /* HasRestParameter */;
69413             }
69414             if (candidates.some(signatureHasLiteralTypes)) {
69415                 flags |= 2 /* HasLiteralTypes */;
69416             }
69417             return createSignature(candidates[0].declaration, 
69418             /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
69419             thisParameter, parameters, 
69420             /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), 
69421             /*typePredicate*/ undefined, minArgumentCount, flags);
69422         }
69423         function getNumNonRestParameters(signature) {
69424             var numParams = signature.parameters.length;
69425             return signatureHasRestParameter(signature) ? numParams - 1 : numParams;
69426         }
69427         function createCombinedSymbolFromTypes(sources, types) {
69428             return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */));
69429         }
69430         function createCombinedSymbolForOverloadFailure(sources, type) {
69431             // This function is currently only used for erroneous overloads, so it's good enough to just use the first source.
69432             return createSymbolWithType(ts.first(sources), type);
69433         }
69434         function pickLongestCandidateSignature(node, candidates, args) {
69435             // Pick the longest signature. This way we can get a contextual type for cases like:
69436             //     declare function f(a: { xa: number; xb: number; }, b: number);
69437             //     f({ |
69438             // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like:
69439             //     declare function f<T>(k: keyof T);
69440             //     f<Foo>("
69441             var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount);
69442             var candidate = candidates[bestIndex];
69443             var typeParameters = candidate.typeParameters;
69444             if (!typeParameters) {
69445                 return candidate;
69446             }
69447             var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined;
69448             var instantiated = typeArgumentNodes
69449                 ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node)))
69450                 : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args);
69451             candidates[bestIndex] = instantiated;
69452             return instantiated;
69453         }
69454         function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
69455             var typeArguments = typeArgumentNodes.map(getTypeOfNode);
69456             while (typeArguments.length > typeParameters.length) {
69457                 typeArguments.pop();
69458             }
69459             while (typeArguments.length < typeParameters.length) {
69460                 typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
69461             }
69462             return typeArguments;
69463         }
69464         function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
69465             var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
69466             var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
69467             return createSignatureInstantiation(candidate, typeArgumentTypes);
69468         }
69469         function getLongestCandidateIndex(candidates, argsCount) {
69470             var maxParamsIndex = -1;
69471             var maxParams = -1;
69472             for (var i = 0; i < candidates.length; i++) {
69473                 var candidate = candidates[i];
69474                 var paramCount = getParameterCount(candidate);
69475                 if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
69476                     return i;
69477                 }
69478                 if (paramCount > maxParams) {
69479                     maxParams = paramCount;
69480                     maxParamsIndex = i;
69481                 }
69482             }
69483             return maxParamsIndex;
69484         }
69485         function resolveCallExpression(node, candidatesOutArray, checkMode) {
69486             if (node.expression.kind === 105 /* SuperKeyword */) {
69487                 var superType = checkSuperExpression(node.expression);
69488                 if (isTypeAny(superType)) {
69489                     for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
69490                         var arg = _a[_i];
69491                         checkExpression(arg); // Still visit arguments so they get marked for visibility, etc
69492                     }
69493                     return anySignature;
69494                 }
69495                 if (superType !== errorType) {
69496                     // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated
69497                     // with the type arguments specified in the extends clause.
69498                     var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
69499                     if (baseTypeNode) {
69500                         var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
69501                         return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */);
69502                     }
69503                 }
69504                 return resolveUntypedCall(node);
69505             }
69506             var callChainFlags;
69507             var funcType = checkExpression(node.expression);
69508             if (ts.isCallChain(node)) {
69509                 var nonOptionalType = getOptionalExpressionType(funcType, node.expression);
69510                 callChainFlags = nonOptionalType === funcType ? 0 /* None */ :
69511                     ts.isOutermostOptionalChain(node) ? 16 /* IsOuterCallChain */ :
69512                         8 /* IsInnerCallChain */;
69513                 funcType = nonOptionalType;
69514             }
69515             else {
69516                 callChainFlags = 0 /* None */;
69517             }
69518             funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError);
69519             if (funcType === silentNeverType) {
69520                 return silentNeverSignature;
69521             }
69522             var apparentType = getApparentType(funcType);
69523             if (apparentType === errorType) {
69524                 // Another error has already been reported
69525                 return resolveErrorCall(node);
69526             }
69527             // Technically, this signatures list may be incomplete. We are taking the apparent type,
69528             // but we are not including call signatures that may have been added to the Object or
69529             // Function interface, since they have none by default. This is a bit of a leap of faith
69530             // that the user will not add any.
69531             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
69532             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
69533             // TS 1.0 Spec: 4.12
69534             // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual
69535             // types are provided for the argument expressions, and the result is always of type Any.
69536             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
69537                 // The unknownType indicates that an error already occurred (and was reported).  No
69538                 // need to report another error in this case.
69539                 if (funcType !== errorType && node.typeArguments) {
69540                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
69541                 }
69542                 return resolveUntypedCall(node);
69543             }
69544             // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call.
69545             // TypeScript employs overload resolution in typed function calls in order to support functions
69546             // with multiple call signatures.
69547             if (!callSignatures.length) {
69548                 if (numConstructSignatures) {
69549                     error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
69550                 }
69551                 else {
69552                     var relatedInformation = void 0;
69553                     if (node.arguments.length === 1) {
69554                         var text = ts.getSourceFileOfNode(node).text;
69555                         if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) {
69556                             relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.Are_you_missing_a_semicolon);
69557                         }
69558                     }
69559                     invocationError(node.expression, apparentType, 0 /* Call */, relatedInformation);
69560                 }
69561                 return resolveErrorCall(node);
69562             }
69563             // When a call to a generic function is an argument to an outer call to a generic function for which
69564             // inference is in process, we have a choice to make. If the inner call relies on inferences made from
69565             // its contextual type to its return type, deferring the inner call processing allows the best possible
69566             // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
69567             // the inner call, the inner call should be processed early. There's no sure way to know which choice is
69568             // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
69569             // If no type arguments are specified in the inner call and at least one call signature is generic and
69570             // returns a function type, we choose to defer processing. This narrowly permits function composition
69571             // operators to flow inferences through return types, but otherwise processes calls right away. We
69572             // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
69573             // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
69574             // from which we never make inferences).
69575             if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
69576                 skippedGenericFunction(node, checkMode);
69577                 return resolvingSignature;
69578             }
69579             // If the function is explicitly marked with `@class`, then it must be constructed.
69580             if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
69581                 error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
69582                 return resolveErrorCall(node);
69583             }
69584             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags);
69585         }
69586         function isGenericFunctionReturningFunction(signature) {
69587             return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
69588         }
69589         /**
69590          * TS 1.0 spec: 4.12
69591          * If FuncExpr is of type Any, or of an object type that has no call or construct signatures
69592          * but is a subtype of the Function interface, the call is an untyped function call.
69593          */
69594         function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
69595             // We exclude union types because we may have a union of function types that happen to have no common signatures.
69596             return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
69597                 !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
69598         }
69599         function resolveNewExpression(node, candidatesOutArray, checkMode) {
69600             if (node.arguments && languageVersion < 1 /* ES5 */) {
69601                 var spreadIndex = getSpreadArgumentIndex(node.arguments);
69602                 if (spreadIndex >= 0) {
69603                     error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher);
69604                 }
69605             }
69606             var expressionType = checkNonNullExpression(node.expression);
69607             if (expressionType === silentNeverType) {
69608                 return silentNeverSignature;
69609             }
69610             // If expressionType's apparent type(section 3.8.1) is an object type with one or
69611             // more construct signatures, the expression is processed in the same manner as a
69612             // function call, but using the construct signatures as the initial set of candidate
69613             // signatures for overload resolution. The result type of the function call becomes
69614             // the result type of the operation.
69615             expressionType = getApparentType(expressionType);
69616             if (expressionType === errorType) {
69617                 // Another error has already been reported
69618                 return resolveErrorCall(node);
69619             }
69620             // TS 1.0 spec: 4.11
69621             // If expressionType is of type Any, Args can be any argument
69622             // list and the result of the operation is of type Any.
69623             if (isTypeAny(expressionType)) {
69624                 if (node.typeArguments) {
69625                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
69626                 }
69627                 return resolveUntypedCall(node);
69628             }
69629             // Technically, this signatures list may be incomplete. We are taking the apparent type,
69630             // but we are not including construct signatures that may have been added to the Object or
69631             // Function interface, since they have none by default. This is a bit of a leap of faith
69632             // that the user will not add any.
69633             var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
69634             if (constructSignatures.length) {
69635                 if (!isConstructorAccessible(node, constructSignatures[0])) {
69636                     return resolveErrorCall(node);
69637                 }
69638                 // If the expression is a class of abstract type, or an abstract construct signature,
69639                 // then it cannot be instantiated.
69640                 // In the case of a merged class-module or class-interface declaration,
69641                 // only the class declaration node will have the Abstract flag set.
69642                 if (constructSignatures.some(function (signature) { return signature.flags & 4 /* Abstract */; })) {
69643                     error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
69644                     return resolveErrorCall(node);
69645                 }
69646                 var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol);
69647                 if (valueDecl && ts.hasSyntacticModifier(valueDecl, 128 /* Abstract */)) {
69648                     error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
69649                     return resolveErrorCall(node);
69650                 }
69651                 return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */);
69652             }
69653             // If expressionType's apparent type is an object type with no construct signatures but
69654             // one or more call signatures, the expression is processed as a function call. A compile-time
69655             // error occurs if the result of the function call is not Void. The type of the result of the
69656             // operation is Any. It is an error to have a Void this type.
69657             var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
69658             if (callSignatures.length) {
69659                 var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
69660                 if (!noImplicitAny) {
69661                     if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
69662                         error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
69663                     }
69664                     if (getThisTypeOfSignature(signature) === voidType) {
69665                         error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
69666                     }
69667                 }
69668                 return signature;
69669             }
69670             invocationError(node.expression, expressionType, 1 /* Construct */);
69671             return resolveErrorCall(node);
69672         }
69673         function typeHasProtectedAccessibleBase(target, type) {
69674             var baseTypes = getBaseTypes(type);
69675             if (!ts.length(baseTypes)) {
69676                 return false;
69677             }
69678             var firstBase = baseTypes[0];
69679             if (firstBase.flags & 2097152 /* Intersection */) {
69680                 var types = firstBase.types;
69681                 var mixinFlags = findMixins(types);
69682                 var i = 0;
69683                 for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) {
69684                     var intersectionMember = _a[_i];
69685                     // We want to ignore mixin ctors
69686                     if (!mixinFlags[i]) {
69687                         if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
69688                             if (intersectionMember.symbol === target) {
69689                                 return true;
69690                             }
69691                             if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
69692                                 return true;
69693                             }
69694                         }
69695                     }
69696                     i++;
69697                 }
69698                 return false;
69699             }
69700             if (firstBase.symbol === target) {
69701                 return true;
69702             }
69703             return typeHasProtectedAccessibleBase(target, firstBase);
69704         }
69705         function isConstructorAccessible(node, signature) {
69706             if (!signature || !signature.declaration) {
69707                 return true;
69708             }
69709             var declaration = signature.declaration;
69710             var modifiers = ts.getSelectedEffectiveModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */);
69711             // (1) Public constructors and (2) constructor functions are always accessible.
69712             if (!modifiers || declaration.kind !== 166 /* Constructor */) {
69713                 return true;
69714             }
69715             var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
69716             var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
69717             // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected)
69718             if (!isNodeWithinClass(node, declaringClassDeclaration)) {
69719                 var containingClass = ts.getContainingClass(node);
69720                 if (containingClass && modifiers & 16 /* Protected */) {
69721                     var containingType = getTypeOfNode(containingClass);
69722                     if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
69723                         return true;
69724                     }
69725                 }
69726                 if (modifiers & 8 /* Private */) {
69727                     error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
69728                 }
69729                 if (modifiers & 16 /* Protected */) {
69730                     error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
69731                 }
69732                 return false;
69733             }
69734             return true;
69735         }
69736         function invocationErrorDetails(errorTarget, apparentType, kind) {
69737             var errorInfo;
69738             var isCall = kind === 0 /* Call */;
69739             var awaitedType = getAwaitedType(apparentType);
69740             var maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
69741             if (apparentType.flags & 1048576 /* Union */) {
69742                 var types = apparentType.types;
69743                 var hasSignatures = false;
69744                 for (var _i = 0, types_21 = types; _i < types_21.length; _i++) {
69745                     var constituent = types_21[_i];
69746                     var signatures = getSignaturesOfType(constituent, kind);
69747                     if (signatures.length !== 0) {
69748                         hasSignatures = true;
69749                         if (errorInfo) {
69750                             // Bail early if we already have an error, no chance of "No constituent of type is callable"
69751                             break;
69752                         }
69753                     }
69754                     else {
69755                         // Error on the first non callable constituent only
69756                         if (!errorInfo) {
69757                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
69758                                 ts.Diagnostics.Type_0_has_no_call_signatures :
69759                                 ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(constituent));
69760                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
69761                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_callable :
69762                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_constructable, typeToString(apparentType));
69763                         }
69764                         if (hasSignatures) {
69765                             // Bail early if we already found a siganture, no chance of "No constituent of type is callable"
69766                             break;
69767                         }
69768                     }
69769                 }
69770                 if (!hasSignatures) {
69771                     errorInfo = ts.chainDiagnosticMessages(
69772                     /* detials */ undefined, isCall ?
69773                         ts.Diagnostics.No_constituent_of_type_0_is_callable :
69774                         ts.Diagnostics.No_constituent_of_type_0_is_constructable, typeToString(apparentType));
69775                 }
69776                 if (!errorInfo) {
69777                     errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
69778                         ts.Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other :
69779                         ts.Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, typeToString(apparentType));
69780                 }
69781             }
69782             else {
69783                 errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
69784                     ts.Diagnostics.Type_0_has_no_call_signatures :
69785                     ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(apparentType));
69786             }
69787             var headMessage = isCall ? ts.Diagnostics.This_expression_is_not_callable : ts.Diagnostics.This_expression_is_not_constructable;
69788             // Diagnose get accessors incorrectly called as functions
69789             if (ts.isCallExpression(errorTarget.parent) && errorTarget.parent.arguments.length === 0) {
69790                 var resolvedSymbol = getNodeLinks(errorTarget).resolvedSymbol;
69791                 if (resolvedSymbol && resolvedSymbol.flags & 32768 /* GetAccessor */) {
69792                     headMessage = ts.Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without;
69793                 }
69794             }
69795             return {
69796                 messageChain: ts.chainDiagnosticMessages(errorInfo, headMessage),
69797                 relatedMessage: maybeMissingAwait ? ts.Diagnostics.Did_you_forget_to_use_await : undefined,
69798             };
69799         }
69800         function invocationError(errorTarget, apparentType, kind, relatedInformation) {
69801             var _a = invocationErrorDetails(errorTarget, apparentType, kind), messageChain = _a.messageChain, relatedInfo = _a.relatedMessage;
69802             var diagnostic = ts.createDiagnosticForNodeFromMessageChain(errorTarget, messageChain);
69803             if (relatedInfo) {
69804                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo));
69805             }
69806             if (ts.isCallExpression(errorTarget.parent)) {
69807                 var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_8 = _b.length;
69808                 diagnostic.start = start;
69809                 diagnostic.length = length_8;
69810             }
69811             diagnostics.add(diagnostic);
69812             invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
69813         }
69814         function invocationErrorRecovery(apparentType, kind, diagnostic) {
69815             if (!apparentType.symbol) {
69816                 return;
69817             }
69818             var importNode = getSymbolLinks(apparentType.symbol).originatingImport;
69819             // Create a diagnostic on the originating import if possible onto which we can attach a quickfix
69820             //  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
69821             if (importNode && !ts.isImportCall(importNode)) {
69822                 var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
69823                 if (!sigs || !sigs.length)
69824                     return;
69825                 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));
69826             }
69827         }
69828         function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
69829             var tagType = checkExpression(node.tag);
69830             var apparentType = getApparentType(tagType);
69831             if (apparentType === errorType) {
69832                 // Another error has already been reported
69833                 return resolveErrorCall(node);
69834             }
69835             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
69836             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
69837             if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) {
69838                 return resolveUntypedCall(node);
69839             }
69840             if (!callSignatures.length) {
69841                 if (ts.isArrayLiteralExpression(node.parent)) {
69842                     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);
69843                     diagnostics.add(diagnostic);
69844                     return resolveErrorCall(node);
69845                 }
69846                 invocationError(node.tag, apparentType, 0 /* Call */);
69847                 return resolveErrorCall(node);
69848             }
69849             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
69850         }
69851         /**
69852          * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
69853          */
69854         function getDiagnosticHeadMessageForDecoratorResolution(node) {
69855             switch (node.parent.kind) {
69856                 case 252 /* ClassDeclaration */:
69857                 case 221 /* ClassExpression */:
69858                     return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
69859                 case 160 /* Parameter */:
69860                     return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
69861                 case 163 /* PropertyDeclaration */:
69862                     return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
69863                 case 165 /* MethodDeclaration */:
69864                 case 167 /* GetAccessor */:
69865                 case 168 /* SetAccessor */:
69866                     return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
69867                 default:
69868                     return ts.Debug.fail();
69869             }
69870         }
69871         /**
69872          * Resolves a decorator as if it were a call expression.
69873          */
69874         function resolveDecorator(node, candidatesOutArray, checkMode) {
69875             var funcType = checkExpression(node.expression);
69876             var apparentType = getApparentType(funcType);
69877             if (apparentType === errorType) {
69878                 return resolveErrorCall(node);
69879             }
69880             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
69881             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
69882             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
69883                 return resolveUntypedCall(node);
69884             }
69885             if (isPotentiallyUncalledDecorator(node, callSignatures)) {
69886                 var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false);
69887                 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);
69888                 return resolveErrorCall(node);
69889             }
69890             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
69891             if (!callSignatures.length) {
69892                 var errorDetails = invocationErrorDetails(node.expression, apparentType, 0 /* Call */);
69893                 var messageChain = ts.chainDiagnosticMessages(errorDetails.messageChain, headMessage);
69894                 var diag = ts.createDiagnosticForNodeFromMessageChain(node.expression, messageChain);
69895                 if (errorDetails.relatedMessage) {
69896                     ts.addRelatedInfo(diag, ts.createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
69897                 }
69898                 diagnostics.add(diag);
69899                 invocationErrorRecovery(apparentType, 0 /* Call */, diag);
69900                 return resolveErrorCall(node);
69901             }
69902             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage);
69903         }
69904         function createSignatureForJSXIntrinsic(node, result) {
69905             var namespace = getJsxNamespaceAt(node);
69906             var exports = namespace && getExportsOfSymbol(namespace);
69907             // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration
69908             // file would probably be preferable.
69909             var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* Type */);
69910             var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */, node);
69911             var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
69912             var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props");
69913             parameterSymbol.type = result;
69914             return createSignature(declaration, 
69915             /*typeParameters*/ undefined, 
69916             /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, 
69917             /*returnTypePredicate*/ undefined, 1, 0 /* None */);
69918         }
69919         function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
69920             if (isJsxIntrinsicIdentifier(node.tagName)) {
69921                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
69922                 var fakeSignature = createSignatureForJSXIntrinsic(node, result);
69923                 checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
69924                 if (ts.length(node.typeArguments)) {
69925                     ts.forEach(node.typeArguments, checkSourceElement);
69926                     diagnostics.add(ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), node.typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, 0, ts.length(node.typeArguments)));
69927                 }
69928                 return fakeSignature;
69929             }
69930             var exprTypes = checkExpression(node.tagName);
69931             var apparentType = getApparentType(exprTypes);
69932             if (apparentType === errorType) {
69933                 return resolveErrorCall(node);
69934             }
69935             var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
69936             if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
69937                 return resolveUntypedCall(node);
69938             }
69939             if (signatures.length === 0) {
69940                 // We found no signatures at all, which is an error
69941                 error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
69942                 return resolveErrorCall(node);
69943             }
69944             return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */);
69945         }
69946         /**
69947          * Sometimes, we have a decorator that could accept zero arguments,
69948          * but is receiving too many arguments as part of the decorator invocation.
69949          * In those cases, a user may have meant to *call* the expression before using it as a decorator.
69950          */
69951         function isPotentiallyUncalledDecorator(decorator, signatures) {
69952             return signatures.length && ts.every(signatures, function (signature) {
69953                 return signature.minArgumentCount === 0 &&
69954                     !signatureHasRestParameter(signature) &&
69955                     signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
69956             });
69957         }
69958         function resolveSignature(node, candidatesOutArray, checkMode) {
69959             switch (node.kind) {
69960                 case 203 /* CallExpression */:
69961                     return resolveCallExpression(node, candidatesOutArray, checkMode);
69962                 case 204 /* NewExpression */:
69963                     return resolveNewExpression(node, candidatesOutArray, checkMode);
69964                 case 205 /* TaggedTemplateExpression */:
69965                     return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
69966                 case 161 /* Decorator */:
69967                     return resolveDecorator(node, candidatesOutArray, checkMode);
69968                 case 275 /* JsxOpeningElement */:
69969                 case 274 /* JsxSelfClosingElement */:
69970                     return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
69971             }
69972             throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
69973         }
69974         /**
69975          * Resolve a signature of a given call-like expression.
69976          * @param node a call-like expression to try resolve a signature for
69977          * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
69978          *                           the function will fill it up with appropriate candidate signatures
69979          * @return a signature of the call-like expression or undefined if one can't be found
69980          */
69981         function getResolvedSignature(node, candidatesOutArray, checkMode) {
69982             var links = getNodeLinks(node);
69983             // If getResolvedSignature has already been called, we will have cached the resolvedSignature.
69984             // However, it is possible that either candidatesOutArray was not passed in the first time,
69985             // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work
69986             // to correctly fill the candidatesOutArray.
69987             var cached = links.resolvedSignature;
69988             if (cached && cached !== resolvingSignature && !candidatesOutArray) {
69989                 return cached;
69990             }
69991             links.resolvedSignature = resolvingSignature;
69992             var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
69993             // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
69994             // resolution should be deferred.
69995             if (result !== resolvingSignature) {
69996                 // If signature resolution originated in control flow type analysis (for example to compute the
69997                 // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
69998                 // types from the control flow analysis.
69999                 links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
70000             }
70001             return result;
70002         }
70003         /**
70004          * Indicates whether a declaration can be treated as a constructor in a JavaScript
70005          * file.
70006          */
70007         function isJSConstructor(node) {
70008             var _a;
70009             if (!node || !ts.isInJSFile(node)) {
70010                 return false;
70011             }
70012             var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node :
70013                 ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer :
70014                     undefined;
70015             if (func) {
70016                 // If the node has a @class tag, treat it like a constructor.
70017                 if (ts.getJSDocClassTag(node))
70018                     return true;
70019                 // If the symbol of the node has members, treat it like a constructor.
70020                 var symbol = getSymbolOfNode(func);
70021                 return !!((_a = symbol === null || symbol === void 0 ? void 0 : symbol.members) === null || _a === void 0 ? void 0 : _a.size);
70022             }
70023             return false;
70024         }
70025         function mergeJSSymbols(target, source) {
70026             var _a, _b;
70027             if (source) {
70028                 var links = getSymbolLinks(source);
70029                 if (!links.inferredClassSymbol || !links.inferredClassSymbol.has(getSymbolId(target))) {
70030                     var inferred = ts.isTransientSymbol(target) ? target : cloneSymbol(target);
70031                     inferred.exports = inferred.exports || ts.createSymbolTable();
70032                     inferred.members = inferred.members || ts.createSymbolTable();
70033                     inferred.flags |= source.flags & 32 /* Class */;
70034                     if ((_a = source.exports) === null || _a === void 0 ? void 0 : _a.size) {
70035                         mergeSymbolTable(inferred.exports, source.exports);
70036                     }
70037                     if ((_b = source.members) === null || _b === void 0 ? void 0 : _b.size) {
70038                         mergeSymbolTable(inferred.members, source.members);
70039                     }
70040                     (links.inferredClassSymbol || (links.inferredClassSymbol = new ts.Map())).set(getSymbolId(inferred), inferred);
70041                     return inferred;
70042                 }
70043                 return links.inferredClassSymbol.get(getSymbolId(target));
70044             }
70045         }
70046         function getAssignedClassSymbol(decl) {
70047             var _a;
70048             var assignmentSymbol = decl && getSymbolOfExpando(decl, /*allowDeclaration*/ true);
70049             var prototype = (_a = assignmentSymbol === null || assignmentSymbol === void 0 ? void 0 : assignmentSymbol.exports) === null || _a === void 0 ? void 0 : _a.get("prototype");
70050             var init = (prototype === null || prototype === void 0 ? void 0 : prototype.valueDeclaration) && getAssignedJSPrototype(prototype.valueDeclaration);
70051             return init ? getSymbolOfNode(init) : undefined;
70052         }
70053         function getSymbolOfExpando(node, allowDeclaration) {
70054             if (!node.parent) {
70055                 return undefined;
70056             }
70057             var name;
70058             var decl;
70059             if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) {
70060                 if (!ts.isInJSFile(node) && !(ts.isVarConst(node.parent) && ts.isFunctionLikeDeclaration(node))) {
70061                     return undefined;
70062                 }
70063                 name = node.parent.name;
70064                 decl = node.parent;
70065             }
70066             else if (ts.isBinaryExpression(node.parent)) {
70067                 var parentNode = node.parent;
70068                 var parentNodeOperator = node.parent.operatorToken.kind;
70069                 if (parentNodeOperator === 62 /* EqualsToken */ && (allowDeclaration || parentNode.right === node)) {
70070                     name = parentNode.left;
70071                     decl = name;
70072                 }
70073                 else if (parentNodeOperator === 56 /* BarBarToken */ || parentNodeOperator === 60 /* QuestionQuestionToken */) {
70074                     if (ts.isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) {
70075                         name = parentNode.parent.name;
70076                         decl = parentNode.parent;
70077                     }
70078                     else if (ts.isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 62 /* EqualsToken */ && (allowDeclaration || parentNode.parent.right === parentNode)) {
70079                         name = parentNode.parent.left;
70080                         decl = name;
70081                     }
70082                     if (!name || !ts.isBindableStaticNameExpression(name) || !ts.isSameEntityName(name, parentNode.left)) {
70083                         return undefined;
70084                     }
70085                 }
70086             }
70087             else if (allowDeclaration && ts.isFunctionDeclaration(node)) {
70088                 name = node.name;
70089                 decl = node;
70090             }
70091             if (!decl || !name || (!allowDeclaration && !ts.getExpandoInitializer(node, ts.isPrototypeAccess(name)))) {
70092                 return undefined;
70093             }
70094             return getSymbolOfNode(decl);
70095         }
70096         function getAssignedJSPrototype(node) {
70097             if (!node.parent) {
70098                 return false;
70099             }
70100             var parent = node.parent;
70101             while (parent && parent.kind === 201 /* PropertyAccessExpression */) {
70102                 parent = parent.parent;
70103             }
70104             if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) {
70105                 var right = ts.getInitializerOfBinaryExpression(parent);
70106                 return ts.isObjectLiteralExpression(right) && right;
70107             }
70108         }
70109         /**
70110          * Syntactically and semantically checks a call or new expression.
70111          * @param node The call/new expression to be checked.
70112          * @returns On success, the expression's signature's return type. On failure, anyType.
70113          */
70114         function checkCallExpression(node, checkMode) {
70115             var _a;
70116             if (!checkGrammarTypeArguments(node, node.typeArguments))
70117                 checkGrammarArguments(node.arguments);
70118             var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
70119             if (signature === resolvingSignature) {
70120                 // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
70121                 // returns a function type. We defer checking and return nonInferrableType.
70122                 return nonInferrableType;
70123             }
70124             checkDeprecatedSignature(signature, node);
70125             if (node.expression.kind === 105 /* SuperKeyword */) {
70126                 return voidType;
70127             }
70128             if (node.kind === 204 /* NewExpression */) {
70129                 var declaration = signature.declaration;
70130                 if (declaration &&
70131                     declaration.kind !== 166 /* Constructor */ &&
70132                     declaration.kind !== 170 /* ConstructSignature */ &&
70133                     declaration.kind !== 175 /* ConstructorType */ &&
70134                     !ts.isJSDocConstructSignature(declaration) &&
70135                     !isJSConstructor(declaration)) {
70136                     // When resolved signature is a call signature (and not a construct signature) the result type is any
70137                     if (noImplicitAny) {
70138                         error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
70139                     }
70140                     return anyType;
70141                 }
70142             }
70143             // In JavaScript files, calls to any identifier 'require' are treated as external module imports
70144             if (ts.isInJSFile(node) && isCommonJsRequire(node)) {
70145                 return resolveExternalModuleTypeByLiteral(node.arguments[0]);
70146             }
70147             var returnType = getReturnTypeOfSignature(signature);
70148             // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property
70149             // as a fresh unique symbol literal type.
70150             if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
70151                 return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent));
70152             }
70153             if (node.kind === 203 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 233 /* ExpressionStatement */ &&
70154                 returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) {
70155                 if (!ts.isDottedName(node.expression)) {
70156                     error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
70157                 }
70158                 else if (!getEffectsSignature(node)) {
70159                     var diagnostic = error(node.expression, ts.Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation);
70160                     getTypeOfDottedName(node.expression, diagnostic);
70161                 }
70162             }
70163             if (ts.isInJSFile(node)) {
70164                 var jsSymbol = getSymbolOfExpando(node, /*allowDeclaration*/ false);
70165                 if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) {
70166                     var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
70167                     jsAssignmentType.objectFlags |= 16384 /* JSLiteral */;
70168                     return getIntersectionType([returnType, jsAssignmentType]);
70169                 }
70170             }
70171             return returnType;
70172         }
70173         function checkDeprecatedSignature(signature, node) {
70174             if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) {
70175                 var suggestionNode = getDeprecatedSuggestionNode(node);
70176                 var name = ts.tryGetPropertyAccessOrIdentifierToString(ts.getInvokedExpression(node));
70177                 addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature));
70178             }
70179         }
70180         function getDeprecatedSuggestionNode(node) {
70181             node = ts.skipParentheses(node);
70182             switch (node.kind) {
70183                 case 203 /* CallExpression */:
70184                 case 161 /* Decorator */:
70185                 case 204 /* NewExpression */:
70186                     return getDeprecatedSuggestionNode(node.expression);
70187                 case 205 /* TaggedTemplateExpression */:
70188                     return getDeprecatedSuggestionNode(node.tag);
70189                 case 275 /* JsxOpeningElement */:
70190                 case 274 /* JsxSelfClosingElement */:
70191                     return getDeprecatedSuggestionNode(node.tagName);
70192                 case 202 /* ElementAccessExpression */:
70193                     return node.argumentExpression;
70194                 case 201 /* PropertyAccessExpression */:
70195                     return node.name;
70196                 case 173 /* TypeReference */:
70197                     var typeReference = node;
70198                     return ts.isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference;
70199                 default:
70200                     return node;
70201             }
70202         }
70203         function isSymbolOrSymbolForCall(node) {
70204             if (!ts.isCallExpression(node))
70205                 return false;
70206             var left = node.expression;
70207             if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") {
70208                 left = left.expression;
70209             }
70210             if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") {
70211                 return false;
70212             }
70213             // make sure `Symbol` is the global symbol
70214             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false);
70215             if (!globalESSymbol) {
70216                 return false;
70217             }
70218             return globalESSymbol === resolveName(left, "Symbol", 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
70219         }
70220         function checkImportCallExpression(node) {
70221             // Check grammar of dynamic import
70222             if (!checkGrammarArguments(node.arguments))
70223                 checkGrammarImportCallExpression(node);
70224             if (node.arguments.length === 0) {
70225                 return createPromiseReturnType(node, anyType);
70226             }
70227             var specifier = node.arguments[0];
70228             var specifierType = checkExpressionCached(specifier);
70229             // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion
70230             for (var i = 1; i < node.arguments.length; ++i) {
70231                 checkExpressionCached(node.arguments[i]);
70232             }
70233             if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
70234                 error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
70235             }
70236             // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal
70237             var moduleSymbol = resolveExternalModuleName(node, specifier);
70238             if (moduleSymbol) {
70239                 var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false);
70240                 if (esModuleSymbol) {
70241                     return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol));
70242                 }
70243             }
70244             return createPromiseReturnType(node, anyType);
70245         }
70246         function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) {
70247             if (allowSyntheticDefaultImports && type && type !== errorType) {
70248                 var synthType = type;
70249                 if (!synthType.syntheticType) {
70250                     var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
70251                     var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
70252                     if (hasSyntheticDefault) {
70253                         var memberTable = ts.createSymbolTable();
70254                         var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
70255                         newSymbol.parent = originalSymbol;
70256                         newSymbol.nameType = getLiteralType("default");
70257                         newSymbol.target = resolveSymbol(symbol);
70258                         memberTable.set("default" /* Default */, newSymbol);
70259                         var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
70260                         var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
70261                         anonymousSymbol.type = defaultContainingObject;
70262                         synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
70263                     }
70264                     else {
70265                         synthType.syntheticType = type;
70266                     }
70267                 }
70268                 return synthType.syntheticType;
70269             }
70270             return type;
70271         }
70272         function isCommonJsRequire(node) {
70273             if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
70274                 return false;
70275             }
70276             // Make sure require is not a local function
70277             if (!ts.isIdentifier(node.expression))
70278                 return ts.Debug.fail();
70279             var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
70280             if (resolvedRequire === requireSymbol) {
70281                 return true;
70282             }
70283             // project includes symbol named 'require' - make sure that it is ambient and local non-alias
70284             if (resolvedRequire.flags & 2097152 /* Alias */) {
70285                 return false;
70286             }
70287             var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */
70288                 ? 251 /* FunctionDeclaration */
70289                 : resolvedRequire.flags & 3 /* Variable */
70290                     ? 249 /* VariableDeclaration */
70291                     : 0 /* Unknown */;
70292             if (targetDeclarationKind !== 0 /* Unknown */) {
70293                 var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
70294                 // function/variable declaration should be ambient
70295                 return !!decl && !!(decl.flags & 8388608 /* Ambient */);
70296             }
70297             return false;
70298         }
70299         function checkTaggedTemplateExpression(node) {
70300             if (!checkGrammarTaggedTemplateChain(node))
70301                 checkGrammarTypeArguments(node, node.typeArguments);
70302             if (languageVersion < 2 /* ES2015 */) {
70303                 checkExternalEmitHelpers(node, 262144 /* MakeTemplateObject */);
70304             }
70305             var signature = getResolvedSignature(node);
70306             checkDeprecatedSignature(signature, node);
70307             return getReturnTypeOfSignature(signature);
70308         }
70309         function checkAssertion(node) {
70310             return checkAssertionWorker(node, node.type, node.expression);
70311         }
70312         function isValidConstAssertionArgument(node) {
70313             switch (node.kind) {
70314                 case 10 /* StringLiteral */:
70315                 case 14 /* NoSubstitutionTemplateLiteral */:
70316                 case 8 /* NumericLiteral */:
70317                 case 9 /* BigIntLiteral */:
70318                 case 109 /* TrueKeyword */:
70319                 case 94 /* FalseKeyword */:
70320                 case 199 /* ArrayLiteralExpression */:
70321                 case 200 /* ObjectLiteralExpression */:
70322                 case 218 /* TemplateExpression */:
70323                     return true;
70324                 case 207 /* ParenthesizedExpression */:
70325                     return isValidConstAssertionArgument(node.expression);
70326                 case 214 /* PrefixUnaryExpression */:
70327                     var op = node.operator;
70328                     var arg = node.operand;
70329                     return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
70330                         op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
70331                 case 201 /* PropertyAccessExpression */:
70332                 case 202 /* ElementAccessExpression */:
70333                     var expr = node.expression;
70334                     if (ts.isIdentifier(expr)) {
70335                         var symbol = getSymbolAtLocation(expr);
70336                         if (symbol && symbol.flags & 2097152 /* Alias */) {
70337                             symbol = resolveAlias(symbol);
70338                         }
70339                         return !!(symbol && (symbol.flags & 384 /* Enum */) && getEnumKind(symbol) === 1 /* Literal */);
70340                     }
70341             }
70342             return false;
70343         }
70344         function checkAssertionWorker(errNode, type, expression, checkMode) {
70345             var exprType = checkExpression(expression, checkMode);
70346             if (ts.isConstTypeReference(type)) {
70347                 if (!isValidConstAssertionArgument(expression)) {
70348                     error(expression, ts.Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals);
70349                 }
70350                 return getRegularTypeOfLiteralType(exprType);
70351             }
70352             checkSourceElement(type);
70353             exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
70354             var targetType = getTypeFromTypeNode(type);
70355             if (produceDiagnostics && targetType !== errorType) {
70356                 var widenedType = getWidenedType(exprType);
70357                 if (!isTypeComparableTo(targetType, widenedType)) {
70358                     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);
70359                 }
70360             }
70361             return targetType;
70362         }
70363         function checkNonNullChain(node) {
70364             var leftType = checkExpression(node.expression);
70365             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
70366             return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType);
70367         }
70368         function checkNonNullAssertion(node) {
70369             return node.flags & 32 /* OptionalChain */ ? checkNonNullChain(node) :
70370                 getNonNullableType(checkExpression(node.expression));
70371         }
70372         function checkMetaProperty(node) {
70373             checkGrammarMetaProperty(node);
70374             if (node.keywordToken === 102 /* NewKeyword */) {
70375                 return checkNewTargetMetaProperty(node);
70376             }
70377             if (node.keywordToken === 99 /* ImportKeyword */) {
70378                 return checkImportMetaProperty(node);
70379             }
70380             return ts.Debug.assertNever(node.keywordToken);
70381         }
70382         function checkNewTargetMetaProperty(node) {
70383             var container = ts.getNewTargetContainer(node);
70384             if (!container) {
70385                 error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
70386                 return errorType;
70387             }
70388             else if (container.kind === 166 /* Constructor */) {
70389                 var symbol = getSymbolOfNode(container.parent);
70390                 return getTypeOfSymbol(symbol);
70391             }
70392             else {
70393                 var symbol = getSymbolOfNode(container);
70394                 return getTypeOfSymbol(symbol);
70395             }
70396         }
70397         function checkImportMetaProperty(node) {
70398             if (moduleKind !== ts.ModuleKind.ES2020 && moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) {
70399                 error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system);
70400             }
70401             var file = ts.getSourceFileOfNode(node);
70402             ts.Debug.assert(!!(file.flags & 2097152 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag.");
70403             ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module.");
70404             return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
70405         }
70406         function getTypeOfParameter(symbol) {
70407             var type = getTypeOfSymbol(symbol);
70408             if (strictNullChecks) {
70409                 var declaration = symbol.valueDeclaration;
70410                 if (declaration && ts.hasInitializer(declaration)) {
70411                     return getOptionalType(type);
70412                 }
70413             }
70414             return type;
70415         }
70416         function getTupleElementLabel(d) {
70417             ts.Debug.assert(ts.isIdentifier(d.name)); // Parameter declarations could be binding patterns, but we only allow identifier names
70418             return d.name.escapedText;
70419         }
70420         function getParameterNameAtPosition(signature, pos, overrideRestType) {
70421             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
70422             if (pos < paramCount) {
70423                 return signature.parameters[pos].escapedName;
70424             }
70425             var restParameter = signature.parameters[paramCount] || unknownSymbol;
70426             var restType = overrideRestType || getTypeOfSymbol(restParameter);
70427             if (isTupleType(restType)) {
70428                 var associatedNames = restType.target.labeledElementDeclarations;
70429                 var index = pos - paramCount;
70430                 return associatedNames && getTupleElementLabel(associatedNames[index]) || restParameter.escapedName + "_" + index;
70431             }
70432             return restParameter.escapedName;
70433         }
70434         function isValidDeclarationForTupleLabel(d) {
70435             return d.kind === 192 /* NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name));
70436         }
70437         function getNameableDeclarationAtPosition(signature, pos) {
70438             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
70439             if (pos < paramCount) {
70440                 var decl = signature.parameters[pos].valueDeclaration;
70441                 return decl && isValidDeclarationForTupleLabel(decl) ? decl : undefined;
70442             }
70443             var restParameter = signature.parameters[paramCount] || unknownSymbol;
70444             var restType = getTypeOfSymbol(restParameter);
70445             if (isTupleType(restType)) {
70446                 var associatedNames = restType.target.labeledElementDeclarations;
70447                 var index = pos - paramCount;
70448                 return associatedNames && associatedNames[index];
70449             }
70450             return restParameter.valueDeclaration && isValidDeclarationForTupleLabel(restParameter.valueDeclaration) ? restParameter.valueDeclaration : undefined;
70451         }
70452         function getTypeAtPosition(signature, pos) {
70453             return tryGetTypeAtPosition(signature, pos) || anyType;
70454         }
70455         function tryGetTypeAtPosition(signature, pos) {
70456             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
70457             if (pos < paramCount) {
70458                 return getTypeOfParameter(signature.parameters[pos]);
70459             }
70460             if (signatureHasRestParameter(signature)) {
70461                 // We want to return the value undefined for an out of bounds parameter position,
70462                 // so we need to check bounds here before calling getIndexedAccessType (which
70463                 // otherwise would return the type 'undefined').
70464                 var restType = getTypeOfSymbol(signature.parameters[paramCount]);
70465                 var index = pos - paramCount;
70466                 if (!isTupleType(restType) || restType.target.hasRestElement || index < restType.target.fixedLength) {
70467                     return getIndexedAccessType(restType, getLiteralType(index));
70468                 }
70469             }
70470             return undefined;
70471         }
70472         function getRestTypeAtPosition(source, pos) {
70473             var parameterCount = getParameterCount(source);
70474             var minArgumentCount = getMinArgumentCount(source);
70475             var restType = getEffectiveRestType(source);
70476             if (restType && pos >= parameterCount - 1) {
70477                 return pos === parameterCount - 1 ? restType : createArrayType(getIndexedAccessType(restType, numberType));
70478             }
70479             var types = [];
70480             var flags = [];
70481             var names = [];
70482             for (var i = pos; i < parameterCount; i++) {
70483                 if (!restType || i < parameterCount - 1) {
70484                     types.push(getTypeAtPosition(source, i));
70485                     flags.push(i < minArgumentCount ? 1 /* Required */ : 2 /* Optional */);
70486                 }
70487                 else {
70488                     types.push(restType);
70489                     flags.push(8 /* Variadic */);
70490                 }
70491                 var name = getNameableDeclarationAtPosition(source, i);
70492                 if (name) {
70493                     names.push(name);
70494                 }
70495             }
70496             return createTupleType(types, flags, /*readonly*/ false, ts.length(names) === ts.length(types) ? names : undefined);
70497         }
70498         // Return the number of parameters in a signature. The rest parameter, if present, counts as one
70499         // parameter. For example, the parameter count of (x: number, y: number, ...z: string[]) is 3 and
70500         // the parameter count of (x: number, ...args: [number, ...string[], boolean])) is also 3. In the
70501         // latter example, the effective rest type is [...string[], boolean].
70502         function getParameterCount(signature) {
70503             var length = signature.parameters.length;
70504             if (signatureHasRestParameter(signature)) {
70505                 var restType = getTypeOfSymbol(signature.parameters[length - 1]);
70506                 if (isTupleType(restType)) {
70507                     return length + restType.target.fixedLength - (restType.target.hasRestElement ? 0 : 1);
70508                 }
70509             }
70510             return length;
70511         }
70512         function getMinArgumentCount(signature, flags) {
70513             var strongArityForUntypedJS = flags & 1 /* StrongArityForUntypedJS */;
70514             var voidIsNonOptional = flags & 2 /* VoidIsNonOptional */;
70515             if (voidIsNonOptional || signature.resolvedMinArgumentCount === undefined) {
70516                 var minArgumentCount = void 0;
70517                 if (signatureHasRestParameter(signature)) {
70518                     var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
70519                     if (isTupleType(restType)) {
70520                         var firstOptionalIndex = ts.findIndex(restType.target.elementFlags, function (f) { return !(f & 1 /* Required */); });
70521                         var requiredCount = firstOptionalIndex < 0 ? restType.target.fixedLength : firstOptionalIndex;
70522                         if (requiredCount > 0) {
70523                             minArgumentCount = signature.parameters.length - 1 + requiredCount;
70524                         }
70525                     }
70526                 }
70527                 if (minArgumentCount === undefined) {
70528                     if (!strongArityForUntypedJS && signature.flags & 32 /* IsUntypedSignatureInJSFile */) {
70529                         return 0;
70530                     }
70531                     minArgumentCount = signature.minArgumentCount;
70532                 }
70533                 if (voidIsNonOptional) {
70534                     return minArgumentCount;
70535                 }
70536                 for (var i = minArgumentCount - 1; i >= 0; i--) {
70537                     var type = getTypeAtPosition(signature, i);
70538                     if (filterType(type, acceptsVoid).flags & 131072 /* Never */) {
70539                         break;
70540                     }
70541                     minArgumentCount = i;
70542                 }
70543                 signature.resolvedMinArgumentCount = minArgumentCount;
70544             }
70545             return signature.resolvedMinArgumentCount;
70546         }
70547         function hasEffectiveRestParameter(signature) {
70548             if (signatureHasRestParameter(signature)) {
70549                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
70550                 return !isTupleType(restType) || restType.target.hasRestElement;
70551             }
70552             return false;
70553         }
70554         function getEffectiveRestType(signature) {
70555             if (signatureHasRestParameter(signature)) {
70556                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
70557                 if (!isTupleType(restType)) {
70558                     return restType;
70559                 }
70560                 if (restType.target.hasRestElement) {
70561                     return sliceTupleType(restType, restType.target.fixedLength);
70562                 }
70563             }
70564             return undefined;
70565         }
70566         function getNonArrayRestType(signature) {
70567             var restType = getEffectiveRestType(signature);
70568             return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined;
70569         }
70570         function getTypeOfFirstParameterOfSignature(signature) {
70571             return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
70572         }
70573         function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
70574             return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
70575         }
70576         function inferFromAnnotatedParameters(signature, context, inferenceContext) {
70577             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
70578             for (var i = 0; i < len; i++) {
70579                 var declaration = signature.parameters[i].valueDeclaration;
70580                 if (declaration.type) {
70581                     var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
70582                     if (typeNode) {
70583                         inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
70584                     }
70585                 }
70586             }
70587             var restType = getEffectiveRestType(context);
70588             if (restType && restType.flags & 262144 /* TypeParameter */) {
70589                 // The contextual signature has a generic rest parameter. We first instantiate the contextual
70590                 // signature (without fixing type parameters) and assign types to contextually typed parameters.
70591                 var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
70592                 assignContextualParameterTypes(signature, instantiatedContext);
70593                 // We then infer from a tuple type representing the parameters that correspond to the contextual
70594                 // rest parameter.
70595                 var restPos = getParameterCount(context) - 1;
70596                 inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
70597             }
70598         }
70599         function assignContextualParameterTypes(signature, context) {
70600             signature.typeParameters = context.typeParameters;
70601             if (context.thisParameter) {
70602                 var parameter = signature.thisParameter;
70603                 if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
70604                     if (!parameter) {
70605                         signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
70606                     }
70607                     assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
70608                 }
70609             }
70610             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
70611             for (var i = 0; i < len; i++) {
70612                 var parameter = signature.parameters[i];
70613                 if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
70614                     var contextualParameterType = tryGetTypeAtPosition(context, i);
70615                     assignParameterType(parameter, contextualParameterType);
70616                 }
70617             }
70618             if (signatureHasRestParameter(signature)) {
70619                 // parameter might be a transient symbol generated by use of `arguments` in the function body.
70620                 var parameter = ts.last(signature.parameters);
70621                 if (ts.isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
70622                     var contextualParameterType = getRestTypeAtPosition(context, len);
70623                     assignParameterType(parameter, contextualParameterType);
70624                 }
70625             }
70626         }
70627         function assignNonContextualParameterTypes(signature) {
70628             if (signature.thisParameter) {
70629                 assignParameterType(signature.thisParameter);
70630             }
70631             for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
70632                 var parameter = _a[_i];
70633                 assignParameterType(parameter);
70634             }
70635         }
70636         function assignParameterType(parameter, type) {
70637             var links = getSymbolLinks(parameter);
70638             if (!links.type) {
70639                 var declaration = parameter.valueDeclaration;
70640                 links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
70641                 if (declaration.name.kind !== 78 /* Identifier */) {
70642                     // if inference didn't come up with anything but unknown, fall back to the binding pattern if present.
70643                     if (links.type === unknownType) {
70644                         links.type = getTypeFromBindingPattern(declaration.name);
70645                     }
70646                     assignBindingElementTypes(declaration.name);
70647                 }
70648             }
70649         }
70650         // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push
70651         // the destructured type into the contained binding elements.
70652         function assignBindingElementTypes(pattern) {
70653             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
70654                 var element = _a[_i];
70655                 if (!ts.isOmittedExpression(element)) {
70656                     if (element.name.kind === 78 /* Identifier */) {
70657                         getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);
70658                     }
70659                     else {
70660                         assignBindingElementTypes(element.name);
70661                     }
70662                 }
70663             }
70664         }
70665         function createPromiseType(promisedType) {
70666             // creates a `Promise<T>` type where `T` is the promisedType argument
70667             var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
70668             if (globalPromiseType !== emptyGenericType) {
70669                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
70670                 promisedType = getAwaitedType(promisedType) || unknownType;
70671                 return createTypeReference(globalPromiseType, [promisedType]);
70672             }
70673             return unknownType;
70674         }
70675         function createPromiseLikeType(promisedType) {
70676             // creates a `PromiseLike<T>` type where `T` is the promisedType argument
70677             var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true);
70678             if (globalPromiseLikeType !== emptyGenericType) {
70679                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
70680                 promisedType = getAwaitedType(promisedType) || unknownType;
70681                 return createTypeReference(globalPromiseLikeType, [promisedType]);
70682             }
70683             return unknownType;
70684         }
70685         function createPromiseReturnType(func, promisedType) {
70686             var promiseType = createPromiseType(promisedType);
70687             if (promiseType === unknownType) {
70688                 error(func, ts.isImportCall(func) ?
70689                     ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option :
70690                     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);
70691                 return errorType;
70692             }
70693             else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
70694                 error(func, ts.isImportCall(func) ?
70695                     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 :
70696                     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);
70697             }
70698             return promiseType;
70699         }
70700         function getReturnTypeFromBody(func, checkMode) {
70701             if (!func.body) {
70702                 return errorType;
70703             }
70704             var functionFlags = ts.getFunctionFlags(func);
70705             var isAsync = (functionFlags & 2 /* Async */) !== 0;
70706             var isGenerator = (functionFlags & 1 /* Generator */) !== 0;
70707             var returnType;
70708             var yieldType;
70709             var nextType;
70710             var fallbackReturnType = voidType;
70711             if (func.body.kind !== 230 /* Block */) { // Async or normal arrow function
70712                 returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
70713                 if (isAsync) {
70714                     // From within an async function you can return either a non-promise value or a promise. Any
70715                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
70716                     // return type of the body should be unwrapped to its awaited type, which we will wrap in
70717                     // the native Promise<T> type later in this function.
70718                     returnType = checkAwaitedType(returnType, /*errorNode*/ func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
70719                 }
70720             }
70721             else if (isGenerator) { // Generator or AsyncGenerator function
70722                 var returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode);
70723                 if (!returnTypes) {
70724                     fallbackReturnType = neverType;
70725                 }
70726                 else if (returnTypes.length > 0) {
70727                     returnType = getUnionType(returnTypes, 2 /* Subtype */);
70728                 }
70729                 var _a = checkAndAggregateYieldOperandTypes(func, checkMode), yieldTypes = _a.yieldTypes, nextTypes = _a.nextTypes;
70730                 yieldType = ts.some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : undefined;
70731                 nextType = ts.some(nextTypes) ? getIntersectionType(nextTypes) : undefined;
70732             }
70733             else { // Async or normal function
70734                 var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
70735                 if (!types) {
70736                     // For an async function, the return type will not be never, but rather a Promise for never.
70737                     return functionFlags & 2 /* Async */
70738                         ? createPromiseReturnType(func, neverType) // Async function
70739                         : neverType; // Normal function
70740                 }
70741                 if (types.length === 0) {
70742                     // For an async function, the return type will not be void, but rather a Promise for void.
70743                     return functionFlags & 2 /* Async */
70744                         ? createPromiseReturnType(func, voidType) // Async function
70745                         : voidType; // Normal function
70746                 }
70747                 // Return a union of the return expression types.
70748                 returnType = getUnionType(types, 2 /* Subtype */);
70749             }
70750             if (returnType || yieldType || nextType) {
70751                 if (yieldType)
70752                     reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */);
70753                 if (returnType)
70754                     reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */);
70755                 if (nextType)
70756                     reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */);
70757                 if (returnType && isUnitType(returnType) ||
70758                     yieldType && isUnitType(yieldType) ||
70759                     nextType && isUnitType(nextType)) {
70760                     var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
70761                     var contextualType = !contextualSignature ? undefined :
70762                         contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType :
70763                             instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func);
70764                     if (isGenerator) {
70765                         yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync);
70766                         returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync);
70767                         nextType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(nextType, contextualType, 2 /* Next */, isAsync);
70768                     }
70769                     else {
70770                         returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync);
70771                     }
70772                 }
70773                 if (yieldType)
70774                     yieldType = getWidenedType(yieldType);
70775                 if (returnType)
70776                     returnType = getWidenedType(returnType);
70777                 if (nextType)
70778                     nextType = getWidenedType(nextType);
70779             }
70780             if (isGenerator) {
70781                 return createGeneratorReturnType(yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(2 /* Next */, func) || unknownType, isAsync);
70782             }
70783             else {
70784                 // From within an async function you can return either a non-promise value or a promise. Any
70785                 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
70786                 // return type of the body is awaited type of the body, wrapped in a native Promise<T> type.
70787                 return isAsync
70788                     ? createPromiseType(returnType || fallbackReturnType)
70789                     : returnType || fallbackReturnType;
70790             }
70791         }
70792         function createGeneratorReturnType(yieldType, returnType, nextType, isAsyncGenerator) {
70793             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
70794             var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
70795             yieldType = resolver.resolveIterationType(yieldType, /*errorNode*/ undefined) || unknownType;
70796             returnType = resolver.resolveIterationType(returnType, /*errorNode*/ undefined) || unknownType;
70797             nextType = resolver.resolveIterationType(nextType, /*errorNode*/ undefined) || unknownType;
70798             if (globalGeneratorType === emptyGenericType) {
70799                 // Fall back to the global IterableIterator if returnType is assignable to the expected return iteration
70800                 // type of IterableIterator, and the expected next iteration type of IterableIterator is assignable to
70801                 // nextType.
70802                 var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
70803                 var iterationTypes = globalType !== emptyGenericType ? getIterationTypesOfGlobalIterableType(globalType, resolver) : undefined;
70804                 var iterableIteratorReturnType = iterationTypes ? iterationTypes.returnType : anyType;
70805                 var iterableIteratorNextType = iterationTypes ? iterationTypes.nextType : undefinedType;
70806                 if (isTypeAssignableTo(returnType, iterableIteratorReturnType) &&
70807                     isTypeAssignableTo(iterableIteratorNextType, nextType)) {
70808                     if (globalType !== emptyGenericType) {
70809                         return createTypeFromGenericGlobalType(globalType, [yieldType]);
70810                     }
70811                     // The global IterableIterator type doesn't exist, so report an error
70812                     resolver.getGlobalIterableIteratorType(/*reportErrors*/ true);
70813                     return emptyObjectType;
70814                 }
70815                 // The global Generator type doesn't exist, so report an error
70816                 resolver.getGlobalGeneratorType(/*reportErrors*/ true);
70817                 return emptyObjectType;
70818             }
70819             return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]);
70820         }
70821         function checkAndAggregateYieldOperandTypes(func, checkMode) {
70822             var yieldTypes = [];
70823             var nextTypes = [];
70824             var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0;
70825             ts.forEachYieldExpression(func.body, function (yieldExpression) {
70826                 var yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType;
70827                 ts.pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync));
70828                 var nextType;
70829                 if (yieldExpression.asteriskToken) {
70830                     var iterationTypes = getIterationTypesOfIterable(yieldExpressionType, isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, yieldExpression.expression);
70831                     nextType = iterationTypes && iterationTypes.nextType;
70832                 }
70833                 else {
70834                     nextType = getContextualType(yieldExpression);
70835                 }
70836                 if (nextType)
70837                     ts.pushIfUnique(nextTypes, nextType);
70838             });
70839             return { yieldTypes: yieldTypes, nextTypes: nextTypes };
70840         }
70841         function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) {
70842             var errorNode = node.expression || node;
70843             // A `yield*` expression effectively yields everything that its operand yields
70844             var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType;
70845             return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken
70846                 ? 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
70847                 : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
70848         }
70849         /**
70850          * Collect the TypeFacts learned from a typeof switch with
70851          * total clauses `witnesses`, and the active clause ranging
70852          * from `start` to `end`. Parameter `hasDefault` denotes
70853          * whether the active clause contains a default clause.
70854          */
70855         function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) {
70856             var facts = 0 /* None */;
70857             // When in the default we only collect inequality facts
70858             // because default is 'in theory' a set of infinite
70859             // equalities.
70860             if (hasDefault) {
70861                 // Value is not equal to any types after the active clause.
70862                 for (var i = end; i < witnesses.length; i++) {
70863                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
70864                 }
70865                 // Remove inequalities for types that appear in the
70866                 // active clause because they appear before other
70867                 // types collected so far.
70868                 for (var i = start; i < end; i++) {
70869                     facts &= ~(typeofNEFacts.get(witnesses[i]) || 0);
70870                 }
70871                 // Add inequalities for types before the active clause unconditionally.
70872                 for (var i = 0; i < start; i++) {
70873                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
70874                 }
70875             }
70876             // When in an active clause without default the set of
70877             // equalities is finite.
70878             else {
70879                 // Add equalities for all types in the active clause.
70880                 for (var i = start; i < end; i++) {
70881                     facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */;
70882                 }
70883                 // Remove equalities for types that appear before the
70884                 // active clause.
70885                 for (var i = 0; i < start; i++) {
70886                     facts &= ~(typeofEQFacts.get(witnesses[i]) || 0);
70887                 }
70888             }
70889             return facts;
70890         }
70891         function isExhaustiveSwitchStatement(node) {
70892             var links = getNodeLinks(node);
70893             return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node));
70894         }
70895         function computeExhaustiveSwitchStatement(node) {
70896             if (node.expression.kind === 211 /* TypeOfExpression */) {
70897                 var operandType = getTypeOfExpression(node.expression.expression);
70898                 var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false);
70899                 // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
70900                 var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
70901                 var type_4 = getBaseConstraintOfType(operandType) || operandType;
70902                 // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types.
70903                 if (type_4.flags & 3 /* AnyOrUnknown */) {
70904                     return (556800 /* AllTypeofNE */ & notEqualFacts_1) === 556800 /* AllTypeofNE */;
70905                 }
70906                 return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */);
70907             }
70908             var type = getTypeOfExpression(node.expression);
70909             if (!isLiteralType(type)) {
70910                 return false;
70911             }
70912             var switchTypes = getSwitchClauseTypes(node);
70913             if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) {
70914                 return false;
70915             }
70916             return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
70917         }
70918         function functionHasImplicitReturn(func) {
70919             return func.endFlowNode && isReachableFlowNode(func.endFlowNode);
70920         }
70921         /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */
70922         function checkAndAggregateReturnExpressionTypes(func, checkMode) {
70923             var functionFlags = ts.getFunctionFlags(func);
70924             var aggregatedTypes = [];
70925             var hasReturnWithNoExpression = functionHasImplicitReturn(func);
70926             var hasReturnOfTypeNever = false;
70927             ts.forEachReturnStatement(func.body, function (returnStatement) {
70928                 var expr = returnStatement.expression;
70929                 if (expr) {
70930                     var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
70931                     if (functionFlags & 2 /* Async */) {
70932                         // From within an async function you can return either a non-promise value or a promise. Any
70933                         // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
70934                         // return type of the body should be unwrapped to its awaited type, which should be wrapped in
70935                         // the native Promise<T> type by the caller.
70936                         type = checkAwaitedType(type, func, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
70937                     }
70938                     if (type.flags & 131072 /* Never */) {
70939                         hasReturnOfTypeNever = true;
70940                     }
70941                     ts.pushIfUnique(aggregatedTypes, type);
70942                 }
70943                 else {
70944                     hasReturnWithNoExpression = true;
70945                 }
70946             });
70947             if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
70948                 return undefined;
70949             }
70950             if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression &&
70951                 !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) {
70952                 // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined
70953                 ts.pushIfUnique(aggregatedTypes, undefinedType);
70954             }
70955             return aggregatedTypes;
70956         }
70957         function mayReturnNever(func) {
70958             switch (func.kind) {
70959                 case 208 /* FunctionExpression */:
70960                 case 209 /* ArrowFunction */:
70961                     return true;
70962                 case 165 /* MethodDeclaration */:
70963                     return func.parent.kind === 200 /* ObjectLiteralExpression */;
70964                 default:
70965                     return false;
70966             }
70967         }
70968         /**
70969          * TypeScript Specification 1.0 (6.3) - July 2014
70970          *   An explicitly typed function whose return type isn't the Void type,
70971          *   the Any type, or a union type containing the Void or Any type as a constituent
70972          *   must have at least one return statement somewhere in its body.
70973          *   An exception to this rule is if the function implementation consists of a single 'throw' statement.
70974          *
70975          * @param returnType - return type of the function, can be undefined if return type is not explicitly specified
70976          */
70977         function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
70978             if (!produceDiagnostics) {
70979                 return;
70980             }
70981             var functionFlags = ts.getFunctionFlags(func);
70982             var type = returnType && unwrapReturnType(returnType, functionFlags);
70983             // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
70984             if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) {
70985                 return;
70986             }
70987             // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
70988             // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
70989             if (func.kind === 164 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 230 /* Block */ || !functionHasImplicitReturn(func)) {
70990                 return;
70991             }
70992             var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */;
70993             if (type && type.flags & 131072 /* Never */) {
70994                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
70995             }
70996             else if (type && !hasExplicitReturn) {
70997                 // minimal check: function has syntactic return type annotation and no explicit return statements in the body
70998                 // this function does not conform to the specification.
70999                 // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
71000                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
71001             }
71002             else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) {
71003                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
71004             }
71005             else if (compilerOptions.noImplicitReturns) {
71006                 if (!type) {
71007                     // If return type annotation is omitted check if function has any explicit return statements.
71008                     // If it does not have any - its inferred return type is void - don't do any checks.
71009                     // Otherwise get inferred return type from function body and report error only if it is not void / anytype
71010                     if (!hasExplicitReturn) {
71011                         return;
71012                     }
71013                     var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
71014                     if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) {
71015                         return;
71016                     }
71017                 }
71018                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value);
71019             }
71020         }
71021         function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
71022             ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
71023             checkNodeDeferred(node);
71024             // The identityMapper object is used to indicate that function expressions are wildcards
71025             if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
71026                 // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
71027                 if (!ts.getEffectiveReturnTypeNode(node) && !hasContextSensitiveParameters(node)) {
71028                     // Return plain anyFunctionType if there is no possibility we'll make inferences from the return type
71029                     var contextualSignature = getContextualSignature(node);
71030                     if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) {
71031                         var links = getNodeLinks(node);
71032                         if (links.contextFreeType) {
71033                             return links.contextFreeType;
71034                         }
71035                         var returnType = getReturnTypeFromBody(node, checkMode);
71036                         var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
71037                         var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
71038                         returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */;
71039                         return links.contextFreeType = returnOnlyType;
71040                     }
71041                 }
71042                 return anyFunctionType;
71043             }
71044             // Grammar checking
71045             var hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
71046             if (!hasGrammarError && node.kind === 208 /* FunctionExpression */) {
71047                 checkGrammarForGenerator(node);
71048             }
71049             contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);
71050             return getTypeOfSymbol(getSymbolOfNode(node));
71051         }
71052         function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
71053             var links = getNodeLinks(node);
71054             // Check if function expression is contextually typed and assign parameter types if so.
71055             if (!(links.flags & 1024 /* ContextChecked */)) {
71056                 var contextualSignature = getContextualSignature(node);
71057                 // If a type check is started at a function expression that is an argument of a function call, obtaining the
71058                 // contextual type may recursively get back to here during overload resolution of the call. If so, we will have
71059                 // already assigned contextual types.
71060                 if (!(links.flags & 1024 /* ContextChecked */)) {
71061                     links.flags |= 1024 /* ContextChecked */;
71062                     var signature = ts.firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfNode(node)), 0 /* Call */));
71063                     if (!signature) {
71064                         return;
71065                     }
71066                     if (isContextSensitive(node)) {
71067                         if (contextualSignature) {
71068                             var inferenceContext = getInferenceContext(node);
71069                             if (checkMode && checkMode & 2 /* Inferential */) {
71070                                 inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
71071                             }
71072                             var instantiatedContextualSignature = inferenceContext ?
71073                                 instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
71074                             assignContextualParameterTypes(signature, instantiatedContextualSignature);
71075                         }
71076                         else {
71077                             // Force resolution of all parameter types such that the absence of a contextual type is consistently reflected.
71078                             assignNonContextualParameterTypes(signature);
71079                         }
71080                     }
71081                     if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
71082                         var returnType = getReturnTypeFromBody(node, checkMode);
71083                         if (!signature.resolvedReturnType) {
71084                             signature.resolvedReturnType = returnType;
71085                         }
71086                     }
71087                     checkSignatureDeclaration(node);
71088                 }
71089             }
71090         }
71091         function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
71092             ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
71093             var functionFlags = ts.getFunctionFlags(node);
71094             var returnType = getReturnTypeFromAnnotation(node);
71095             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
71096             if (node.body) {
71097                 if (!ts.getEffectiveReturnTypeNode(node)) {
71098                     // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors
71099                     // we need. An example is the noImplicitAny errors resulting from widening the return expression
71100                     // of a function. Because checking of function expression bodies is deferred, there was never an
71101                     // appropriate time to do this during the main walk of the file (see the comment at the top of
71102                     // checkFunctionExpressionBodies). So it must be done now.
71103                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
71104                 }
71105                 if (node.body.kind === 230 /* Block */) {
71106                     checkSourceElement(node.body);
71107                 }
71108                 else {
71109                     // From within an async function you can return either a non-promise value or a promise. Any
71110                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so we
71111                     // should not be checking assignability of a promise to the return type. Instead, we need to
71112                     // check assignability of the awaited type of the expression body against the promised type of
71113                     // its return type annotation.
71114                     var exprType = checkExpression(node.body);
71115                     var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags);
71116                     if (returnOrPromisedType) {
71117                         if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
71118                             var awaitedType = checkAwaitedType(exprType, node.body, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
71119                             checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body);
71120                         }
71121                         else { // Normal function
71122                             checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body);
71123                         }
71124                     }
71125                 }
71126             }
71127         }
71128         function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid) {
71129             if (isAwaitValid === void 0) { isAwaitValid = false; }
71130             if (!isTypeAssignableTo(type, numberOrBigIntType)) {
71131                 var awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type);
71132                 errorAndMaybeSuggestAwait(operand, !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), diagnostic);
71133                 return false;
71134             }
71135             return true;
71136         }
71137         function isReadonlyAssignmentDeclaration(d) {
71138             if (!ts.isCallExpression(d)) {
71139                 return false;
71140             }
71141             if (!ts.isBindableObjectDefinePropertyCall(d)) {
71142                 return false;
71143             }
71144             var objectLitType = checkExpressionCached(d.arguments[2]);
71145             var valueType = getTypeOfPropertyOfType(objectLitType, "value");
71146             if (valueType) {
71147                 var writableProp = getPropertyOfType(objectLitType, "writable");
71148                 var writableType = writableProp && getTypeOfSymbol(writableProp);
71149                 if (!writableType || writableType === falseType || writableType === regularFalseType) {
71150                     return true;
71151                 }
71152                 // We include this definition whereupon we walk back and check the type at the declaration because
71153                 // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the
71154                 // argument types, should the type be contextualized by the call itself.
71155                 if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) {
71156                     var initializer = writableProp.valueDeclaration.initializer;
71157                     var rawOriginalType = checkExpression(initializer);
71158                     if (rawOriginalType === falseType || rawOriginalType === regularFalseType) {
71159                         return true;
71160                     }
71161                 }
71162                 return false;
71163             }
71164             var setProp = getPropertyOfType(objectLitType, "set");
71165             return !setProp;
71166         }
71167         function isReadonlySymbol(symbol) {
71168             // The following symbols are considered read-only:
71169             // Properties with a 'readonly' modifier
71170             // Variables declared with 'const'
71171             // Get accessors without matching set accessors
71172             // Enum members
71173             // Object.defineProperty assignments with writable false or no setter
71174             // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
71175             return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ ||
71176                 symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ ||
71177                 symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ||
71178                 symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) ||
71179                 symbol.flags & 8 /* EnumMember */ ||
71180                 ts.some(symbol.declarations, isReadonlyAssignmentDeclaration));
71181         }
71182         function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) {
71183             var _a, _b;
71184             if (assignmentKind === 0 /* None */) {
71185                 // no assigment means it doesn't matter whether the entity is readonly
71186                 return false;
71187             }
71188             if (isReadonlySymbol(symbol)) {
71189                 // Allow assignments to readonly properties within constructors of the same class declaration.
71190                 if (symbol.flags & 4 /* Property */ &&
71191                     ts.isAccessExpression(expr) &&
71192                     expr.expression.kind === 107 /* ThisKeyword */) {
71193                     // Look for if this is the constructor for the class that `symbol` is a property of.
71194                     var ctor = ts.getContainingFunction(expr);
71195                     if (!(ctor && (ctor.kind === 166 /* Constructor */ || isJSConstructor(ctor)))) {
71196                         return true;
71197                     }
71198                     if (symbol.valueDeclaration) {
71199                         var isAssignmentDeclaration_1 = ts.isBinaryExpression(symbol.valueDeclaration);
71200                         var isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent;
71201                         var isLocalParameterProperty = ctor === symbol.valueDeclaration.parent;
71202                         var isLocalThisPropertyAssignment = isAssignmentDeclaration_1 && ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) === ctor.parent;
71203                         var isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration_1 && ((_b = symbol.parent) === null || _b === void 0 ? void 0 : _b.valueDeclaration) === ctor;
71204                         var isWriteableSymbol = isLocalPropertyDeclaration
71205                             || isLocalParameterProperty
71206                             || isLocalThisPropertyAssignment
71207                             || isLocalThisPropertyAssignmentConstructorFunction;
71208                         return !isWriteableSymbol;
71209                     }
71210                 }
71211                 return true;
71212             }
71213             if (ts.isAccessExpression(expr)) {
71214                 // references through namespace import should be readonly
71215                 var node = ts.skipParentheses(expr.expression);
71216                 if (node.kind === 78 /* Identifier */) {
71217                     var symbol_2 = getNodeLinks(node).resolvedSymbol;
71218                     if (symbol_2.flags & 2097152 /* Alias */) {
71219                         var declaration = getDeclarationOfAliasSymbol(symbol_2);
71220                         return !!declaration && declaration.kind === 263 /* NamespaceImport */;
71221                     }
71222                 }
71223             }
71224             return false;
71225         }
71226         function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) {
71227             // References are combinations of identifiers, parentheses, and property accesses.
71228             var node = ts.skipOuterExpressions(expr, 6 /* Assertions */ | 1 /* Parentheses */);
71229             if (node.kind !== 78 /* Identifier */ && !ts.isAccessExpression(node)) {
71230                 error(expr, invalidReferenceMessage);
71231                 return false;
71232             }
71233             if (node.flags & 32 /* OptionalChain */) {
71234                 error(expr, invalidOptionalChainMessage);
71235                 return false;
71236             }
71237             return true;
71238         }
71239         function checkDeleteExpression(node) {
71240             checkExpression(node.expression);
71241             var expr = ts.skipParentheses(node.expression);
71242             if (!ts.isAccessExpression(expr)) {
71243                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
71244                 return booleanType;
71245             }
71246             if (ts.isPropertyAccessExpression(expr) && ts.isPrivateIdentifier(expr.name)) {
71247                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier);
71248             }
71249             var links = getNodeLinks(expr);
71250             var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
71251             if (symbol) {
71252                 if (isReadonlySymbol(symbol)) {
71253                     error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
71254                 }
71255                 checkDeleteExpressionMustBeOptional(expr, getTypeOfSymbol(symbol));
71256             }
71257             return booleanType;
71258         }
71259         function checkDeleteExpressionMustBeOptional(expr, type) {
71260             var AnyOrUnknownOrNeverFlags = 3 /* AnyOrUnknown */ | 131072 /* Never */;
71261             if (strictNullChecks && !(type.flags & AnyOrUnknownOrNeverFlags) && !(getFalsyFlags(type) & 32768 /* Undefined */)) {
71262                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional);
71263             }
71264         }
71265         function checkTypeOfExpression(node) {
71266             checkExpression(node.expression);
71267             return typeofType;
71268         }
71269         function checkVoidExpression(node) {
71270             checkExpression(node.expression);
71271             return undefinedWideningType;
71272         }
71273         function checkAwaitExpression(node) {
71274             // Grammar checking
71275             if (produceDiagnostics) {
71276                 if (!(node.flags & 32768 /* AwaitContext */)) {
71277                     if (ts.isInTopLevelContext(node)) {
71278                         var sourceFile = ts.getSourceFileOfNode(node);
71279                         if (!hasParseDiagnostics(sourceFile)) {
71280                             var span = void 0;
71281                             if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
71282                                 if (!span)
71283                                     span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
71284                                 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);
71285                                 diagnostics.add(diagnostic);
71286                             }
71287                             if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) {
71288                                 span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
71289                                 var diagnostic = ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher);
71290                                 diagnostics.add(diagnostic);
71291                             }
71292                         }
71293                     }
71294                     else {
71295                         // use of 'await' in non-async function
71296                         var sourceFile = ts.getSourceFileOfNode(node);
71297                         if (!hasParseDiagnostics(sourceFile)) {
71298                             var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
71299                             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);
71300                             var func = ts.getContainingFunction(node);
71301                             if (func && func.kind !== 166 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) {
71302                                 var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
71303                                 ts.addRelatedInfo(diagnostic, relatedInfo);
71304                             }
71305                             diagnostics.add(diagnostic);
71306                         }
71307                     }
71308                 }
71309                 if (isInParameterInitializerBeforeContainingFunction(node)) {
71310                     error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
71311                 }
71312             }
71313             var operandType = checkExpression(node.expression);
71314             var awaitedType = checkAwaitedType(operandType, node, ts.Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
71315             if (awaitedType === operandType && awaitedType !== errorType && !(operandType.flags & 3 /* AnyOrUnknown */)) {
71316                 addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression));
71317             }
71318             return awaitedType;
71319         }
71320         function checkPrefixUnaryExpression(node) {
71321             var operandType = checkExpression(node.operand);
71322             if (operandType === silentNeverType) {
71323                 return silentNeverType;
71324             }
71325             switch (node.operand.kind) {
71326                 case 8 /* NumericLiteral */:
71327                     switch (node.operator) {
71328                         case 40 /* MinusToken */:
71329                             return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text));
71330                         case 39 /* PlusToken */:
71331                             return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text));
71332                     }
71333                     break;
71334                 case 9 /* BigIntLiteral */:
71335                     if (node.operator === 40 /* MinusToken */) {
71336                         return getFreshTypeOfLiteralType(getLiteralType({
71337                             negative: true,
71338                             base10Value: ts.parsePseudoBigInt(node.operand.text)
71339                         }));
71340                     }
71341             }
71342             switch (node.operator) {
71343                 case 39 /* PlusToken */:
71344                 case 40 /* MinusToken */:
71345                 case 54 /* TildeToken */:
71346                     checkNonNullType(operandType, node.operand);
71347                     if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) {
71348                         error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator));
71349                     }
71350                     if (node.operator === 39 /* PlusToken */) {
71351                         if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
71352                             error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType)));
71353                         }
71354                         return numberType;
71355                     }
71356                     return getUnaryResultType(operandType);
71357                 case 53 /* ExclamationToken */:
71358                     checkTruthinessExpression(node.operand);
71359                     var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */);
71360                     return facts === 4194304 /* Truthy */ ? falseType :
71361                         facts === 8388608 /* Falsy */ ? trueType :
71362                             booleanType;
71363                 case 45 /* PlusPlusToken */:
71364                 case 46 /* MinusMinusToken */:
71365                     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);
71366                     if (ok) {
71367                         // run check only if former checks succeeded to avoid reporting cascading errors
71368                         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);
71369                     }
71370                     return getUnaryResultType(operandType);
71371             }
71372             return errorType;
71373         }
71374         function checkPostfixUnaryExpression(node) {
71375             var operandType = checkExpression(node.operand);
71376             if (operandType === silentNeverType) {
71377                 return silentNeverType;
71378             }
71379             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);
71380             if (ok) {
71381                 // run check only if former checks succeeded to avoid reporting cascading errors
71382                 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);
71383             }
71384             return getUnaryResultType(operandType);
71385         }
71386         function getUnaryResultType(operandType) {
71387             if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
71388                 return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */)
71389                     ? numberOrBigIntType
71390                     : bigintType;
71391             }
71392             // If it's not a bigint type, implicit coercion will result in a number
71393             return numberType;
71394         }
71395         // Return true if type might be of the given kind. A union or intersection type might be of a given
71396         // kind if at least one constituent type is of the given kind.
71397         function maybeTypeOfKind(type, kind) {
71398             if (type.flags & kind) {
71399                 return true;
71400             }
71401             if (type.flags & 3145728 /* UnionOrIntersection */) {
71402                 var types = type.types;
71403                 for (var _i = 0, types_22 = types; _i < types_22.length; _i++) {
71404                     var t = types_22[_i];
71405                     if (maybeTypeOfKind(t, kind)) {
71406                         return true;
71407                     }
71408                 }
71409             }
71410             return false;
71411         }
71412         function isTypeAssignableToKind(source, kind, strict) {
71413             if (source.flags & kind) {
71414                 return true;
71415             }
71416             if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) {
71417                 return false;
71418             }
71419             return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) ||
71420                 !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) ||
71421                 !!(kind & 402653316 /* StringLike */) && isTypeAssignableTo(source, stringType) ||
71422                 !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) ||
71423                 !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) ||
71424                 !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) ||
71425                 !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) ||
71426                 !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) ||
71427                 !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) ||
71428                 !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
71429         }
71430         function allTypesAssignableToKind(source, kind, strict) {
71431             return source.flags & 1048576 /* Union */ ?
71432                 ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) :
71433                 isTypeAssignableToKind(source, kind, strict);
71434         }
71435         function isConstEnumObjectType(type) {
71436             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
71437         }
71438         function isConstEnumSymbol(symbol) {
71439             return (symbol.flags & 128 /* ConstEnum */) !== 0;
71440         }
71441         function checkInstanceOfExpression(left, right, leftType, rightType) {
71442             if (leftType === silentNeverType || rightType === silentNeverType) {
71443                 return silentNeverType;
71444             }
71445             // TypeScript 1.0 spec (April 2014): 4.15.4
71446             // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
71447             // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature.
71448             // The result is always of the Boolean primitive type.
71449             // NOTE: do not raise error if leftType is unknown as related error was already reported
71450             if (!isTypeAny(leftType) &&
71451                 allTypesAssignableToKind(leftType, 131068 /* Primitive */)) {
71452                 error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
71453             }
71454             // NOTE: do not raise error if right is unknown as related error was already reported
71455             if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
71456                 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);
71457             }
71458             return booleanType;
71459         }
71460         function checkInExpression(left, right, leftType, rightType) {
71461             if (leftType === silentNeverType || rightType === silentNeverType) {
71462                 return silentNeverType;
71463             }
71464             leftType = checkNonNullType(leftType, left);
71465             rightType = checkNonNullType(rightType, right);
71466             // TypeScript 1.0 spec (April 2014): 4.15.5
71467             // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
71468             // and the right operand to be
71469             //
71470             //   1. assignable to the non-primitive type,
71471             //   2. an unconstrained type parameter,
71472             //   3. a union or intersection including one or more type parameters, whose constituents are all assignable to the
71473             //      the non-primitive type, or are unconstrainted type parameters, or have constraints assignable to the
71474             //      non-primitive type, or
71475             //   4. a type parameter whose constraint is
71476             //      i. an object type,
71477             //     ii. the non-primitive type, or
71478             //    iii. a union or intersection with at least one constituent assignable to an object or non-primitive type.
71479             //
71480             // The divergent behavior for type parameters and unions containing type parameters is a workaround for type
71481             // parameters not being narrowable. If the right operand is a concrete type, we can error if there is any chance
71482             // it is a primitive. But if the operand is a type parameter, it cannot be narrowed, so we don't issue an error
71483             // unless *all* instantiations would result in an error.
71484             //
71485             // The result is always of the Boolean primitive type.
71486             if (!(allTypesAssignableToKind(leftType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) ||
71487                 isTypeAssignableToKind(leftType, 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */ | 262144 /* TypeParameter */))) {
71488                 error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
71489             }
71490             var rightTypeConstraint = getConstraintOfType(rightType);
71491             if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) ||
71492                 rightTypeConstraint && (isTypeAssignableToKind(rightType, 3145728 /* UnionOrIntersection */) && !allTypesAssignableToKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */) ||
71493                     !maybeTypeOfKind(rightTypeConstraint, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */))) {
71494                 error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_not_be_a_primitive);
71495             }
71496             return booleanType;
71497         }
71498         function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
71499             var properties = node.properties;
71500             if (strictNullChecks && properties.length === 0) {
71501                 return checkNonNullType(sourceType, node);
71502             }
71503             for (var i = 0; i < properties.length; i++) {
71504                 checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis);
71505             }
71506             return sourceType;
71507         }
71508         /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
71509         function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis) {
71510             if (rightIsThis === void 0) { rightIsThis = false; }
71511             var properties = node.properties;
71512             var property = properties[propertyIndex];
71513             if (property.kind === 288 /* PropertyAssignment */ || property.kind === 289 /* ShorthandPropertyAssignment */) {
71514                 var name = property.name;
71515                 var exprType = getLiteralTypeFromPropertyName(name);
71516                 if (isTypeUsableAsPropertyName(exprType)) {
71517                     var text = getPropertyNameFromType(exprType);
71518                     var prop = getPropertyOfType(objectLiteralType, text);
71519                     if (prop) {
71520                         markPropertyAsReferenced(prop, property, rightIsThis);
71521                         checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop);
71522                     }
71523                 }
71524                 var elementType = getIndexedAccessType(objectLiteralType, exprType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */);
71525                 var type = getFlowTypeOfDestructuring(property, elementType);
71526                 return checkDestructuringAssignment(property.kind === 289 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
71527             }
71528             else if (property.kind === 290 /* SpreadAssignment */) {
71529                 if (propertyIndex < properties.length - 1) {
71530                     error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
71531                 }
71532                 else {
71533                     if (languageVersion < 99 /* ESNext */) {
71534                         checkExternalEmitHelpers(property, 4 /* Rest */);
71535                     }
71536                     var nonRestNames = [];
71537                     if (allProperties) {
71538                         for (var _i = 0, allProperties_1 = allProperties; _i < allProperties_1.length; _i++) {
71539                             var otherProperty = allProperties_1[_i];
71540                             if (!ts.isSpreadAssignment(otherProperty)) {
71541                                 nonRestNames.push(otherProperty.name);
71542                             }
71543                         }
71544                     }
71545                     var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
71546                     checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
71547                     return checkDestructuringAssignment(property.expression, type);
71548                 }
71549             }
71550             else {
71551                 error(property, ts.Diagnostics.Property_assignment_expected);
71552             }
71553         }
71554         function checkArrayLiteralAssignment(node, sourceType, checkMode) {
71555             var elements = node.elements;
71556             if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
71557                 checkExternalEmitHelpers(node, 512 /* Read */);
71558             }
71559             // This elementType will be used if the specific property corresponding to this index is not
71560             // present (aka the tuple element property). This call also checks that the parentType is in
71561             // fact an iterable or array (depending on target language).
71562             var possiblyOutOfBoundsType = checkIteratedTypeOrElementType(65 /* Destructuring */ | 128 /* PossiblyOutOfBounds */, sourceType, undefinedType, node) || errorType;
71563             var inBoundsType = compilerOptions.noUncheckedIndexedAccess ? undefined : possiblyOutOfBoundsType;
71564             for (var i = 0; i < elements.length; i++) {
71565                 var type = possiblyOutOfBoundsType;
71566                 if (node.elements[i].kind === 220 /* SpreadElement */) {
71567                     type = inBoundsType = inBoundsType !== null && inBoundsType !== void 0 ? inBoundsType : (checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType);
71568                 }
71569                 checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode);
71570             }
71571             return sourceType;
71572         }
71573         function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
71574             var elements = node.elements;
71575             var element = elements[elementIndex];
71576             if (element.kind !== 222 /* OmittedExpression */) {
71577                 if (element.kind !== 220 /* SpreadElement */) {
71578                     var indexType = getLiteralType(elementIndex);
71579                     if (isArrayLikeType(sourceType)) {
71580                         // We create a synthetic expression so that getIndexedAccessType doesn't get confused
71581                         // when the element is a SyntaxKind.ElementAccessExpression.
71582                         var accessFlags = 16 /* ExpressionPosition */ | (hasDefaultValue(element) ? 8 /* NoTupleBoundsCheck */ : 0);
71583                         var elementType_2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, createSyntheticExpression(element, indexType), accessFlags) || errorType;
71584                         var assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType_2, 524288 /* NEUndefined */) : elementType_2;
71585                         var type = getFlowTypeOfDestructuring(element, assignedType);
71586                         return checkDestructuringAssignment(element, type, checkMode);
71587                     }
71588                     return checkDestructuringAssignment(element, elementType, checkMode);
71589                 }
71590                 if (elementIndex < elements.length - 1) {
71591                     error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
71592                 }
71593                 else {
71594                     var restExpression = element.expression;
71595                     if (restExpression.kind === 216 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) {
71596                         error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
71597                     }
71598                     else {
71599                         checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
71600                         var type = everyType(sourceType, isTupleType) ?
71601                             mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) :
71602                             createArrayType(elementType);
71603                         return checkDestructuringAssignment(restExpression, type, checkMode);
71604                     }
71605                 }
71606             }
71607             return undefined;
71608         }
71609         function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
71610             var target;
71611             if (exprOrAssignment.kind === 289 /* ShorthandPropertyAssignment */) {
71612                 var prop = exprOrAssignment;
71613                 if (prop.objectAssignmentInitializer) {
71614                     // In strict null checking mode, if a default value of a non-undefined type is specified, remove
71615                     // undefined from the final type.
71616                     if (strictNullChecks &&
71617                         !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) {
71618                         sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
71619                     }
71620                     checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
71621                 }
71622                 target = exprOrAssignment.name;
71623             }
71624             else {
71625                 target = exprOrAssignment;
71626             }
71627             if (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) {
71628                 checkBinaryExpression(target, checkMode);
71629                 target = target.left;
71630             }
71631             if (target.kind === 200 /* ObjectLiteralExpression */) {
71632                 return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
71633             }
71634             if (target.kind === 199 /* ArrayLiteralExpression */) {
71635                 return checkArrayLiteralAssignment(target, sourceType, checkMode);
71636             }
71637             return checkReferenceAssignment(target, sourceType, checkMode);
71638         }
71639         function checkReferenceAssignment(target, sourceType, checkMode) {
71640             var targetType = checkExpression(target, checkMode);
71641             var error = target.parent.kind === 290 /* SpreadAssignment */ ?
71642                 ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access :
71643                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
71644             var optionalError = target.parent.kind === 290 /* SpreadAssignment */ ?
71645                 ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access :
71646                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access;
71647             if (checkReferenceExpression(target, error, optionalError)) {
71648                 checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
71649             }
71650             if (ts.isPrivateIdentifierPropertyAccessExpression(target)) {
71651                 checkExternalEmitHelpers(target.parent, 1048576 /* ClassPrivateFieldSet */);
71652             }
71653             return sourceType;
71654         }
71655         /**
71656          * This is a *shallow* check: An expression is side-effect-free if the
71657          * evaluation of the expression *itself* cannot produce side effects.
71658          * For example, x++ / 3 is side-effect free because the / operator
71659          * does not have side effects.
71660          * The intent is to "smell test" an expression for correctness in positions where
71661          * its value is discarded (e.g. the left side of the comma operator).
71662          */
71663         function isSideEffectFree(node) {
71664             node = ts.skipParentheses(node);
71665             switch (node.kind) {
71666                 case 78 /* Identifier */:
71667                 case 10 /* StringLiteral */:
71668                 case 13 /* RegularExpressionLiteral */:
71669                 case 205 /* TaggedTemplateExpression */:
71670                 case 218 /* TemplateExpression */:
71671                 case 14 /* NoSubstitutionTemplateLiteral */:
71672                 case 8 /* NumericLiteral */:
71673                 case 9 /* BigIntLiteral */:
71674                 case 109 /* TrueKeyword */:
71675                 case 94 /* FalseKeyword */:
71676                 case 103 /* NullKeyword */:
71677                 case 150 /* UndefinedKeyword */:
71678                 case 208 /* FunctionExpression */:
71679                 case 221 /* ClassExpression */:
71680                 case 209 /* ArrowFunction */:
71681                 case 199 /* ArrayLiteralExpression */:
71682                 case 200 /* ObjectLiteralExpression */:
71683                 case 211 /* TypeOfExpression */:
71684                 case 225 /* NonNullExpression */:
71685                 case 274 /* JsxSelfClosingElement */:
71686                 case 273 /* JsxElement */:
71687                     return true;
71688                 case 217 /* ConditionalExpression */:
71689                     return isSideEffectFree(node.whenTrue) &&
71690                         isSideEffectFree(node.whenFalse);
71691                 case 216 /* BinaryExpression */:
71692                     if (ts.isAssignmentOperator(node.operatorToken.kind)) {
71693                         return false;
71694                     }
71695                     return isSideEffectFree(node.left) &&
71696                         isSideEffectFree(node.right);
71697                 case 214 /* PrefixUnaryExpression */:
71698                 case 215 /* PostfixUnaryExpression */:
71699                     // Unary operators ~, !, +, and - have no side effects.
71700                     // The rest do.
71701                     switch (node.operator) {
71702                         case 53 /* ExclamationToken */:
71703                         case 39 /* PlusToken */:
71704                         case 40 /* MinusToken */:
71705                         case 54 /* TildeToken */:
71706                             return true;
71707                     }
71708                     return false;
71709                 // Some forms listed here for clarity
71710                 case 212 /* VoidExpression */: // Explicit opt-out
71711                 case 206 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
71712                 case 224 /* AsExpression */: // Not SEF, but can produce useful type warnings
71713                 default:
71714                     return false;
71715             }
71716         }
71717         function isTypeEqualityComparableTo(source, target) {
71718             return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target);
71719         }
71720         var CheckBinaryExpressionState;
71721         (function (CheckBinaryExpressionState) {
71722             CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft";
71723             CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight";
71724             CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck";
71725         })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {}));
71726         function checkBinaryExpression(node, checkMode) {
71727             var workStacks = {
71728                 expr: [node],
71729                 state: [0 /* MaybeCheckLeft */],
71730                 leftType: [undefined]
71731             };
71732             var stackIndex = 0;
71733             var lastResult;
71734             while (stackIndex >= 0) {
71735                 node = workStacks.expr[stackIndex];
71736                 switch (workStacks.state[stackIndex]) {
71737                     case 0 /* MaybeCheckLeft */: {
71738                         if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) {
71739                             finishInvocation(checkExpression(node.right, checkMode));
71740                             break;
71741                         }
71742                         checkGrammarNullishCoalesceWithLogicalExpression(node);
71743                         var operator = node.operatorToken.kind;
71744                         if (operator === 62 /* EqualsToken */ && (node.left.kind === 200 /* ObjectLiteralExpression */ || node.left.kind === 199 /* ArrayLiteralExpression */)) {
71745                             finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107 /* ThisKeyword */));
71746                             break;
71747                         }
71748                         advanceState(1 /* CheckRight */);
71749                         maybeCheckExpression(node.left);
71750                         break;
71751                     }
71752                     case 1 /* CheckRight */: {
71753                         var leftType = lastResult;
71754                         workStacks.leftType[stackIndex] = leftType;
71755                         var operator = node.operatorToken.kind;
71756                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
71757                             if (operator === 55 /* AmpersandAmpersandToken */) {
71758                                 var parent = ts.walkUpParenthesizedExpressions(node.parent);
71759                                 checkTestingKnownTruthyCallableType(node.left, leftType, ts.isIfStatement(parent) ? parent.thenStatement : undefined);
71760                             }
71761                             checkTruthinessOfType(leftType, node.left);
71762                         }
71763                         advanceState(2 /* FinishCheck */);
71764                         maybeCheckExpression(node.right);
71765                         break;
71766                     }
71767                     case 2 /* FinishCheck */: {
71768                         var leftType = workStacks.leftType[stackIndex];
71769                         var rightType = lastResult;
71770                         finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node));
71771                         break;
71772                     }
71773                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression");
71774                 }
71775             }
71776             return lastResult;
71777             function finishInvocation(result) {
71778                 lastResult = result;
71779                 stackIndex--;
71780             }
71781             /**
71782              * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new
71783              * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution.
71784              */
71785             function advanceState(nextState) {
71786                 workStacks.state[stackIndex] = nextState;
71787             }
71788             function maybeCheckExpression(node) {
71789                 if (ts.isBinaryExpression(node)) {
71790                     stackIndex++;
71791                     workStacks.expr[stackIndex] = node;
71792                     workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */;
71793                     workStacks.leftType[stackIndex] = undefined;
71794                 }
71795                 else {
71796                     lastResult = checkExpression(node, checkMode);
71797                 }
71798             }
71799         }
71800         function checkGrammarNullishCoalesceWithLogicalExpression(node) {
71801             var left = node.left, operatorToken = node.operatorToken, right = node.right;
71802             if (operatorToken.kind === 60 /* QuestionQuestionToken */) {
71803                 if (ts.isBinaryExpression(left) && (left.operatorToken.kind === 56 /* BarBarToken */ || left.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
71804                     grammarErrorOnNode(left, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(left.operatorToken.kind), ts.tokenToString(operatorToken.kind));
71805                 }
71806                 if (ts.isBinaryExpression(right) && (right.operatorToken.kind === 56 /* BarBarToken */ || right.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
71807                     grammarErrorOnNode(right, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(right.operatorToken.kind), ts.tokenToString(operatorToken.kind));
71808                 }
71809             }
71810         }
71811         // Note that this and `checkBinaryExpression` above should behave mostly the same, except this elides some
71812         // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame
71813         function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
71814             var operator = operatorToken.kind;
71815             if (operator === 62 /* EqualsToken */ && (left.kind === 200 /* ObjectLiteralExpression */ || left.kind === 199 /* ArrayLiteralExpression */)) {
71816                 return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 107 /* ThisKeyword */);
71817             }
71818             var leftType;
71819             if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
71820                 leftType = checkTruthinessExpression(left, checkMode);
71821             }
71822             else {
71823                 leftType = checkExpression(left, checkMode);
71824             }
71825             var rightType = checkExpression(right, checkMode);
71826             return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode);
71827         }
71828         function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode) {
71829             var operator = operatorToken.kind;
71830             switch (operator) {
71831                 case 41 /* AsteriskToken */:
71832                 case 42 /* AsteriskAsteriskToken */:
71833                 case 65 /* AsteriskEqualsToken */:
71834                 case 66 /* AsteriskAsteriskEqualsToken */:
71835                 case 43 /* SlashToken */:
71836                 case 67 /* SlashEqualsToken */:
71837                 case 44 /* PercentToken */:
71838                 case 68 /* PercentEqualsToken */:
71839                 case 40 /* MinusToken */:
71840                 case 64 /* MinusEqualsToken */:
71841                 case 47 /* LessThanLessThanToken */:
71842                 case 69 /* LessThanLessThanEqualsToken */:
71843                 case 48 /* GreaterThanGreaterThanToken */:
71844                 case 70 /* GreaterThanGreaterThanEqualsToken */:
71845                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
71846                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
71847                 case 51 /* BarToken */:
71848                 case 73 /* BarEqualsToken */:
71849                 case 52 /* CaretToken */:
71850                 case 77 /* CaretEqualsToken */:
71851                 case 50 /* AmpersandToken */:
71852                 case 72 /* AmpersandEqualsToken */:
71853                     if (leftType === silentNeverType || rightType === silentNeverType) {
71854                         return silentNeverType;
71855                     }
71856                     leftType = checkNonNullType(leftType, left);
71857                     rightType = checkNonNullType(rightType, right);
71858                     var suggestedOperator = void 0;
71859                     // if a user tries to apply a bitwise operator to 2 boolean operands
71860                     // try and return them a helpful suggestion
71861                     if ((leftType.flags & 528 /* BooleanLike */) &&
71862                         (rightType.flags & 528 /* BooleanLike */) &&
71863                         (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) {
71864                         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));
71865                         return numberType;
71866                     }
71867                     else {
71868                         // otherwise just check each operand separately and report errors as normal
71869                         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);
71870                         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);
71871                         var resultType_1;
71872                         // If both are any or unknown, allow operation; assume it will resolve to number
71873                         if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) ||
71874                             // Or, if neither could be bigint, implicit coercion results in a number result
71875                             !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) {
71876                             resultType_1 = numberType;
71877                         }
71878                         // At least one is assignable to bigint, so check that both are
71879                         else if (bothAreBigIntLike(leftType, rightType)) {
71880                             switch (operator) {
71881                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
71882                                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
71883                                     reportOperatorError();
71884                                     break;
71885                                 case 42 /* AsteriskAsteriskToken */:
71886                                 case 66 /* AsteriskAsteriskEqualsToken */:
71887                                     if (languageVersion < 3 /* ES2016 */) {
71888                                         error(errorNode, ts.Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later);
71889                                     }
71890                             }
71891                             resultType_1 = bigintType;
71892                         }
71893                         // Exactly one of leftType/rightType is assignable to bigint
71894                         else {
71895                             reportOperatorError(bothAreBigIntLike);
71896                             resultType_1 = errorType;
71897                         }
71898                         if (leftOk && rightOk) {
71899                             checkAssignmentOperator(resultType_1);
71900                         }
71901                         return resultType_1;
71902                     }
71903                 case 39 /* PlusToken */:
71904                 case 63 /* PlusEqualsToken */:
71905                     if (leftType === silentNeverType || rightType === silentNeverType) {
71906                         return silentNeverType;
71907                     }
71908                     if (!isTypeAssignableToKind(leftType, 402653316 /* StringLike */) && !isTypeAssignableToKind(rightType, 402653316 /* StringLike */)) {
71909                         leftType = checkNonNullType(leftType, left);
71910                         rightType = checkNonNullType(rightType, right);
71911                     }
71912                     var resultType = void 0;
71913                     if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) {
71914                         // Operands of an enum type are treated as having the primitive type Number.
71915                         // If both operands are of the Number primitive type, the result is of the Number primitive type.
71916                         resultType = numberType;
71917                     }
71918                     else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) {
71919                         // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type.
71920                         resultType = bigintType;
71921                     }
71922                     else if (isTypeAssignableToKind(leftType, 402653316 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 402653316 /* StringLike */, /*strict*/ true)) {
71923                         // If one or both operands are of the String primitive type, the result is of the String primitive type.
71924                         resultType = stringType;
71925                     }
71926                     else if (isTypeAny(leftType) || isTypeAny(rightType)) {
71927                         // Otherwise, the result is of type Any.
71928                         // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we.
71929                         resultType = leftType === errorType || rightType === errorType ? errorType : anyType;
71930                     }
71931                     // Symbols are not allowed at all in arithmetic expressions
71932                     if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
71933                         return resultType;
71934                     }
71935                     if (!resultType) {
71936                         // Types that have a reasonably good chance of being a valid operand type.
71937                         // If both types have an awaited type of one of these, we'll assume the user
71938                         // might be missing an await without doing an exhaustive check that inserting
71939                         // await(s) will actually be a completely valid binary expression.
71940                         var closeEnoughKind_1 = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 3 /* AnyOrUnknown */;
71941                         reportOperatorError(function (left, right) {
71942                             return isTypeAssignableToKind(left, closeEnoughKind_1) &&
71943                                 isTypeAssignableToKind(right, closeEnoughKind_1);
71944                         });
71945                         return anyType;
71946                     }
71947                     if (operator === 63 /* PlusEqualsToken */) {
71948                         checkAssignmentOperator(resultType);
71949                     }
71950                     return resultType;
71951                 case 29 /* LessThanToken */:
71952                 case 31 /* GreaterThanToken */:
71953                 case 32 /* LessThanEqualsToken */:
71954                 case 33 /* GreaterThanEqualsToken */:
71955                     if (checkForDisallowedESSymbolOperand(operator)) {
71956                         leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
71957                         rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
71958                         reportOperatorErrorUnless(function (left, right) {
71959                             return isTypeComparableTo(left, right) || isTypeComparableTo(right, left) || (isTypeAssignableTo(left, numberOrBigIntType) && isTypeAssignableTo(right, numberOrBigIntType));
71960                         });
71961                     }
71962                     return booleanType;
71963                 case 34 /* EqualsEqualsToken */:
71964                 case 35 /* ExclamationEqualsToken */:
71965                 case 36 /* EqualsEqualsEqualsToken */:
71966                 case 37 /* ExclamationEqualsEqualsToken */:
71967                     reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); });
71968                     return booleanType;
71969                 case 101 /* InstanceOfKeyword */:
71970                     return checkInstanceOfExpression(left, right, leftType, rightType);
71971                 case 100 /* InKeyword */:
71972                     return checkInExpression(left, right, leftType, rightType);
71973                 case 55 /* AmpersandAmpersandToken */:
71974                 case 75 /* AmpersandAmpersandEqualsToken */: {
71975                     var resultType_2 = getTypeFacts(leftType) & 4194304 /* Truthy */ ?
71976                         getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) :
71977                         leftType;
71978                     if (operator === 75 /* AmpersandAmpersandEqualsToken */) {
71979                         checkAssignmentOperator(rightType);
71980                     }
71981                     return resultType_2;
71982                 }
71983                 case 56 /* BarBarToken */:
71984                 case 74 /* BarBarEqualsToken */: {
71985                     var resultType_3 = getTypeFacts(leftType) & 8388608 /* Falsy */ ?
71986                         getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) :
71987                         leftType;
71988                     if (operator === 74 /* BarBarEqualsToken */) {
71989                         checkAssignmentOperator(rightType);
71990                     }
71991                     return resultType_3;
71992                 }
71993                 case 60 /* QuestionQuestionToken */:
71994                 case 76 /* QuestionQuestionEqualsToken */: {
71995                     var resultType_4 = getTypeFacts(leftType) & 262144 /* EQUndefinedOrNull */ ?
71996                         getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) :
71997                         leftType;
71998                     if (operator === 76 /* QuestionQuestionEqualsToken */) {
71999                         checkAssignmentOperator(rightType);
72000                     }
72001                     return resultType_4;
72002                 }
72003                 case 62 /* EqualsToken */:
72004                     var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
72005                     checkAssignmentDeclaration(declKind, rightType);
72006                     if (isAssignmentDeclaration(declKind)) {
72007                         if (!(rightType.flags & 524288 /* Object */) ||
72008                             declKind !== 2 /* ModuleExports */ &&
72009                                 declKind !== 6 /* Prototype */ &&
72010                                 !isEmptyObjectType(rightType) &&
72011                                 !isFunctionObjectType(rightType) &&
72012                                 !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
72013                             // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
72014                             checkAssignmentOperator(rightType);
72015                         }
72016                         return leftType;
72017                     }
72018                     else {
72019                         checkAssignmentOperator(rightType);
72020                         return getRegularTypeOfObjectLiteral(rightType);
72021                     }
72022                 case 27 /* CommaToken */:
72023                     if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) {
72024                         var sf = ts.getSourceFileOfNode(left);
72025                         var sourceText = sf.text;
72026                         var start_3 = ts.skipTrivia(sourceText, left.pos);
72027                         var isInDiag2657 = sf.parseDiagnostics.some(function (diag) {
72028                             if (diag.code !== ts.Diagnostics.JSX_expressions_must_have_one_parent_element.code)
72029                                 return false;
72030                             return ts.textSpanContainsPosition(diag, start_3);
72031                         });
72032                         if (!isInDiag2657)
72033                             error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
72034                     }
72035                     return rightType;
72036                 default:
72037                     return ts.Debug.fail();
72038             }
72039             function bothAreBigIntLike(left, right) {
72040                 return isTypeAssignableToKind(left, 2112 /* BigIntLike */) && isTypeAssignableToKind(right, 2112 /* BigIntLike */);
72041             }
72042             function checkAssignmentDeclaration(kind, rightType) {
72043                 if (kind === 2 /* ModuleExports */) {
72044                     for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
72045                         var prop = _a[_i];
72046                         var propType = getTypeOfSymbol(prop);
72047                         if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
72048                             var name = prop.escapedName;
72049                             var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false);
72050                             if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) {
72051                                 addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop);
72052                                 addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol);
72053                             }
72054                         }
72055                     }
72056                 }
72057             }
72058             function isEvalNode(node) {
72059                 return node.kind === 78 /* Identifier */ && node.escapedText === "eval";
72060             }
72061             // Return true if there was no error, false if there was an error.
72062             function checkForDisallowedESSymbolOperand(operator) {
72063                 var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left :
72064                     maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right :
72065                         undefined;
72066                 if (offendingSymbolOperand) {
72067                     error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator));
72068                     return false;
72069                 }
72070                 return true;
72071             }
72072             function getSuggestedBooleanOperator(operator) {
72073                 switch (operator) {
72074                     case 51 /* BarToken */:
72075                     case 73 /* BarEqualsToken */:
72076                         return 56 /* BarBarToken */;
72077                     case 52 /* CaretToken */:
72078                     case 77 /* CaretEqualsToken */:
72079                         return 37 /* ExclamationEqualsEqualsToken */;
72080                     case 50 /* AmpersandToken */:
72081                     case 72 /* AmpersandEqualsToken */:
72082                         return 55 /* AmpersandAmpersandToken */;
72083                     default:
72084                         return undefined;
72085                 }
72086             }
72087             function checkAssignmentOperator(valueType) {
72088                 if (produceDiagnostics && ts.isAssignmentOperator(operator)) {
72089                     // TypeScript 1.0 spec (April 2014): 4.17
72090                     // An assignment of the form
72091                     //    VarExpr = ValueExpr
72092                     // requires VarExpr to be classified as a reference
72093                     // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1)
72094                     // and the type of the non-compound operation to be assignable to the type of VarExpr.
72095                     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)
72096                         && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) {
72097                         // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported
72098                         checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right);
72099                     }
72100                 }
72101             }
72102             function isAssignmentDeclaration(kind) {
72103                 var _a;
72104                 switch (kind) {
72105                     case 2 /* ModuleExports */:
72106                         return true;
72107                     case 1 /* ExportsProperty */:
72108                     case 5 /* Property */:
72109                     case 6 /* Prototype */:
72110                     case 3 /* PrototypeProperty */:
72111                     case 4 /* ThisProperty */:
72112                         var symbol = getSymbolOfNode(left);
72113                         var init = ts.getAssignedExpandoInitializer(right);
72114                         return !!init && ts.isObjectLiteralExpression(init) &&
72115                             !!((_a = symbol === null || symbol === void 0 ? void 0 : symbol.exports) === null || _a === void 0 ? void 0 : _a.size);
72116                     default:
72117                         return false;
72118                 }
72119             }
72120             /**
72121              * Returns true if an error is reported
72122              */
72123             function reportOperatorErrorUnless(typesAreCompatible) {
72124                 if (!typesAreCompatible(leftType, rightType)) {
72125                     reportOperatorError(typesAreCompatible);
72126                     return true;
72127                 }
72128                 return false;
72129             }
72130             function reportOperatorError(isRelated) {
72131                 var _a;
72132                 var wouldWorkWithAwait = false;
72133                 var errNode = errorNode || operatorToken;
72134                 if (isRelated) {
72135                     var awaitedLeftType = getAwaitedType(leftType);
72136                     var awaitedRightType = getAwaitedType(rightType);
72137                     wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType)
72138                         && !!(awaitedLeftType && awaitedRightType)
72139                         && isRelated(awaitedLeftType, awaitedRightType);
72140                 }
72141                 var effectiveLeft = leftType;
72142                 var effectiveRight = rightType;
72143                 if (!wouldWorkWithAwait && isRelated) {
72144                     _a = getBaseTypesIfUnrelated(leftType, rightType, isRelated), effectiveLeft = _a[0], effectiveRight = _a[1];
72145                 }
72146                 var _b = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight), leftStr = _b[0], rightStr = _b[1];
72147                 if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) {
72148                     errorAndMaybeSuggestAwait(errNode, wouldWorkWithAwait, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr);
72149                 }
72150             }
72151             function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) {
72152                 var typeName;
72153                 switch (operatorToken.kind) {
72154                     case 36 /* EqualsEqualsEqualsToken */:
72155                     case 34 /* EqualsEqualsToken */:
72156                         typeName = "false";
72157                         break;
72158                     case 37 /* ExclamationEqualsEqualsToken */:
72159                     case 35 /* ExclamationEqualsToken */:
72160                         typeName = "true";
72161                 }
72162                 if (typeName) {
72163                     return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, typeName, leftStr, rightStr);
72164                 }
72165                 return undefined;
72166             }
72167         }
72168         function getBaseTypesIfUnrelated(leftType, rightType, isRelated) {
72169             var effectiveLeft = leftType;
72170             var effectiveRight = rightType;
72171             var leftBase = getBaseTypeOfLiteralType(leftType);
72172             var rightBase = getBaseTypeOfLiteralType(rightType);
72173             if (!isRelated(leftBase, rightBase)) {
72174                 effectiveLeft = leftBase;
72175                 effectiveRight = rightBase;
72176             }
72177             return [effectiveLeft, effectiveRight];
72178         }
72179         function checkYieldExpression(node) {
72180             // Grammar checking
72181             if (produceDiagnostics) {
72182                 if (!(node.flags & 8192 /* YieldContext */)) {
72183                     grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
72184                 }
72185                 if (isInParameterInitializerBeforeContainingFunction(node)) {
72186                     error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
72187                 }
72188             }
72189             var func = ts.getContainingFunction(node);
72190             if (!func)
72191                 return anyType;
72192             var functionFlags = ts.getFunctionFlags(func);
72193             if (!(functionFlags & 1 /* Generator */)) {
72194                 // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context.
72195                 return anyType;
72196             }
72197             var isAsync = (functionFlags & 2 /* Async */) !== 0;
72198             if (node.asteriskToken) {
72199                 // Async generator functions prior to ESNext require the __await, __asyncDelegator,
72200                 // and __asyncValues helpers
72201                 if (isAsync && languageVersion < 99 /* ESNext */) {
72202                     checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */);
72203                 }
72204                 // Generator functions prior to ES2015 require the __values helper
72205                 if (!isAsync && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
72206                     checkExternalEmitHelpers(node, 256 /* Values */);
72207                 }
72208             }
72209             // There is no point in doing an assignability check if the function
72210             // has no explicit return type because the return type is directly computed
72211             // from the yield expressions.
72212             var returnType = getReturnTypeFromAnnotation(func);
72213             var iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync);
72214             var signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType;
72215             var signatureNextType = iterationTypes && iterationTypes.nextType || anyType;
72216             var resolvedSignatureNextType = isAsync ? getAwaitedType(signatureNextType) || anyType : signatureNextType;
72217             var yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType;
72218             var yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, resolvedSignatureNextType, isAsync);
72219             if (returnType && yieldedType) {
72220                 checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression);
72221             }
72222             if (node.asteriskToken) {
72223                 var use = isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */;
72224                 return getIterationTypeOfIterable(use, 1 /* Return */, yieldExpressionType, node.expression)
72225                     || anyType;
72226             }
72227             else if (returnType) {
72228                 return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync)
72229                     || anyType;
72230             }
72231             var type = getContextualIterationType(2 /* Next */, func);
72232             if (!type) {
72233                 type = anyType;
72234                 if (produceDiagnostics && noImplicitAny && !ts.expressionResultIsUnused(node)) {
72235                     var contextualType = getContextualType(node);
72236                     if (!contextualType || isTypeAny(contextualType)) {
72237                         error(node, ts.Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation);
72238                     }
72239                 }
72240             }
72241             return type;
72242         }
72243         function checkConditionalExpression(node, checkMode) {
72244             var type = checkTruthinessExpression(node.condition);
72245             checkTestingKnownTruthyCallableType(node.condition, type, node.whenTrue);
72246             var type1 = checkExpression(node.whenTrue, checkMode);
72247             var type2 = checkExpression(node.whenFalse, checkMode);
72248             return getUnionType([type1, type2], 2 /* Subtype */);
72249         }
72250         function checkTemplateExpression(node) {
72251             var texts = [node.head.text];
72252             var types = [];
72253             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
72254                 var span = _a[_i];
72255                 var type = checkExpression(span.expression);
72256                 if (maybeTypeOfKind(type, 12288 /* ESSymbolLike */)) {
72257                     error(span.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
72258                 }
72259                 texts.push(span.literal.text);
72260                 types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType);
72261             }
72262             return isConstContext(node) ? getTemplateLiteralType(texts, types) : stringType;
72263         }
72264         function getContextNode(node) {
72265             if (node.kind === 281 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) {
72266                 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)
72267             }
72268             return node;
72269         }
72270         function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
72271             var context = getContextNode(node);
72272             var saveContextualType = context.contextualType;
72273             var saveInferenceContext = context.inferenceContext;
72274             try {
72275                 context.contextualType = contextualType;
72276                 context.inferenceContext = inferenceContext;
72277                 var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
72278                 // We strip literal freshness when an appropriate contextual type is present such that contextually typed
72279                 // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
72280                 // here would be to not mark contextually typed literals as fresh in the first place.
72281                 var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
72282                     getRegularTypeOfLiteralType(type) : type;
72283                 return result;
72284             }
72285             finally {
72286                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
72287                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
72288                 // may hold onto the checker that created it.
72289                 context.contextualType = saveContextualType;
72290                 context.inferenceContext = saveInferenceContext;
72291             }
72292         }
72293         function checkExpressionCached(node, checkMode) {
72294             var links = getNodeLinks(node);
72295             if (!links.resolvedType) {
72296                 if (checkMode && checkMode !== 0 /* Normal */) {
72297                     return checkExpression(node, checkMode);
72298                 }
72299                 // When computing a type that we're going to cache, we need to ignore any ongoing control flow
72300                 // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart
72301                 // to the top of the stack ensures all transient types are computed from a known point.
72302                 var saveFlowLoopStart = flowLoopStart;
72303                 var saveFlowTypeCache = flowTypeCache;
72304                 flowLoopStart = flowLoopCount;
72305                 flowTypeCache = undefined;
72306                 links.resolvedType = checkExpression(node, checkMode);
72307                 flowTypeCache = saveFlowTypeCache;
72308                 flowLoopStart = saveFlowLoopStart;
72309             }
72310             return links.resolvedType;
72311         }
72312         function isTypeAssertion(node) {
72313             node = ts.skipParentheses(node);
72314             return node.kind === 206 /* TypeAssertionExpression */ || node.kind === 224 /* AsExpression */;
72315         }
72316         function checkDeclarationInitializer(declaration, contextualType) {
72317             var initializer = ts.getEffectiveInitializer(declaration);
72318             var type = getQuickTypeOfExpression(initializer) ||
72319                 (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer));
72320             return ts.isParameter(declaration) && declaration.name.kind === 197 /* ArrayBindingPattern */ &&
72321                 isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ?
72322                 padTupleType(type, declaration.name) : type;
72323         }
72324         function padTupleType(type, pattern) {
72325             var patternElements = pattern.elements;
72326             var elementTypes = getTypeArguments(type).slice();
72327             var elementFlags = type.target.elementFlags.slice();
72328             for (var i = getTypeReferenceArity(type); i < patternElements.length; i++) {
72329                 var e = patternElements[i];
72330                 if (i < patternElements.length - 1 || !(e.kind === 198 /* BindingElement */ && e.dotDotDotToken)) {
72331                     elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType);
72332                     elementFlags.push(2 /* Optional */);
72333                     if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) {
72334                         reportImplicitAny(e, anyType);
72335                     }
72336                 }
72337             }
72338             return createTupleType(elementTypes, elementFlags, type.target.readonly);
72339         }
72340         function widenTypeInferredFromInitializer(declaration, type) {
72341             var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type);
72342             if (ts.isInJSFile(declaration)) {
72343                 if (widened.flags & 98304 /* Nullable */) {
72344                     reportImplicitAny(declaration, anyType);
72345                     return anyType;
72346                 }
72347                 else if (isEmptyArrayLiteralType(widened)) {
72348                     reportImplicitAny(declaration, anyArrayType);
72349                     return anyArrayType;
72350                 }
72351             }
72352             return widened;
72353         }
72354         function isLiteralOfContextualType(candidateType, contextualType) {
72355             if (contextualType) {
72356                 if (contextualType.flags & 3145728 /* UnionOrIntersection */) {
72357                     var types = contextualType.types;
72358                     return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); });
72359                 }
72360                 if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) {
72361                     // If the contextual type is a type variable constrained to a primitive type, consider
72362                     // this a literal context for literals of that primitive type. For example, given a
72363                     // type parameter 'T extends string', infer string literal types for T.
72364                     var constraint = getBaseConstraintOfType(contextualType) || unknownType;
72365                     return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
72366                         maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
72367                         maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
72368                         maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) ||
72369                         isLiteralOfContextualType(candidateType, constraint);
72370                 }
72371                 // If the contextual type is a literal of a particular primitive type, we consider this a
72372                 // literal context for all literals of that primitive type.
72373                 return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
72374                     contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
72375                     contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
72376                     contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) ||
72377                     contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */));
72378             }
72379             return false;
72380         }
72381         function isConstContext(node) {
72382             var parent = node.parent;
72383             return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
72384                 (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
72385                 (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent) || ts.isTemplateSpan(parent)) && isConstContext(parent.parent);
72386         }
72387         function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
72388             var type = checkExpression(node, checkMode, forceTuple);
72389             return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
72390                 isTypeAssertion(node) ? type :
72391                     getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
72392         }
72393         function checkPropertyAssignment(node, checkMode) {
72394             // Do not use hasDynamicName here, because that returns false for well known symbols.
72395             // We want to perform checkComputedPropertyName for all computed properties, including
72396             // well known symbols.
72397             if (node.name.kind === 158 /* ComputedPropertyName */) {
72398                 checkComputedPropertyName(node.name);
72399             }
72400             return checkExpressionForMutableLocation(node.initializer, checkMode);
72401         }
72402         function checkObjectLiteralMethod(node, checkMode) {
72403             // Grammar checking
72404             checkGrammarMethod(node);
72405             // Do not use hasDynamicName here, because that returns false for well known symbols.
72406             // We want to perform checkComputedPropertyName for all computed properties, including
72407             // well known symbols.
72408             if (node.name.kind === 158 /* ComputedPropertyName */) {
72409                 checkComputedPropertyName(node.name);
72410             }
72411             var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
72412             return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
72413         }
72414         function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
72415             if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
72416                 var callSignature = getSingleSignature(type, 0 /* Call */, /*allowMembers*/ true);
72417                 var constructSignature = getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ true);
72418                 var signature = callSignature || constructSignature;
72419                 if (signature && signature.typeParameters) {
72420                     var contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */);
72421                     if (contextualType) {
72422                         var contextualSignature = getSingleSignature(getNonNullableType(contextualType), callSignature ? 0 /* Call */ : 1 /* Construct */, /*allowMembers*/ false);
72423                         if (contextualSignature && !contextualSignature.typeParameters) {
72424                             if (checkMode & 8 /* SkipGenericFunctions */) {
72425                                 skippedGenericFunction(node, checkMode);
72426                                 return anyFunctionType;
72427                             }
72428                             var context = getInferenceContext(node);
72429                             // We have an expression that is an argument of a generic function for which we are performing
72430                             // type argument inference. The expression is of a function type with a single generic call
72431                             // signature and a contextual function type with a single non-generic call signature. Now check
72432                             // if the outer function returns a function type with a single non-generic call signature and
72433                             // if some of the outer function type parameters have no inferences so far. If so, we can
72434                             // potentially add inferred type parameters to the outer function return type.
72435                             var returnType = context.signature && getReturnTypeOfSignature(context.signature);
72436                             var returnSignature = returnType && getSingleCallOrConstructSignature(returnType);
72437                             if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
72438                                 // Instantiate the signature with its own type parameters as type arguments, possibly
72439                                 // renaming the type parameters to ensure they have unique names.
72440                                 var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
72441                                 var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
72442                                 // Infer from the parameters of the instantiated signature to the parameters of the
72443                                 // contextual signature starting with an empty set of inference candidates.
72444                                 var inferences_3 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
72445                                 applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
72446                                     inferTypes(inferences_3, source, target, /*priority*/ 0, /*contravariant*/ true);
72447                                 });
72448                                 if (ts.some(inferences_3, hasInferenceCandidates)) {
72449                                     // We have inference candidates, indicating that one or more type parameters are referenced
72450                                     // in the parameter types of the contextual signature. Now also infer from the return type.
72451                                     applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
72452                                         inferTypes(inferences_3, source, target);
72453                                     });
72454                                     // If the type parameters for which we produced candidates do not have any inferences yet,
72455                                     // we adopt the new inference candidates and add the type parameters of the expression type
72456                                     // to the set of inferred type parameters for the outer function return type.
72457                                     if (!hasOverlappingInferences(context.inferences, inferences_3)) {
72458                                         mergeInferences(context.inferences, inferences_3);
72459                                         context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
72460                                         return getOrCreateTypeFromSignature(instantiatedSignature);
72461                                     }
72462                                 }
72463                             }
72464                             return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
72465                         }
72466                     }
72467                 }
72468             }
72469             return type;
72470         }
72471         function skippedGenericFunction(node, checkMode) {
72472             if (checkMode & 2 /* Inferential */) {
72473                 // We have skipped a generic function during inferential typing. Obtain the inference context and
72474                 // indicate this has occurred such that we know a second pass of inference is be needed.
72475                 var context = getInferenceContext(node);
72476                 context.flags |= 4 /* SkippedGenericFunction */;
72477             }
72478         }
72479         function hasInferenceCandidates(info) {
72480             return !!(info.candidates || info.contraCandidates);
72481         }
72482         function hasOverlappingInferences(a, b) {
72483             for (var i = 0; i < a.length; i++) {
72484                 if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
72485                     return true;
72486                 }
72487             }
72488             return false;
72489         }
72490         function mergeInferences(target, source) {
72491             for (var i = 0; i < target.length; i++) {
72492                 if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
72493                     target[i] = source[i];
72494                 }
72495             }
72496         }
72497         function getUniqueTypeParameters(context, typeParameters) {
72498             var result = [];
72499             var oldTypeParameters;
72500             var newTypeParameters;
72501             for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
72502                 var tp = typeParameters_2[_i];
72503                 var name = tp.symbol.escapedName;
72504                 if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
72505                     var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
72506                     var symbol = createSymbol(262144 /* TypeParameter */, newName);
72507                     var newTypeParameter = createTypeParameter(symbol);
72508                     newTypeParameter.target = tp;
72509                     oldTypeParameters = ts.append(oldTypeParameters, tp);
72510                     newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
72511                     result.push(newTypeParameter);
72512                 }
72513                 else {
72514                     result.push(tp);
72515                 }
72516             }
72517             if (newTypeParameters) {
72518                 var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
72519                 for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
72520                     var tp = newTypeParameters_1[_a];
72521                     tp.mapper = mapper;
72522                 }
72523             }
72524             return result;
72525         }
72526         function hasTypeParameterByName(typeParameters, name) {
72527             return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
72528         }
72529         function getUniqueTypeParameterName(typeParameters, baseName) {
72530             var len = baseName.length;
72531             while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
72532                 len--;
72533             var s = baseName.slice(0, len);
72534             for (var index = 1; true; index++) {
72535                 var augmentedName = (s + index);
72536                 if (!hasTypeParameterByName(typeParameters, augmentedName)) {
72537                     return augmentedName;
72538                 }
72539             }
72540         }
72541         function getReturnTypeOfSingleNonGenericCallSignature(funcType) {
72542             var signature = getSingleCallSignature(funcType);
72543             if (signature && !signature.typeParameters) {
72544                 return getReturnTypeOfSignature(signature);
72545             }
72546         }
72547         function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) {
72548             var funcType = checkExpression(expr.expression);
72549             var nonOptionalType = getOptionalExpressionType(funcType, expr.expression);
72550             var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType);
72551             return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType);
72552         }
72553         /**
72554          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
72555          * with computing the type and may not fully check all contained sub-expressions for errors.
72556          */
72557         function getTypeOfExpression(node) {
72558             // Don't bother caching types that require no flow analysis and are quick to compute.
72559             var quickType = getQuickTypeOfExpression(node);
72560             if (quickType) {
72561                 return quickType;
72562             }
72563             // If a type has been cached for the node, return it.
72564             if (node.flags & 67108864 /* TypeCached */ && flowTypeCache) {
72565                 var cachedType = flowTypeCache[getNodeId(node)];
72566                 if (cachedType) {
72567                     return cachedType;
72568                 }
72569             }
72570             var startInvocationCount = flowInvocationCount;
72571             var type = checkExpression(node);
72572             // If control flow analysis was required to determine the type, it is worth caching.
72573             if (flowInvocationCount !== startInvocationCount) {
72574                 var cache = flowTypeCache || (flowTypeCache = []);
72575                 cache[getNodeId(node)] = type;
72576                 ts.setNodeFlags(node, node.flags | 67108864 /* TypeCached */);
72577             }
72578             return type;
72579         }
72580         function getQuickTypeOfExpression(node) {
72581             var expr = ts.skipParentheses(node);
72582             // Optimize for the common case of a call to a function with a single non-generic call
72583             // signature where we can just fetch the return type without checking the arguments.
72584             if (ts.isCallExpression(expr) && expr.expression.kind !== 105 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) {
72585                 var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) :
72586                     getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression));
72587                 if (type) {
72588                     return type;
72589                 }
72590             }
72591             else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
72592                 return getTypeFromTypeNode(expr.type);
72593             }
72594             else if (node.kind === 8 /* NumericLiteral */ || node.kind === 10 /* StringLiteral */ ||
72595                 node.kind === 109 /* TrueKeyword */ || node.kind === 94 /* FalseKeyword */) {
72596                 return checkExpression(node);
72597             }
72598             return undefined;
72599         }
72600         /**
72601          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
72602          * with computing the type and may not fully check all contained sub-expressions for errors.
72603          * It is intended for uses where you know there is no contextual type,
72604          * and requesting the contextual type might cause a circularity or other bad behaviour.
72605          * It sets the contextual type of the node to any before calling getTypeOfExpression.
72606          */
72607         function getContextFreeTypeOfExpression(node) {
72608             var links = getNodeLinks(node);
72609             if (links.contextFreeType) {
72610                 return links.contextFreeType;
72611             }
72612             var saveContextualType = node.contextualType;
72613             node.contextualType = anyType;
72614             try {
72615                 var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
72616                 return type;
72617             }
72618             finally {
72619                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
72620                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
72621                 // may hold onto the checker that created it.
72622                 node.contextualType = saveContextualType;
72623             }
72624         }
72625         function checkExpression(node, checkMode, forceTuple) {
72626             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end });
72627             var saveCurrentNode = currentNode;
72628             currentNode = node;
72629             instantiationCount = 0;
72630             var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
72631             var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
72632             if (isConstEnumObjectType(type)) {
72633                 checkConstEnumAccess(node, type);
72634             }
72635             currentNode = saveCurrentNode;
72636             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
72637             return type;
72638         }
72639         function checkConstEnumAccess(node, type) {
72640             // enum object type for const enums are only permitted in:
72641             // - 'left' in property access
72642             // - 'object' in indexed access
72643             // - target in rhs of import statement
72644             var ok = (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.expression === node) ||
72645                 (node.parent.kind === 202 /* ElementAccessExpression */ && node.parent.expression === node) ||
72646                 ((node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) ||
72647                     (node.parent.kind === 176 /* TypeQuery */ && node.parent.exprName === node)) ||
72648                 (node.parent.kind === 270 /* ExportSpecifier */); // We allow reexporting const enums
72649             if (!ok) {
72650                 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);
72651             }
72652             if (compilerOptions.isolatedModules) {
72653                 ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
72654                 var constEnumDeclaration = type.symbol.valueDeclaration;
72655                 if (constEnumDeclaration.flags & 8388608 /* Ambient */) {
72656                     error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
72657                 }
72658             }
72659         }
72660         function checkParenthesizedExpression(node, checkMode) {
72661             var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
72662             if (tag) {
72663                 return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode);
72664             }
72665             return checkExpression(node.expression, checkMode);
72666         }
72667         function checkExpressionWorker(node, checkMode, forceTuple) {
72668             var kind = node.kind;
72669             if (cancellationToken) {
72670                 // Only bother checking on a few construct kinds.  We don't want to be excessively
72671                 // hitting the cancellation token on every node we check.
72672                 switch (kind) {
72673                     case 221 /* ClassExpression */:
72674                     case 208 /* FunctionExpression */:
72675                     case 209 /* ArrowFunction */:
72676                         cancellationToken.throwIfCancellationRequested();
72677                 }
72678             }
72679             switch (kind) {
72680                 case 78 /* Identifier */:
72681                     return checkIdentifier(node);
72682                 case 107 /* ThisKeyword */:
72683                     return checkThisExpression(node);
72684                 case 105 /* SuperKeyword */:
72685                     return checkSuperExpression(node);
72686                 case 103 /* NullKeyword */:
72687                     return nullWideningType;
72688                 case 14 /* NoSubstitutionTemplateLiteral */:
72689                 case 10 /* StringLiteral */:
72690                     return getFreshTypeOfLiteralType(getLiteralType(node.text));
72691                 case 8 /* NumericLiteral */:
72692                     checkGrammarNumericLiteral(node);
72693                     return getFreshTypeOfLiteralType(getLiteralType(+node.text));
72694                 case 9 /* BigIntLiteral */:
72695                     checkGrammarBigIntLiteral(node);
72696                     return getFreshTypeOfLiteralType(getBigIntLiteralType(node));
72697                 case 109 /* TrueKeyword */:
72698                     return trueType;
72699                 case 94 /* FalseKeyword */:
72700                     return falseType;
72701                 case 218 /* TemplateExpression */:
72702                     return checkTemplateExpression(node);
72703                 case 13 /* RegularExpressionLiteral */:
72704                     return globalRegExpType;
72705                 case 199 /* ArrayLiteralExpression */:
72706                     return checkArrayLiteral(node, checkMode, forceTuple);
72707                 case 200 /* ObjectLiteralExpression */:
72708                     return checkObjectLiteral(node, checkMode);
72709                 case 201 /* PropertyAccessExpression */:
72710                     return checkPropertyAccessExpression(node);
72711                 case 157 /* QualifiedName */:
72712                     return checkQualifiedName(node);
72713                 case 202 /* ElementAccessExpression */:
72714                     return checkIndexedAccess(node);
72715                 case 203 /* CallExpression */:
72716                     if (node.expression.kind === 99 /* ImportKeyword */) {
72717                         return checkImportCallExpression(node);
72718                     }
72719                 // falls through
72720                 case 204 /* NewExpression */:
72721                     return checkCallExpression(node, checkMode);
72722                 case 205 /* TaggedTemplateExpression */:
72723                     return checkTaggedTemplateExpression(node);
72724                 case 207 /* ParenthesizedExpression */:
72725                     return checkParenthesizedExpression(node, checkMode);
72726                 case 221 /* ClassExpression */:
72727                     return checkClassExpression(node);
72728                 case 208 /* FunctionExpression */:
72729                 case 209 /* ArrowFunction */:
72730                     return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
72731                 case 211 /* TypeOfExpression */:
72732                     return checkTypeOfExpression(node);
72733                 case 206 /* TypeAssertionExpression */:
72734                 case 224 /* AsExpression */:
72735                     return checkAssertion(node);
72736                 case 225 /* NonNullExpression */:
72737                     return checkNonNullAssertion(node);
72738                 case 226 /* MetaProperty */:
72739                     return checkMetaProperty(node);
72740                 case 210 /* DeleteExpression */:
72741                     return checkDeleteExpression(node);
72742                 case 212 /* VoidExpression */:
72743                     return checkVoidExpression(node);
72744                 case 213 /* AwaitExpression */:
72745                     return checkAwaitExpression(node);
72746                 case 214 /* PrefixUnaryExpression */:
72747                     return checkPrefixUnaryExpression(node);
72748                 case 215 /* PostfixUnaryExpression */:
72749                     return checkPostfixUnaryExpression(node);
72750                 case 216 /* BinaryExpression */:
72751                     return checkBinaryExpression(node, checkMode);
72752                 case 217 /* ConditionalExpression */:
72753                     return checkConditionalExpression(node, checkMode);
72754                 case 220 /* SpreadElement */:
72755                     return checkSpreadExpression(node, checkMode);
72756                 case 222 /* OmittedExpression */:
72757                     return undefinedWideningType;
72758                 case 219 /* YieldExpression */:
72759                     return checkYieldExpression(node);
72760                 case 227 /* SyntheticExpression */:
72761                     return checkSyntheticExpression(node);
72762                 case 283 /* JsxExpression */:
72763                     return checkJsxExpression(node, checkMode);
72764                 case 273 /* JsxElement */:
72765                     return checkJsxElement(node, checkMode);
72766                 case 274 /* JsxSelfClosingElement */:
72767                     return checkJsxSelfClosingElement(node, checkMode);
72768                 case 277 /* JsxFragment */:
72769                     return checkJsxFragment(node);
72770                 case 281 /* JsxAttributes */:
72771                     return checkJsxAttributes(node, checkMode);
72772                 case 275 /* JsxOpeningElement */:
72773                     ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
72774             }
72775             return errorType;
72776         }
72777         // DECLARATION AND STATEMENT TYPE CHECKING
72778         function checkTypeParameter(node) {
72779             // Grammar Checking
72780             if (node.expression) {
72781                 grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);
72782             }
72783             checkSourceElement(node.constraint);
72784             checkSourceElement(node.default);
72785             var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
72786             // Resolve base constraint to reveal circularity errors
72787             getBaseConstraintOfType(typeParameter);
72788             if (!hasNonCircularTypeParameterDefault(typeParameter)) {
72789                 error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
72790             }
72791             var constraintType = getConstraintOfTypeParameter(typeParameter);
72792             var defaultType = getDefaultFromTypeParameter(typeParameter);
72793             if (constraintType && defaultType) {
72794                 checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
72795             }
72796             if (produceDiagnostics) {
72797                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
72798             }
72799         }
72800         function checkParameter(node) {
72801             // Grammar checking
72802             // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
72803             // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
72804             // or if its FunctionBody is strict code(11.1.5).
72805             checkGrammarDecoratorsAndModifiers(node);
72806             checkVariableLikeDeclaration(node);
72807             var func = ts.getContainingFunction(node);
72808             if (ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) {
72809                 if (!(func.kind === 166 /* Constructor */ && ts.nodeIsPresent(func.body))) {
72810                     error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
72811                 }
72812                 if (func.kind === 166 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") {
72813                     error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name);
72814                 }
72815             }
72816             if (node.questionToken && ts.isBindingPattern(node.name) && func.body) {
72817                 error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
72818             }
72819             if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
72820                 if (func.parameters.indexOf(node) !== 0) {
72821                     error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
72822                 }
72823                 if (func.kind === 166 /* Constructor */ || func.kind === 170 /* ConstructSignature */ || func.kind === 175 /* ConstructorType */) {
72824                     error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter);
72825                 }
72826                 if (func.kind === 209 /* ArrowFunction */) {
72827                     error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
72828                 }
72829                 if (func.kind === 167 /* GetAccessor */ || func.kind === 168 /* SetAccessor */) {
72830                     error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters);
72831                 }
72832             }
72833             // Only check rest parameter type if it's not a binding pattern. Since binding patterns are
72834             // not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
72835             if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) {
72836                 error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
72837             }
72838         }
72839         function checkTypePredicate(node) {
72840             var parent = getTypePredicateParent(node);
72841             if (!parent) {
72842                 // The parent must not be valid.
72843                 error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
72844                 return;
72845             }
72846             var signature = getSignatureFromDeclaration(parent);
72847             var typePredicate = getTypePredicateOfSignature(signature);
72848             if (!typePredicate) {
72849                 return;
72850             }
72851             checkSourceElement(node.type);
72852             var parameterName = node.parameterName;
72853             if (typePredicate.kind === 0 /* This */ || typePredicate.kind === 2 /* AssertsThis */) {
72854                 getTypeFromThisTypeNode(parameterName);
72855             }
72856             else {
72857                 if (typePredicate.parameterIndex >= 0) {
72858                     if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) {
72859                         error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
72860                     }
72861                     else {
72862                         if (typePredicate.type) {
72863                             var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
72864                             checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, 
72865                             /*headMessage*/ undefined, leadingError);
72866                         }
72867                     }
72868                 }
72869                 else if (parameterName) {
72870                     var hasReportedError = false;
72871                     for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
72872                         var name = _a[_i].name;
72873                         if (ts.isBindingPattern(name) &&
72874                             checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
72875                             hasReportedError = true;
72876                             break;
72877                         }
72878                     }
72879                     if (!hasReportedError) {
72880                         error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
72881                     }
72882                 }
72883             }
72884         }
72885         function getTypePredicateParent(node) {
72886             switch (node.parent.kind) {
72887                 case 209 /* ArrowFunction */:
72888                 case 169 /* CallSignature */:
72889                 case 251 /* FunctionDeclaration */:
72890                 case 208 /* FunctionExpression */:
72891                 case 174 /* FunctionType */:
72892                 case 165 /* MethodDeclaration */:
72893                 case 164 /* MethodSignature */:
72894                     var parent = node.parent;
72895                     if (node === parent.type) {
72896                         return parent;
72897                     }
72898             }
72899         }
72900         function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
72901             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
72902                 var element = _a[_i];
72903                 if (ts.isOmittedExpression(element)) {
72904                     continue;
72905                 }
72906                 var name = element.name;
72907                 if (name.kind === 78 /* Identifier */ && name.escapedText === predicateVariableName) {
72908                     error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
72909                     return true;
72910                 }
72911                 else if (name.kind === 197 /* ArrayBindingPattern */ || name.kind === 196 /* ObjectBindingPattern */) {
72912                     if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) {
72913                         return true;
72914                     }
72915                 }
72916             }
72917         }
72918         function checkSignatureDeclaration(node) {
72919             // Grammar checking
72920             if (node.kind === 171 /* IndexSignature */) {
72921                 checkGrammarIndexSignature(node);
72922             }
72923             // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled
72924             else if (node.kind === 174 /* FunctionType */ || node.kind === 251 /* FunctionDeclaration */ || node.kind === 175 /* ConstructorType */ ||
72925                 node.kind === 169 /* CallSignature */ || node.kind === 166 /* Constructor */ ||
72926                 node.kind === 170 /* ConstructSignature */) {
72927                 checkGrammarFunctionLikeDeclaration(node);
72928             }
72929             var functionFlags = ts.getFunctionFlags(node);
72930             if (!(functionFlags & 4 /* Invalid */)) {
72931                 // Async generators prior to ESNext require the __await and __asyncGenerator helpers
72932                 if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 99 /* ESNext */) {
72933                     checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */);
72934                 }
72935                 // Async functions prior to ES2017 require the __awaiter helper
72936                 if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
72937                     checkExternalEmitHelpers(node, 64 /* Awaiter */);
72938                 }
72939                 // Generator functions, Async functions, and Async Generator functions prior to
72940                 // ES2015 require the __generator helper
72941                 if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) {
72942                     checkExternalEmitHelpers(node, 128 /* Generator */);
72943                 }
72944             }
72945             checkTypeParameters(node.typeParameters);
72946             ts.forEach(node.parameters, checkParameter);
72947             // TODO(rbuckton): Should we start checking JSDoc types?
72948             if (node.type) {
72949                 checkSourceElement(node.type);
72950             }
72951             if (produceDiagnostics) {
72952                 checkCollisionWithArgumentsInGeneratedCode(node);
72953                 var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
72954                 if (noImplicitAny && !returnTypeNode) {
72955                     switch (node.kind) {
72956                         case 170 /* ConstructSignature */:
72957                             error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
72958                             break;
72959                         case 169 /* CallSignature */:
72960                             error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
72961                             break;
72962                     }
72963                 }
72964                 if (returnTypeNode) {
72965                     var functionFlags_1 = ts.getFunctionFlags(node);
72966                     if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
72967                         var returnType = getTypeFromTypeNode(returnTypeNode);
72968                         if (returnType === voidType) {
72969                             error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation);
72970                         }
72971                         else {
72972                             // Naively, one could check that Generator<any, any, any> is assignable to the return type annotation.
72973                             // However, that would not catch the error in the following case.
72974                             //
72975                             //    interface BadGenerator extends Iterable<number>, Iterator<string> { }
72976                             //    function* g(): BadGenerator { } // Iterable and Iterator have different types!
72977                             //
72978                             var generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType;
72979                             var generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || generatorYieldType;
72980                             var generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || unknownType;
72981                             var generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags_1 & 2 /* Async */));
72982                             checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode);
72983                         }
72984                     }
72985                     else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) {
72986                         checkAsyncFunctionReturnType(node, returnTypeNode);
72987                     }
72988                 }
72989                 if (node.kind !== 171 /* IndexSignature */ && node.kind !== 308 /* JSDocFunctionType */) {
72990                     registerForUnusedIdentifiersCheck(node);
72991                 }
72992             }
72993         }
72994         function checkClassForDuplicateDeclarations(node) {
72995             var instanceNames = new ts.Map();
72996             var staticNames = new ts.Map();
72997             // instance and static private identifiers share the same scope
72998             var privateIdentifiers = new ts.Map();
72999             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
73000                 var member = _a[_i];
73001                 if (member.kind === 166 /* Constructor */) {
73002                     for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
73003                         var param = _c[_b];
73004                         if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) {
73005                             addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */);
73006                         }
73007                     }
73008                 }
73009                 else {
73010                     var isStatic = ts.hasSyntacticModifier(member, 32 /* Static */);
73011                     var name = member.name;
73012                     if (!name) {
73013                         return;
73014                     }
73015                     var names = ts.isPrivateIdentifier(name) ? privateIdentifiers :
73016                         isStatic ? staticNames :
73017                             instanceNames;
73018                     var memberName = name && ts.getPropertyNameForPropertyNameNode(name);
73019                     if (memberName) {
73020                         switch (member.kind) {
73021                             case 167 /* GetAccessor */:
73022                                 addName(names, name, memberName, 1 /* GetAccessor */);
73023                                 break;
73024                             case 168 /* SetAccessor */:
73025                                 addName(names, name, memberName, 2 /* SetAccessor */);
73026                                 break;
73027                             case 163 /* PropertyDeclaration */:
73028                                 addName(names, name, memberName, 3 /* GetOrSetAccessor */);
73029                                 break;
73030                             case 165 /* MethodDeclaration */:
73031                                 addName(names, name, memberName, 8 /* Method */);
73032                                 break;
73033                         }
73034                     }
73035                 }
73036             }
73037             function addName(names, location, name, meaning) {
73038                 var prev = names.get(name);
73039                 if (prev) {
73040                     if (prev & 8 /* Method */) {
73041                         if (meaning !== 8 /* Method */) {
73042                             error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
73043                         }
73044                     }
73045                     else if (prev & meaning) {
73046                         error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
73047                     }
73048                     else {
73049                         names.set(name, prev | meaning);
73050                     }
73051                 }
73052                 else {
73053                     names.set(name, meaning);
73054                 }
73055             }
73056         }
73057         /**
73058          * Static members being set on a constructor function may conflict with built-in properties
73059          * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable
73060          * built-in properties. This check issues a transpile error when a class has a static
73061          * member with the same name as a non-writable built-in property.
73062          *
73063          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3
73064          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5
73065          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor
73066          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances
73067          */
73068         function checkClassForStaticPropertyNameConflicts(node) {
73069             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
73070                 var member = _a[_i];
73071                 var memberNameNode = member.name;
73072                 var isStatic = ts.hasSyntacticModifier(member, 32 /* Static */);
73073                 if (isStatic && memberNameNode) {
73074                     var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode);
73075                     switch (memberName) {
73076                         case "name":
73077                         case "length":
73078                         case "caller":
73079                         case "arguments":
73080                         case "prototype":
73081                             var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
73082                             var className = getNameOfSymbolAsWritten(getSymbolOfNode(node));
73083                             error(memberNameNode, message, memberName, className);
73084                             break;
73085                     }
73086                 }
73087             }
73088         }
73089         function checkObjectTypeForDuplicateDeclarations(node) {
73090             var names = new ts.Map();
73091             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
73092                 var member = _a[_i];
73093                 if (member.kind === 162 /* PropertySignature */) {
73094                     var memberName = void 0;
73095                     var name = member.name;
73096                     switch (name.kind) {
73097                         case 10 /* StringLiteral */:
73098                         case 8 /* NumericLiteral */:
73099                             memberName = name.text;
73100                             break;
73101                         case 78 /* Identifier */:
73102                             memberName = ts.idText(name);
73103                             break;
73104                         default:
73105                             continue;
73106                     }
73107                     if (names.get(memberName)) {
73108                         error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName);
73109                         error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
73110                     }
73111                     else {
73112                         names.set(memberName, true);
73113                     }
73114                 }
73115             }
73116         }
73117         function checkTypeForDuplicateIndexSignatures(node) {
73118             if (node.kind === 253 /* InterfaceDeclaration */) {
73119                 var nodeSymbol = getSymbolOfNode(node);
73120                 // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration
73121                 // to prevent this run check only for the first declaration of a given kind
73122                 if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
73123                     return;
73124                 }
73125             }
73126             // TypeScript 1.0 spec (April 2014)
73127             // 3.7.4: An object type can contain at most one string index signature and one numeric index signature.
73128             // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration
73129             var indexSymbol = getIndexSymbol(getSymbolOfNode(node));
73130             if (indexSymbol) {
73131                 var seenNumericIndexer = false;
73132                 var seenStringIndexer = false;
73133                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
73134                     var decl = _a[_i];
73135                     var declaration = decl;
73136                     if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
73137                         switch (declaration.parameters[0].type.kind) {
73138                             case 147 /* StringKeyword */:
73139                                 if (!seenStringIndexer) {
73140                                     seenStringIndexer = true;
73141                                 }
73142                                 else {
73143                                     error(declaration, ts.Diagnostics.Duplicate_string_index_signature);
73144                                 }
73145                                 break;
73146                             case 144 /* NumberKeyword */:
73147                                 if (!seenNumericIndexer) {
73148                                     seenNumericIndexer = true;
73149                                 }
73150                                 else {
73151                                     error(declaration, ts.Diagnostics.Duplicate_number_index_signature);
73152                                 }
73153                                 break;
73154                         }
73155                     }
73156                 }
73157             }
73158         }
73159         function checkPropertyDeclaration(node) {
73160             // Grammar checking
73161             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node))
73162                 checkGrammarComputedPropertyName(node.name);
73163             checkVariableLikeDeclaration(node);
73164             // Private class fields transformation relies on WeakMaps.
73165             if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) {
73166                 for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) {
73167                     getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */;
73168                 }
73169             }
73170         }
73171         function checkPropertySignature(node) {
73172             if (ts.isPrivateIdentifier(node.name)) {
73173                 error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
73174             }
73175             return checkPropertyDeclaration(node);
73176         }
73177         function checkMethodDeclaration(node) {
73178             // Grammar checking
73179             if (!checkGrammarMethod(node))
73180                 checkGrammarComputedPropertyName(node.name);
73181             if (ts.isPrivateIdentifier(node.name)) {
73182                 error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier);
73183             }
73184             // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration
73185             checkFunctionOrMethodDeclaration(node);
73186             // Abstract methods cannot have an implementation.
73187             // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node.
73188             if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 165 /* MethodDeclaration */ && node.body) {
73189                 error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name));
73190             }
73191         }
73192         function checkConstructorDeclaration(node) {
73193             // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function.
73194             checkSignatureDeclaration(node);
73195             // Grammar check for checking only related to constructorDeclaration
73196             if (!checkGrammarConstructorTypeParameters(node))
73197                 checkGrammarConstructorTypeAnnotation(node);
73198             checkSourceElement(node.body);
73199             var symbol = getSymbolOfNode(node);
73200             var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind);
73201             // Only type check the symbol once
73202             if (node === firstDeclaration) {
73203                 checkFunctionOrConstructorSymbol(symbol);
73204             }
73205             // exit early in the case of signature - super checks are not relevant to them
73206             if (ts.nodeIsMissing(node.body)) {
73207                 return;
73208             }
73209             if (!produceDiagnostics) {
73210                 return;
73211             }
73212             function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) {
73213                 if (ts.isPrivateIdentifierPropertyDeclaration(n)) {
73214                     return true;
73215                 }
73216                 return n.kind === 163 /* PropertyDeclaration */ &&
73217                     !ts.hasSyntacticModifier(n, 32 /* Static */) &&
73218                     !!n.initializer;
73219             }
73220             // TS 1.0 spec (April 2014): 8.3.2
73221             // Constructors of classes with no extends clause may not contain super calls, whereas
73222             // constructors of derived classes must contain at least one super call somewhere in their function body.
73223             var containingClassDecl = node.parent;
73224             if (ts.getClassExtendsHeritageElement(containingClassDecl)) {
73225                 captureLexicalThis(node.parent, containingClassDecl);
73226                 var classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
73227                 var superCall = findFirstSuperCall(node.body);
73228                 if (superCall) {
73229                     if (classExtendsNull) {
73230                         error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
73231                     }
73232                     // The first statement in the body of a constructor (excluding prologue directives) must be a super call
73233                     // if both of the following are true:
73234                     // - The containing class is a derived class.
73235                     // - The constructor declares parameter properties
73236                     //   or the containing class declares instance member variables with initializers.
73237                     var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) &&
73238                         (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) ||
73239                             ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92 /* ParameterPropertyModifier */); }));
73240                     // Skip past any prologue directives to find the first statement
73241                     // to ensure that it was a super call.
73242                     if (superCallShouldBeFirst) {
73243                         var statements = node.body.statements;
73244                         var superCallStatement = void 0;
73245                         for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) {
73246                             var statement = statements_4[_i];
73247                             if (statement.kind === 233 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
73248                                 superCallStatement = statement;
73249                                 break;
73250                             }
73251                             if (!ts.isPrologueDirective(statement)) {
73252                                 break;
73253                             }
73254                         }
73255                         if (!superCallStatement) {
73256                             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);
73257                         }
73258                     }
73259                 }
73260                 else if (!classExtendsNull) {
73261                     error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
73262                 }
73263             }
73264         }
73265         function checkAccessorDeclaration(node) {
73266             if (produceDiagnostics) {
73267                 // Grammar checking accessors
73268                 if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node))
73269                     checkGrammarComputedPropertyName(node.name);
73270                 checkDecorators(node);
73271                 checkSignatureDeclaration(node);
73272                 if (node.kind === 167 /* GetAccessor */) {
73273                     if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) {
73274                         if (!(node.flags & 512 /* HasExplicitReturn */)) {
73275                             error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value);
73276                         }
73277                     }
73278                 }
73279                 // Do not use hasDynamicName here, because that returns false for well known symbols.
73280                 // We want to perform checkComputedPropertyName for all computed properties, including
73281                 // well known symbols.
73282                 if (node.name.kind === 158 /* ComputedPropertyName */) {
73283                     checkComputedPropertyName(node.name);
73284                 }
73285                 if (ts.isPrivateIdentifier(node.name)) {
73286                     error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier);
73287                 }
73288                 if (hasBindableName(node)) {
73289                     // TypeScript 1.0 spec (April 2014): 8.4.3
73290                     // Accessors for the same member name must specify the same accessibility.
73291                     var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */;
73292                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
73293                     if (otherAccessor) {
73294                         var nodeFlags = ts.getEffectiveModifierFlags(node);
73295                         var otherFlags = ts.getEffectiveModifierFlags(otherAccessor);
73296                         if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) {
73297                             error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility);
73298                         }
73299                         if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) {
73300                             error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
73301                         }
73302                         // TypeScript 1.0 spec (April 2014): 4.5
73303                         // If both accessors include type annotations, the specified types must be identical.
73304                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type);
73305                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type);
73306                     }
73307                 }
73308                 var returnType = getTypeOfAccessors(getSymbolOfNode(node));
73309                 if (node.kind === 167 /* GetAccessor */) {
73310                     checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
73311                 }
73312             }
73313             checkSourceElement(node.body);
73314         }
73315         function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) {
73316             var firstType = getAnnotatedType(first);
73317             var secondType = getAnnotatedType(second);
73318             if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) {
73319                 error(first, message);
73320             }
73321         }
73322         function checkMissingDeclaration(node) {
73323             checkDecorators(node);
73324         }
73325         function getEffectiveTypeArguments(node, typeParameters) {
73326             return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node));
73327         }
73328         function checkTypeArgumentConstraints(node, typeParameters) {
73329             var typeArguments;
73330             var mapper;
73331             var result = true;
73332             for (var i = 0; i < typeParameters.length; i++) {
73333                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
73334                 if (constraint) {
73335                     if (!typeArguments) {
73336                         typeArguments = getEffectiveTypeArguments(node, typeParameters);
73337                         mapper = createTypeMapper(typeParameters, typeArguments);
73338                     }
73339                     result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
73340                 }
73341             }
73342             return result;
73343         }
73344         function getTypeParametersForTypeReference(node) {
73345             var type = getTypeFromTypeReference(node);
73346             if (type !== errorType) {
73347                 var symbol = getNodeLinks(node).resolvedSymbol;
73348                 if (symbol) {
73349                     return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters ||
73350                         (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined);
73351                 }
73352             }
73353             return undefined;
73354         }
73355         function checkTypeReferenceNode(node) {
73356             checkGrammarTypeArguments(node, node.typeArguments);
73357             if (node.kind === 173 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) {
73358                 grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
73359             }
73360             ts.forEach(node.typeArguments, checkSourceElement);
73361             var type = getTypeFromTypeReference(node);
73362             if (type !== errorType) {
73363                 if (node.typeArguments && produceDiagnostics) {
73364                     var typeParameters = getTypeParametersForTypeReference(node);
73365                     if (typeParameters) {
73366                         checkTypeArgumentConstraints(node, typeParameters);
73367                     }
73368                 }
73369                 var symbol = getNodeLinks(node).resolvedSymbol;
73370                 if (symbol) {
73371                     if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) {
73372                         addDeprecatedSuggestion(getDeprecatedSuggestionNode(node), symbol.declarations, symbol.escapedName);
73373                     }
73374                     if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) {
73375                         error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type));
73376                     }
73377                 }
73378             }
73379         }
73380         function getTypeArgumentConstraint(node) {
73381             var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType);
73382             if (!typeReferenceNode)
73383                 return undefined;
73384             var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217
73385             var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
73386             return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
73387         }
73388         function checkTypeQuery(node) {
73389             getTypeFromTypeQueryNode(node);
73390         }
73391         function checkTypeLiteral(node) {
73392             ts.forEach(node.members, checkSourceElement);
73393             if (produceDiagnostics) {
73394                 var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
73395                 checkIndexConstraints(type);
73396                 checkTypeForDuplicateIndexSignatures(node);
73397                 checkObjectTypeForDuplicateDeclarations(node);
73398             }
73399         }
73400         function checkArrayType(node) {
73401             checkSourceElement(node.elementType);
73402         }
73403         function checkTupleType(node) {
73404             var elementTypes = node.elements;
73405             var seenOptionalElement = false;
73406             var seenRestElement = false;
73407             var hasNamedElement = ts.some(elementTypes, ts.isNamedTupleMember);
73408             for (var _i = 0, elementTypes_1 = elementTypes; _i < elementTypes_1.length; _i++) {
73409                 var e = elementTypes_1[_i];
73410                 if (e.kind !== 192 /* NamedTupleMember */ && hasNamedElement) {
73411                     grammarErrorOnNode(e, ts.Diagnostics.Tuple_members_must_all_have_names_or_all_not_have_names);
73412                     break;
73413                 }
73414                 var flags = getTupleElementFlags(e);
73415                 if (flags & 8 /* Variadic */) {
73416                     var type = getTypeFromTypeNode(e.type);
73417                     if (!isArrayLikeType(type)) {
73418                         error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type);
73419                         break;
73420                     }
73421                     if (isArrayType(type) || isTupleType(type) && type.target.combinedFlags & 4 /* Rest */) {
73422                         seenRestElement = true;
73423                     }
73424                 }
73425                 else if (flags & 4 /* Rest */) {
73426                     if (seenRestElement) {
73427                         grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_cannot_follow_another_rest_element);
73428                         break;
73429                     }
73430                     seenRestElement = true;
73431                 }
73432                 else if (flags & 2 /* Optional */) {
73433                     if (seenRestElement) {
73434                         grammarErrorOnNode(e, ts.Diagnostics.An_optional_element_cannot_follow_a_rest_element);
73435                         break;
73436                     }
73437                     seenOptionalElement = true;
73438                 }
73439                 else if (seenOptionalElement) {
73440                     grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element);
73441                     break;
73442                 }
73443             }
73444             ts.forEach(node.elements, checkSourceElement);
73445             getTypeFromTypeNode(node);
73446         }
73447         function checkUnionOrIntersectionType(node) {
73448             ts.forEach(node.types, checkSourceElement);
73449             getTypeFromTypeNode(node);
73450         }
73451         function checkIndexedAccessIndexType(type, accessNode) {
73452             if (!(type.flags & 8388608 /* IndexedAccess */)) {
73453                 return type;
73454             }
73455             // Check if the index type is assignable to 'keyof T' for the object type.
73456             var objectType = type.objectType;
73457             var indexType = type.indexType;
73458             if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) {
73459                 if (accessNode.kind === 202 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) &&
73460                     ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
73461                     error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
73462                 }
73463                 return type;
73464             }
73465             // Check if we're indexing with a numeric type and if either object or index types
73466             // is a generic type with a constraint that has a numeric index signature.
73467             var apparentObjectType = getApparentType(objectType);
73468             if (getIndexInfoOfType(apparentObjectType, 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
73469                 return type;
73470             }
73471             if (isGenericObjectType(objectType)) {
73472                 var propertyName_1 = getPropertyNameFromIndex(indexType, accessNode);
73473                 if (propertyName_1) {
73474                     var propertySymbol = forEachType(apparentObjectType, function (t) { return getPropertyOfType(t, propertyName_1); });
73475                     if (propertySymbol && ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 24 /* NonPublicAccessibilityModifier */) {
73476                         error(accessNode, ts.Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, ts.unescapeLeadingUnderscores(propertyName_1));
73477                         return errorType;
73478                     }
73479                 }
73480             }
73481             error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
73482             return errorType;
73483         }
73484         function checkIndexedAccessType(node) {
73485             checkSourceElement(node.objectType);
73486             checkSourceElement(node.indexType);
73487             checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
73488         }
73489         function checkMappedType(node) {
73490             checkSourceElement(node.typeParameter);
73491             checkSourceElement(node.nameType);
73492             checkSourceElement(node.type);
73493             if (!node.type) {
73494                 reportImplicitAny(node, anyType);
73495             }
73496             var type = getTypeFromMappedTypeNode(node);
73497             var nameType = getNameTypeFromMappedType(type);
73498             if (nameType) {
73499                 checkTypeAssignableTo(nameType, keyofConstraintType, node.nameType);
73500             }
73501             else {
73502                 var constraintType = getConstraintTypeFromMappedType(type);
73503                 checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter));
73504             }
73505         }
73506         function checkThisType(node) {
73507             getTypeFromThisTypeNode(node);
73508         }
73509         function checkTypeOperator(node) {
73510             checkGrammarTypeOperatorNode(node);
73511             checkSourceElement(node.type);
73512         }
73513         function checkConditionalType(node) {
73514             ts.forEachChild(node, checkSourceElement);
73515         }
73516         function checkInferType(node) {
73517             if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 184 /* ConditionalType */ && n.parent.extendsType === n; })) {
73518                 grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
73519             }
73520             checkSourceElement(node.typeParameter);
73521             registerForUnusedIdentifiersCheck(node);
73522         }
73523         function checkTemplateLiteralType(node) {
73524             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
73525                 var span = _a[_i];
73526                 checkSourceElement(span.type);
73527                 var type = getTypeFromTypeNode(span.type);
73528                 checkTypeAssignableTo(type, templateConstraintType, span.type);
73529             }
73530             getTypeFromTypeNode(node);
73531         }
73532         function checkImportType(node) {
73533             checkSourceElement(node.argument);
73534             getTypeFromTypeNode(node);
73535         }
73536         function checkNamedTupleMember(node) {
73537             if (node.dotDotDotToken && node.questionToken) {
73538                 grammarErrorOnNode(node, ts.Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest);
73539             }
73540             if (node.type.kind === 180 /* OptionalType */) {
73541                 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);
73542             }
73543             if (node.type.kind === 181 /* RestType */) {
73544                 grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type);
73545             }
73546             checkSourceElement(node.type);
73547             getTypeFromTypeNode(node);
73548         }
73549         function isPrivateWithinAmbient(node) {
73550             return (ts.hasEffectiveModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */);
73551         }
73552         function getEffectiveDeclarationFlags(n, flagsToCheck) {
73553             var flags = ts.getCombinedModifierFlags(n);
73554             // children of classes (even ambient classes) should not be marked as ambient or export
73555             // because those flags have no useful semantics there.
73556             if (n.parent.kind !== 253 /* InterfaceDeclaration */ &&
73557                 n.parent.kind !== 252 /* ClassDeclaration */ &&
73558                 n.parent.kind !== 221 /* ClassExpression */ &&
73559                 n.flags & 8388608 /* Ambient */) {
73560                 if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
73561                     // It is nested in an ambient context, which means it is automatically exported
73562                     flags |= 1 /* Export */;
73563                 }
73564                 flags |= 2 /* Ambient */;
73565             }
73566             return flags & flagsToCheck;
73567         }
73568         function checkFunctionOrConstructorSymbol(symbol) {
73569             if (!produceDiagnostics) {
73570                 return;
73571             }
73572             function getCanonicalOverload(overloads, implementation) {
73573                 // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration
73574                 // Error on all deviations from this canonical set of flags
73575                 // The caveat is that if some overloads are defined in lib.d.ts, we don't want to
73576                 // report the errors on those. To achieve this, we will say that the implementation is
73577                 // the canonical signature only if it is in the same container as the first overload
73578                 var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent;
73579                 return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
73580             }
73581             function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) {
73582                 // Error if some overloads have a flag that is not shared by all overloads. To find the
73583                 // deviations, we XOR someOverloadFlags with allOverloadFlags
73584                 var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
73585                 if (someButNotAllOverloadFlags !== 0) {
73586                     var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck);
73587                     ts.forEach(overloads, function (o) {
73588                         var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1;
73589                         if (deviation & 1 /* Export */) {
73590                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
73591                         }
73592                         else if (deviation & 2 /* Ambient */) {
73593                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
73594                         }
73595                         else if (deviation & (8 /* Private */ | 16 /* Protected */)) {
73596                             error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
73597                         }
73598                         else if (deviation & 128 /* Abstract */) {
73599                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
73600                         }
73601                     });
73602                 }
73603             }
73604             function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) {
73605                 if (someHaveQuestionToken !== allHaveQuestionToken) {
73606                     var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation));
73607                     ts.forEach(overloads, function (o) {
73608                         var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1;
73609                         if (deviation) {
73610                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required);
73611                         }
73612                     });
73613                 }
73614             }
73615             var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */;
73616             var someNodeFlags = 0 /* None */;
73617             var allNodeFlags = flagsToCheck;
73618             var someHaveQuestionToken = false;
73619             var allHaveQuestionToken = true;
73620             var hasOverloads = false;
73621             var bodyDeclaration;
73622             var lastSeenNonAmbientDeclaration;
73623             var previousDeclaration;
73624             var declarations = symbol.declarations;
73625             var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0;
73626             function reportImplementationExpectedError(node) {
73627                 if (node.name && ts.nodeIsMissing(node.name)) {
73628                     return;
73629                 }
73630                 var seen = false;
73631                 var subsequentNode = ts.forEachChild(node.parent, function (c) {
73632                     if (seen) {
73633                         return c;
73634                     }
73635                     else {
73636                         seen = c === node;
73637                     }
73638                 });
73639                 // We may be here because of some extra nodes between overloads that could not be parsed into a valid node.
73640                 // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here.
73641                 if (subsequentNode && subsequentNode.pos === node.end) {
73642                     if (subsequentNode.kind === node.kind) {
73643                         var errorNode_1 = subsequentNode.name || subsequentNode;
73644                         var subsequentName = subsequentNode.name;
73645                         if (node.name && subsequentName && (
73646                         // both are private identifiers
73647                         ts.isPrivateIdentifier(node.name) && ts.isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText ||
73648                             // Both are computed property names
73649                             // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!)
73650                             ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) ||
73651                             // Both are literal property names that are the same.
73652                             ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) &&
73653                                 ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
73654                             var reportError = (node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */) &&
73655                                 ts.hasSyntacticModifier(node, 32 /* Static */) !== ts.hasSyntacticModifier(subsequentNode, 32 /* Static */);
73656                             // we can get here in two cases
73657                             // 1. mixed static and instance class members
73658                             // 2. something with the same name was defined before the set of overloads that prevents them from merging
73659                             // here we'll report error only for the first case since for second we should already report error in binder
73660                             if (reportError) {
73661                                 var diagnostic = ts.hasSyntacticModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static;
73662                                 error(errorNode_1, diagnostic);
73663                             }
73664                             return;
73665                         }
73666                         if (ts.nodeIsPresent(subsequentNode.body)) {
73667                             error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name));
73668                             return;
73669                         }
73670                     }
73671                 }
73672                 var errorNode = node.name || node;
73673                 if (isConstructor) {
73674                     error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing);
73675                 }
73676                 else {
73677                     // Report different errors regarding non-consecutive blocks of declarations depending on whether
73678                     // the node in question is abstract.
73679                     if (ts.hasSyntacticModifier(node, 128 /* Abstract */)) {
73680                         error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
73681                     }
73682                     else {
73683                         error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
73684                     }
73685                 }
73686             }
73687             var duplicateFunctionDeclaration = false;
73688             var multipleConstructorImplementation = false;
73689             var hasNonAmbientClass = false;
73690             var functionDeclarations = [];
73691             for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
73692                 var current = declarations_4[_i];
73693                 var node = current;
73694                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
73695                 var inAmbientContextOrInterface = node.parent && (node.parent.kind === 253 /* InterfaceDeclaration */ || node.parent.kind === 177 /* TypeLiteral */) || inAmbientContext;
73696                 if (inAmbientContextOrInterface) {
73697                     // check if declarations are consecutive only if they are non-ambient
73698                     // 1. ambient declarations can be interleaved
73699                     // i.e. this is legal
73700                     //     declare function foo();
73701                     //     declare function bar();
73702                     //     declare function foo();
73703                     // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one
73704                     previousDeclaration = undefined;
73705                 }
73706                 if ((node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */) && !inAmbientContext) {
73707                     hasNonAmbientClass = true;
73708                 }
73709                 if (node.kind === 251 /* FunctionDeclaration */ || node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */ || node.kind === 166 /* Constructor */) {
73710                     functionDeclarations.push(node);
73711                     var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
73712                     someNodeFlags |= currentNodeFlags;
73713                     allNodeFlags &= currentNodeFlags;
73714                     someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node);
73715                     allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node);
73716                     var bodyIsPresent = ts.nodeIsPresent(node.body);
73717                     if (bodyIsPresent && bodyDeclaration) {
73718                         if (isConstructor) {
73719                             multipleConstructorImplementation = true;
73720                         }
73721                         else {
73722                             duplicateFunctionDeclaration = true;
73723                         }
73724                     }
73725                     else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) {
73726                         reportImplementationExpectedError(previousDeclaration);
73727                     }
73728                     if (bodyIsPresent) {
73729                         if (!bodyDeclaration) {
73730                             bodyDeclaration = node;
73731                         }
73732                     }
73733                     else {
73734                         hasOverloads = true;
73735                     }
73736                     previousDeclaration = node;
73737                     if (!inAmbientContextOrInterface) {
73738                         lastSeenNonAmbientDeclaration = node;
73739                     }
73740                 }
73741             }
73742             if (multipleConstructorImplementation) {
73743                 ts.forEach(functionDeclarations, function (declaration) {
73744                     error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed);
73745                 });
73746             }
73747             if (duplicateFunctionDeclaration) {
73748                 ts.forEach(functionDeclarations, function (declaration) {
73749                     error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_function_implementation);
73750                 });
73751             }
73752             if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */) {
73753                 // A non-ambient class cannot be an implementation for a non-constructor function/class merge
73754                 // TODO: The below just replicates our older error from when classes and functions were
73755                 // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list"
73756                 // might be warranted. :shrug:
73757                 ts.forEach(declarations, function (declaration) {
73758                     addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations);
73759                 });
73760             }
73761             // Abstract methods can't have an implementation -- in particular, they don't need one.
73762             if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body &&
73763                 !ts.hasSyntacticModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) {
73764                 reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
73765             }
73766             if (hasOverloads) {
73767                 checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
73768                 checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
73769                 if (bodyDeclaration) {
73770                     var signatures = getSignaturesOfSymbol(symbol);
73771                     var bodySignature = getSignatureFromDeclaration(bodyDeclaration);
73772                     for (var _a = 0, signatures_10 = signatures; _a < signatures_10.length; _a++) {
73773                         var signature = signatures_10[_a];
73774                         if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
73775                             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));
73776                             break;
73777                         }
73778                     }
73779                 }
73780             }
73781         }
73782         function checkExportsOnMergedDeclarations(node) {
73783             if (!produceDiagnostics) {
73784                 return;
73785             }
73786             // if localSymbol is defined on node then node itself is exported - check is required
73787             var symbol = node.localSymbol;
73788             if (!symbol) {
73789                 // local symbol is undefined => this declaration is non-exported.
73790                 // however symbol might contain other declarations that are exported
73791                 symbol = getSymbolOfNode(node);
73792                 if (!symbol.exportSymbol) {
73793                     // this is a pure local symbol (all declarations are non-exported) - no need to check anything
73794                     return;
73795                 }
73796             }
73797             // run the check only for the first declaration in the list
73798             if (ts.getDeclarationOfKind(symbol, node.kind) !== node) {
73799                 return;
73800             }
73801             var exportedDeclarationSpaces = 0 /* None */;
73802             var nonExportedDeclarationSpaces = 0 /* None */;
73803             var defaultExportedDeclarationSpaces = 0 /* None */;
73804             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
73805                 var d = _a[_i];
73806                 var declarationSpaces = getDeclarationSpaces(d);
73807                 var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */);
73808                 if (effectiveDeclarationFlags & 1 /* Export */) {
73809                     if (effectiveDeclarationFlags & 512 /* Default */) {
73810                         defaultExportedDeclarationSpaces |= declarationSpaces;
73811                     }
73812                     else {
73813                         exportedDeclarationSpaces |= declarationSpaces;
73814                     }
73815                 }
73816                 else {
73817                     nonExportedDeclarationSpaces |= declarationSpaces;
73818                 }
73819             }
73820             // Spaces for anything not declared a 'default export'.
73821             var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
73822             var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
73823             var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
73824             if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
73825                 // declaration spaces for exported and non-exported declarations intersect
73826                 for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) {
73827                     var d = _c[_b];
73828                     var declarationSpaces = getDeclarationSpaces(d);
73829                     var name = ts.getNameOfDeclaration(d);
73830                     // Only error on the declarations that contributed to the intersecting spaces.
73831                     if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
73832                         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));
73833                     }
73834                     else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
73835                         error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name));
73836                     }
73837                 }
73838             }
73839             function getDeclarationSpaces(decl) {
73840                 var d = decl;
73841                 switch (d.kind) {
73842                     case 253 /* InterfaceDeclaration */:
73843                     case 254 /* TypeAliasDeclaration */:
73844                     // A jsdoc typedef and callback are, by definition, type aliases.
73845                     // falls through
73846                     case 331 /* JSDocTypedefTag */:
73847                     case 324 /* JSDocCallbackTag */:
73848                     case 325 /* JSDocEnumTag */:
73849                         return 2 /* ExportType */;
73850                     case 256 /* ModuleDeclaration */:
73851                         return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
73852                             ? 4 /* ExportNamespace */ | 1 /* ExportValue */
73853                             : 4 /* ExportNamespace */;
73854                     case 252 /* ClassDeclaration */:
73855                     case 255 /* EnumDeclaration */:
73856                     case 291 /* EnumMember */:
73857                         return 2 /* ExportType */ | 1 /* ExportValue */;
73858                     case 297 /* SourceFile */:
73859                         return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
73860                     case 266 /* ExportAssignment */:
73861                         // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
73862                         if (!ts.isEntityNameExpression(d.expression)) {
73863                             return 1 /* ExportValue */;
73864                         }
73865                         d = d.expression;
73866                     // The below options all declare an Alias, which is allowed to merge with other values within the importing module.
73867                     // falls through
73868                     case 260 /* ImportEqualsDeclaration */:
73869                     case 263 /* NamespaceImport */:
73870                     case 262 /* ImportClause */:
73871                         var result_12 = 0 /* None */;
73872                         var target = resolveAlias(getSymbolOfNode(d));
73873                         ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); });
73874                         return result_12;
73875                     case 249 /* VariableDeclaration */:
73876                     case 198 /* BindingElement */:
73877                     case 251 /* FunctionDeclaration */:
73878                     case 265 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
73879                     case 78 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098
73880                         // Identifiers are used as declarations of assignment declarations whose parents may be
73881                         // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});`
73882                         // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it)
73883                         // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;`
73884                         // all of which are pretty much always values, or at least imply a value meaning.
73885                         // It may be apprpriate to treat these as aliases in the future.
73886                         return 1 /* ExportValue */;
73887                     default:
73888                         return ts.Debug.failBadSyntaxKind(d);
73889                 }
73890             }
73891         }
73892         function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, arg0) {
73893             var promisedType = getPromisedTypeOfPromise(type, errorNode);
73894             return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
73895         }
73896         /**
73897          * Gets the "promised type" of a promise.
73898          * @param type The type of the promise.
73899          * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
73900          */
73901         function getPromisedTypeOfPromise(type, errorNode) {
73902             //
73903             //  { // type
73904             //      then( // thenFunction
73905             //          onfulfilled: ( // onfulfilledParameterType
73906             //              value: T // valueParameterType
73907             //          ) => any
73908             //      ): any;
73909             //  }
73910             //
73911             if (isTypeAny(type)) {
73912                 return undefined;
73913             }
73914             var typeAsPromise = type;
73915             if (typeAsPromise.promisedTypeOfPromise) {
73916                 return typeAsPromise.promisedTypeOfPromise;
73917             }
73918             if (isReferenceToType(type, getGlobalPromiseType(/*reportErrors*/ false))) {
73919                 return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0];
73920             }
73921             var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217
73922             if (isTypeAny(thenFunction)) {
73923                 return undefined;
73924             }
73925             var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray;
73926             if (thenSignatures.length === 0) {
73927                 if (errorNode) {
73928                     error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method);
73929                 }
73930                 return undefined;
73931             }
73932             var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */);
73933             if (isTypeAny(onfulfilledParameterType)) {
73934                 return undefined;
73935             }
73936             var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
73937             if (onfulfilledParameterSignatures.length === 0) {
73938                 if (errorNode) {
73939                     error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
73940                 }
73941                 return undefined;
73942             }
73943             return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */);
73944         }
73945         /**
73946          * Gets the "awaited type" of a type.
73947          * @param type The type to await.
73948          * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
73949          * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
73950          * The runtime behavior of the `await` keyword.
73951          */
73952         function checkAwaitedType(type, errorNode, diagnosticMessage, arg0) {
73953             var awaitedType = getAwaitedType(type, errorNode, diagnosticMessage, arg0);
73954             return awaitedType || errorType;
73955         }
73956         /**
73957          * Determines whether a type has a callable `then` member.
73958          */
73959         function isThenableType(type) {
73960             var thenFunction = getTypeOfPropertyOfType(type, "then");
73961             return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */), 0 /* Call */).length > 0;
73962         }
73963         /**
73964          * Gets the "awaited type" of a type.
73965          *
73966          * The "awaited type" of an expression is its "promised type" if the expression is a
73967          * Promise-like type; otherwise, it is the type of the expression. If the "promised
73968          * type" is itself a Promise-like, the "promised type" is recursively unwrapped until a
73969          * non-promise type is found.
73970          *
73971          * This is used to reflect the runtime behavior of the `await` keyword.
73972          */
73973         function getAwaitedType(type, errorNode, diagnosticMessage, arg0) {
73974             if (isTypeAny(type)) {
73975                 return type;
73976             }
73977             var typeAsAwaitable = type;
73978             if (typeAsAwaitable.awaitedTypeOfType) {
73979                 return typeAsAwaitable.awaitedTypeOfType;
73980             }
73981             // For a union, get a union of the awaited types of each constituent.
73982             //
73983             return typeAsAwaitable.awaitedTypeOfType =
73984                 mapType(type, errorNode ? function (constituentType) { return getAwaitedTypeWorker(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeWorker);
73985         }
73986         function getAwaitedTypeWorker(type, errorNode, diagnosticMessage, arg0) {
73987             var typeAsAwaitable = type;
73988             if (typeAsAwaitable.awaitedTypeOfType) {
73989                 return typeAsAwaitable.awaitedTypeOfType;
73990             }
73991             var promisedType = getPromisedTypeOfPromise(type);
73992             if (promisedType) {
73993                 if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) {
73994                     // Verify that we don't have a bad actor in the form of a promise whose
73995                     // promised type is the same as the promise type, or a mutually recursive
73996                     // promise. If so, we return undefined as we cannot guess the shape. If this
73997                     // were the actual case in the JavaScript, this Promise would never resolve.
73998                     //
73999                     // An example of a bad actor with a singly-recursive promise type might
74000                     // be:
74001                     //
74002                     //  interface BadPromise {
74003                     //      then(
74004                     //          onfulfilled: (value: BadPromise) => any,
74005                     //          onrejected: (error: any) => any): BadPromise;
74006                     //  }
74007                     //
74008                     // The above interface will pass the PromiseLike check, and return a
74009                     // promised type of `BadPromise`. Since this is a self reference, we
74010                     // don't want to keep recursing ad infinitum.
74011                     //
74012                     // An example of a bad actor in the form of a mutually-recursive
74013                     // promise type might be:
74014                     //
74015                     //  interface BadPromiseA {
74016                     //      then(
74017                     //          onfulfilled: (value: BadPromiseB) => any,
74018                     //          onrejected: (error: any) => any): BadPromiseB;
74019                     //  }
74020                     //
74021                     //  interface BadPromiseB {
74022                     //      then(
74023                     //          onfulfilled: (value: BadPromiseA) => any,
74024                     //          onrejected: (error: any) => any): BadPromiseA;
74025                     //  }
74026                     //
74027                     if (errorNode) {
74028                         error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
74029                     }
74030                     return undefined;
74031                 }
74032                 // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
74033                 // See the comments above for more information.
74034                 awaitedTypeStack.push(type.id);
74035                 var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
74036                 awaitedTypeStack.pop();
74037                 if (!awaitedType) {
74038                     return undefined;
74039                 }
74040                 return typeAsAwaitable.awaitedTypeOfType = awaitedType;
74041             }
74042             // The type was not a promise, so it could not be unwrapped any further.
74043             // As long as the type does not have a callable "then" property, it is
74044             // safe to return the type; otherwise, an error is reported and we return
74045             // undefined.
74046             //
74047             // An example of a non-promise "thenable" might be:
74048             //
74049             //  await { then(): void {} }
74050             //
74051             // The "thenable" does not match the minimal definition for a promise. When
74052             // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
74053             // will never settle. We treat this as an error to help flag an early indicator
74054             // of a runtime problem. If the user wants to return this value from an async
74055             // function, they would need to wrap it in some other value. If they want it to
74056             // be treated as a promise, they can cast to <any>.
74057             if (isThenableType(type)) {
74058                 if (errorNode) {
74059                     if (!diagnosticMessage)
74060                         return ts.Debug.fail();
74061                     error(errorNode, diagnosticMessage, arg0);
74062                 }
74063                 return undefined;
74064             }
74065             return typeAsAwaitable.awaitedTypeOfType = type;
74066         }
74067         /**
74068          * Checks the return type of an async function to ensure it is a compatible
74069          * Promise implementation.
74070          *
74071          * This checks that an async function has a valid Promise-compatible return type.
74072          * An async function has a valid Promise-compatible return type if the resolved value
74073          * of the return type has a construct signature that takes in an `initializer` function
74074          * that in turn supplies a `resolve` function as one of its arguments and results in an
74075          * object with a callable `then` signature.
74076          *
74077          * @param node The signature to check
74078          */
74079         function checkAsyncFunctionReturnType(node, returnTypeNode) {
74080             // As part of our emit for an async function, we will need to emit the entity name of
74081             // the return type annotation as an expression. To meet the necessary runtime semantics
74082             // for __awaiter, we must also check that the type of the declaration (e.g. the static
74083             // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`.
74084             //
74085             // An example might be (from lib.es6.d.ts):
74086             //
74087             //  interface Promise<T> { ... }
74088             //  interface PromiseConstructor {
74089             //      new <T>(...): Promise<T>;
74090             //  }
74091             //  declare var Promise: PromiseConstructor;
74092             //
74093             // When an async function declares a return type annotation of `Promise<T>`, we
74094             // need to get the type of the `Promise` variable declaration above, which would
74095             // be `PromiseConstructor`.
74096             //
74097             // The same case applies to a class:
74098             //
74099             //  declare class Promise<T> {
74100             //      constructor(...);
74101             //      then<U>(...): Promise<U>;
74102             //  }
74103             //
74104             var returnType = getTypeFromTypeNode(returnTypeNode);
74105             if (languageVersion >= 2 /* ES2015 */) {
74106                 if (returnType === errorType) {
74107                     return;
74108                 }
74109                 var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
74110                 if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
74111                     // The promise type was not a valid type reference to the global promise type, so we
74112                     // report an error and return the unknown type.
74113                     error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, typeToString(getAwaitedType(returnType) || voidType));
74114                     return;
74115                 }
74116             }
74117             else {
74118                 // Always mark the type node as referenced if it points to a value
74119                 markTypeNodeAsReferenced(returnTypeNode);
74120                 if (returnType === errorType) {
74121                     return;
74122                 }
74123                 var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode);
74124                 if (promiseConstructorName === undefined) {
74125                     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));
74126                     return;
74127                 }
74128                 var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 111551 /* Value */, /*ignoreErrors*/ true);
74129                 var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
74130                 if (promiseConstructorType === errorType) {
74131                     if (promiseConstructorName.kind === 78 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
74132                         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);
74133                     }
74134                     else {
74135                         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));
74136                     }
74137                     return;
74138                 }
74139                 var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true);
74140                 if (globalPromiseConstructorLikeType === emptyObjectType) {
74141                     // If we couldn't resolve the global PromiseConstructorLike type we cannot verify
74142                     // compatibility with __awaiter.
74143                     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));
74144                     return;
74145                 }
74146                 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)) {
74147                     return;
74148                 }
74149                 // Verify there is no local declaration that could collide with the promise constructor.
74150                 var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName);
74151                 var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */);
74152                 if (collidingSymbol) {
74153                     error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName));
74154                     return;
74155                 }
74156             }
74157             checkAwaitedType(returnType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
74158         }
74159         /** Check a decorator */
74160         function checkDecorator(node) {
74161             var signature = getResolvedSignature(node);
74162             checkDeprecatedSignature(signature, node);
74163             var returnType = getReturnTypeOfSignature(signature);
74164             if (returnType.flags & 1 /* Any */) {
74165                 return;
74166             }
74167             var expectedReturnType;
74168             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
74169             var errorInfo;
74170             switch (node.parent.kind) {
74171                 case 252 /* ClassDeclaration */:
74172                     var classSymbol = getSymbolOfNode(node.parent);
74173                     var classConstructorType = getTypeOfSymbol(classSymbol);
74174                     expectedReturnType = getUnionType([classConstructorType, voidType]);
74175                     break;
74176                 case 160 /* Parameter */:
74177                     expectedReturnType = voidType;
74178                     errorInfo = ts.chainDiagnosticMessages(
74179                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
74180                     break;
74181                 case 163 /* PropertyDeclaration */:
74182                     expectedReturnType = voidType;
74183                     errorInfo = ts.chainDiagnosticMessages(
74184                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
74185                     break;
74186                 case 165 /* MethodDeclaration */:
74187                 case 167 /* GetAccessor */:
74188                 case 168 /* SetAccessor */:
74189                     var methodType = getTypeOfNode(node.parent);
74190                     var descriptorType = createTypedPropertyDescriptorType(methodType);
74191                     expectedReturnType = getUnionType([descriptorType, voidType]);
74192                     break;
74193                 default:
74194                     return ts.Debug.fail();
74195             }
74196             checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; });
74197         }
74198         /**
74199          * If a TypeNode can be resolved to a value symbol imported from an external module, it is
74200          * marked as referenced to prevent import elision.
74201          */
74202         function markTypeNodeAsReferenced(node) {
74203             markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node));
74204         }
74205         function markEntityNameOrEntityExpressionAsReference(typeName) {
74206             if (!typeName)
74207                 return;
74208             var rootName = ts.getFirstIdentifier(typeName);
74209             var meaning = (typeName.kind === 78 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
74210             var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true);
74211             if (rootSymbol
74212                 && rootSymbol.flags & 2097152 /* Alias */
74213                 && symbolIsValue(rootSymbol)
74214                 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))
74215                 && !getTypeOnlyAliasDeclaration(rootSymbol)) {
74216                 markAliasSymbolAsReferenced(rootSymbol);
74217             }
74218         }
74219         /**
74220          * This function marks the type used for metadata decorator as referenced if it is import
74221          * from external module.
74222          * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in
74223          * union and intersection type
74224          * @param node
74225          */
74226         function markDecoratorMedataDataTypeNodeAsReferenced(node) {
74227             var entityName = getEntityNameForDecoratorMetadata(node);
74228             if (entityName && ts.isEntityName(entityName)) {
74229                 markEntityNameOrEntityExpressionAsReference(entityName);
74230             }
74231         }
74232         function getEntityNameForDecoratorMetadata(node) {
74233             if (node) {
74234                 switch (node.kind) {
74235                     case 183 /* IntersectionType */:
74236                     case 182 /* UnionType */:
74237                         return getEntityNameForDecoratorMetadataFromTypeList(node.types);
74238                     case 184 /* ConditionalType */:
74239                         return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]);
74240                     case 186 /* ParenthesizedType */:
74241                     case 192 /* NamedTupleMember */:
74242                         return getEntityNameForDecoratorMetadata(node.type);
74243                     case 173 /* TypeReference */:
74244                         return node.typeName;
74245                 }
74246             }
74247         }
74248         function getEntityNameForDecoratorMetadataFromTypeList(types) {
74249             var commonEntityName;
74250             for (var _i = 0, types_23 = types; _i < types_23.length; _i++) {
74251                 var typeNode = types_23[_i];
74252                 while (typeNode.kind === 186 /* ParenthesizedType */ || typeNode.kind === 192 /* NamedTupleMember */) {
74253                     typeNode = typeNode.type; // Skip parens if need be
74254                 }
74255                 if (typeNode.kind === 141 /* NeverKeyword */) {
74256                     continue; // Always elide `never` from the union/intersection if possible
74257                 }
74258                 if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) {
74259                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
74260                 }
74261                 var individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
74262                 if (!individualEntityName) {
74263                     // Individual is something like string number
74264                     // So it would be serialized to either that type or object
74265                     // Safe to return here
74266                     return undefined;
74267                 }
74268                 if (commonEntityName) {
74269                     // Note this is in sync with the transformation that happens for type node.
74270                     // Keep this in sync with serializeUnionOrIntersectionType
74271                     // Verify if they refer to same entity and is identifier
74272                     // return undefined if they dont match because we would emit object
74273                     if (!ts.isIdentifier(commonEntityName) ||
74274                         !ts.isIdentifier(individualEntityName) ||
74275                         commonEntityName.escapedText !== individualEntityName.escapedText) {
74276                         return undefined;
74277                     }
74278                 }
74279                 else {
74280                     commonEntityName = individualEntityName;
74281                 }
74282             }
74283             return commonEntityName;
74284         }
74285         function getParameterTypeNodeForDecoratorCheck(node) {
74286             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
74287             return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode;
74288         }
74289         /** Check the decorators of a node */
74290         function checkDecorators(node) {
74291             if (!node.decorators) {
74292                 return;
74293             }
74294             // skip this check for nodes that cannot have decorators. These should have already had an error reported by
74295             // checkGrammarDecorators.
74296             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
74297                 return;
74298             }
74299             if (!compilerOptions.experimentalDecorators) {
74300                 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);
74301             }
74302             var firstDecorator = node.decorators[0];
74303             checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
74304             if (node.kind === 160 /* Parameter */) {
74305                 checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
74306             }
74307             if (compilerOptions.emitDecoratorMetadata) {
74308                 checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
74309                 // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.
74310                 switch (node.kind) {
74311                     case 252 /* ClassDeclaration */:
74312                         var constructor = ts.getFirstConstructorWithBody(node);
74313                         if (constructor) {
74314                             for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) {
74315                                 var parameter = _a[_i];
74316                                 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
74317                             }
74318                         }
74319                         break;
74320                     case 167 /* GetAccessor */:
74321                     case 168 /* SetAccessor */:
74322                         var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */;
74323                         var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
74324                         markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
74325                         break;
74326                     case 165 /* MethodDeclaration */:
74327                         for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) {
74328                             var parameter = _c[_b];
74329                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
74330                         }
74331                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node));
74332                         break;
74333                     case 163 /* PropertyDeclaration */:
74334                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node));
74335                         break;
74336                     case 160 /* Parameter */:
74337                         markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
74338                         var containingSignature = node.parent;
74339                         for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) {
74340                             var parameter = _e[_d];
74341                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
74342                         }
74343                         break;
74344                 }
74345             }
74346             ts.forEach(node.decorators, checkDecorator);
74347         }
74348         function checkFunctionDeclaration(node) {
74349             if (produceDiagnostics) {
74350                 checkFunctionOrMethodDeclaration(node);
74351                 checkGrammarForGenerator(node);
74352                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
74353                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
74354             }
74355         }
74356         function checkJSDocTypeAliasTag(node) {
74357             if (!node.typeExpression) {
74358                 // If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
74359                 error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
74360             }
74361             if (node.name) {
74362                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
74363             }
74364             checkSourceElement(node.typeExpression);
74365         }
74366         function checkJSDocTemplateTag(node) {
74367             checkSourceElement(node.constraint);
74368             for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
74369                 var tp = _a[_i];
74370                 checkSourceElement(tp);
74371             }
74372         }
74373         function checkJSDocTypeTag(node) {
74374             checkSourceElement(node.typeExpression);
74375         }
74376         function checkJSDocParameterTag(node) {
74377             checkSourceElement(node.typeExpression);
74378             if (!ts.getParameterSymbolFromJSDoc(node)) {
74379                 var decl = ts.getHostSignatureFromJSDoc(node);
74380                 // don't issue an error for invalid hosts -- just functions --
74381                 // and give a better error message when the host function mentions `arguments`
74382                 // but the tag doesn't have an array type
74383                 if (decl) {
74384                     var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node);
74385                     if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) {
74386                         return;
74387                     }
74388                     if (!containsArgumentsReference(decl)) {
74389                         if (ts.isQualifiedName(node.name)) {
74390                             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));
74391                         }
74392                         else {
74393                             error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name));
74394                         }
74395                     }
74396                     else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node &&
74397                         node.typeExpression && node.typeExpression.type &&
74398                         !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) {
74399                         error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, ts.idText(node.name.kind === 157 /* QualifiedName */ ? node.name.right : node.name));
74400                     }
74401                 }
74402             }
74403         }
74404         function checkJSDocPropertyTag(node) {
74405             checkSourceElement(node.typeExpression);
74406         }
74407         function checkJSDocFunctionType(node) {
74408             if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) {
74409                 reportImplicitAny(node, anyType);
74410             }
74411             checkSignatureDeclaration(node);
74412         }
74413         function checkJSDocImplementsTag(node) {
74414             var classLike = ts.getEffectiveJSDocHost(node);
74415             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
74416                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
74417             }
74418         }
74419         function checkJSDocAugmentsTag(node) {
74420             var classLike = ts.getEffectiveJSDocHost(node);
74421             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
74422                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
74423                 return;
74424             }
74425             var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag);
74426             ts.Debug.assert(augmentsTags.length > 0);
74427             if (augmentsTags.length > 1) {
74428                 error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
74429             }
74430             var name = getIdentifierFromEntityNameExpression(node.class.expression);
74431             var extend = ts.getClassExtendsHeritageElement(classLike);
74432             if (extend) {
74433                 var className = getIdentifierFromEntityNameExpression(extend.expression);
74434                 if (className && name.escapedText !== className.escapedText) {
74435                     error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className));
74436                 }
74437             }
74438         }
74439         function getIdentifierFromEntityNameExpression(node) {
74440             switch (node.kind) {
74441                 case 78 /* Identifier */:
74442                     return node;
74443                 case 201 /* PropertyAccessExpression */:
74444                     return node.name;
74445                 default:
74446                     return undefined;
74447             }
74448         }
74449         function checkFunctionOrMethodDeclaration(node) {
74450             checkDecorators(node);
74451             checkSignatureDeclaration(node);
74452             var functionFlags = ts.getFunctionFlags(node);
74453             // Do not use hasDynamicName here, because that returns false for well known symbols.
74454             // We want to perform checkComputedPropertyName for all computed properties, including
74455             // well known symbols.
74456             if (node.name && node.name.kind === 158 /* ComputedPropertyName */) {
74457                 // This check will account for methods in class/interface declarations,
74458                 // as well as accessors in classes/object literals
74459                 checkComputedPropertyName(node.name);
74460             }
74461             if (hasBindableName(node)) {
74462                 // first we want to check the local symbol that contain this declaration
74463                 // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol
74464                 // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode
74465                 var symbol = getSymbolOfNode(node);
74466                 var localSymbol = node.localSymbol || symbol;
74467                 // Since the javascript won't do semantic analysis like typescript,
74468                 // if the javascript file comes before the typescript file and both contain same name functions,
74469                 // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function.
74470                 var firstDeclaration = ts.find(localSymbol.declarations, 
74471                 // Get first non javascript function declaration
74472                 function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); });
74473                 // Only type check the symbol once
74474                 if (node === firstDeclaration) {
74475                     checkFunctionOrConstructorSymbol(localSymbol);
74476                 }
74477                 if (symbol.parent) {
74478                     // run check on export symbol to check that modifiers agree across all exported declarations
74479                     checkFunctionOrConstructorSymbol(symbol);
74480                 }
74481             }
74482             var body = node.kind === 164 /* MethodSignature */ ? undefined : node.body;
74483             checkSourceElement(body);
74484             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node));
74485             if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) {
74486                 // Report an implicit any error if there is no body, no explicit return type, and node is not a private method
74487                 // in an ambient context
74488                 if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
74489                     reportImplicitAny(node, anyType);
74490                 }
74491                 if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) {
74492                     // A generator with a body and no type annotation can still cause errors. It can error if the
74493                     // yielded values have no common supertype, or it can give an implicit any error if it has no
74494                     // yielded values. The only way to trigger these errors is to try checking its return type.
74495                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
74496                 }
74497             }
74498             // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature
74499             if (ts.isInJSFile(node)) {
74500                 var typeTag = ts.getJSDocTypeTag(node);
74501                 if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
74502                     error(typeTag.typeExpression.type, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
74503                 }
74504             }
74505         }
74506         function registerForUnusedIdentifiersCheck(node) {
74507             // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
74508             if (produceDiagnostics) {
74509                 var sourceFile = ts.getSourceFileOfNode(node);
74510                 var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
74511                 if (!potentiallyUnusedIdentifiers) {
74512                     potentiallyUnusedIdentifiers = [];
74513                     allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
74514                 }
74515                 // TODO: GH#22580
74516                 // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
74517                 potentiallyUnusedIdentifiers.push(node);
74518             }
74519         }
74520         function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
74521             for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
74522                 var node = potentiallyUnusedIdentifiers_1[_i];
74523                 switch (node.kind) {
74524                     case 252 /* ClassDeclaration */:
74525                     case 221 /* ClassExpression */:
74526                         checkUnusedClassMembers(node, addDiagnostic);
74527                         checkUnusedTypeParameters(node, addDiagnostic);
74528                         break;
74529                     case 297 /* SourceFile */:
74530                     case 256 /* ModuleDeclaration */:
74531                     case 230 /* Block */:
74532                     case 258 /* CaseBlock */:
74533                     case 237 /* ForStatement */:
74534                     case 238 /* ForInStatement */:
74535                     case 239 /* ForOfStatement */:
74536                         checkUnusedLocalsAndParameters(node, addDiagnostic);
74537                         break;
74538                     case 166 /* Constructor */:
74539                     case 208 /* FunctionExpression */:
74540                     case 251 /* FunctionDeclaration */:
74541                     case 209 /* ArrowFunction */:
74542                     case 165 /* MethodDeclaration */:
74543                     case 167 /* GetAccessor */:
74544                     case 168 /* SetAccessor */:
74545                         if (node.body) { // Don't report unused parameters in overloads
74546                             checkUnusedLocalsAndParameters(node, addDiagnostic);
74547                         }
74548                         checkUnusedTypeParameters(node, addDiagnostic);
74549                         break;
74550                     case 164 /* MethodSignature */:
74551                     case 169 /* CallSignature */:
74552                     case 170 /* ConstructSignature */:
74553                     case 174 /* FunctionType */:
74554                     case 175 /* ConstructorType */:
74555                     case 254 /* TypeAliasDeclaration */:
74556                     case 253 /* InterfaceDeclaration */:
74557                         checkUnusedTypeParameters(node, addDiagnostic);
74558                         break;
74559                     case 185 /* InferType */:
74560                         checkUnusedInferTypeParameter(node, addDiagnostic);
74561                         break;
74562                     default:
74563                         ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
74564                 }
74565             }
74566         }
74567         function errorUnusedLocal(declaration, name, addDiagnostic) {
74568             var node = ts.getNameOfDeclaration(declaration) || declaration;
74569             var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
74570             addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name));
74571         }
74572         function isIdentifierThatStartsWithUnderscore(node) {
74573             return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
74574         }
74575         function checkUnusedClassMembers(node, addDiagnostic) {
74576             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
74577                 var member = _a[_i];
74578                 switch (member.kind) {
74579                     case 165 /* MethodDeclaration */:
74580                     case 163 /* PropertyDeclaration */:
74581                     case 167 /* GetAccessor */:
74582                     case 168 /* SetAccessor */:
74583                         if (member.kind === 168 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
74584                             // Already would have reported an error on the getter.
74585                             break;
74586                         }
74587                         var symbol = getSymbolOfNode(member);
74588                         if (!symbol.isReferenced
74589                             && (ts.hasEffectiveModifier(member, 8 /* Private */) || ts.isNamedDeclaration(member) && ts.isPrivateIdentifier(member.name))
74590                             && !(member.flags & 8388608 /* Ambient */)) {
74591                             addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
74592                         }
74593                         break;
74594                     case 166 /* Constructor */:
74595                         for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
74596                             var parameter = _c[_b];
74597                             if (!parameter.symbol.isReferenced && ts.hasSyntacticModifier(parameter, 8 /* Private */)) {
74598                                 addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
74599                             }
74600                         }
74601                         break;
74602                     case 171 /* IndexSignature */:
74603                     case 229 /* SemicolonClassElement */:
74604                         // Can't be private
74605                         break;
74606                     default:
74607                         ts.Debug.fail();
74608                 }
74609             }
74610         }
74611         function checkUnusedInferTypeParameter(node, addDiagnostic) {
74612             var typeParameter = node.typeParameter;
74613             if (isTypeParameterUnused(typeParameter)) {
74614                 addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
74615             }
74616         }
74617         function checkUnusedTypeParameters(node, addDiagnostic) {
74618             // Only report errors on the last declaration for the type parameter container;
74619             // this ensures that all uses have been accounted for.
74620             if (ts.last(getSymbolOfNode(node).declarations) !== node)
74621                 return;
74622             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
74623             var seenParentsWithEveryUnused = new ts.Set();
74624             for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
74625                 var typeParameter = typeParameters_3[_i];
74626                 if (!isTypeParameterUnused(typeParameter))
74627                     continue;
74628                 var name = ts.idText(typeParameter.name);
74629                 var parent = typeParameter.parent;
74630                 if (parent.kind !== 185 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
74631                     if (ts.tryAddToSet(seenParentsWithEveryUnused, parent)) {
74632                         var sourceFile = ts.getSourceFileOfNode(parent);
74633                         var range = ts.isJSDocTemplateTag(parent)
74634                             // Whole @template tag
74635                             ? ts.rangeOfNode(parent)
74636                             // Include the `<>` in the error message
74637                             : ts.rangeOfTypeParameters(sourceFile, parent.typeParameters);
74638                         var only = parent.typeParameters.length === 1;
74639                         var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
74640                         var arg0 = only ? name : undefined;
74641                         addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, message, arg0));
74642                     }
74643                 }
74644                 else {
74645                     addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
74646                 }
74647             }
74648         }
74649         function isTypeParameterUnused(typeParameter) {
74650             return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
74651         }
74652         function addToGroup(map, key, value, getKey) {
74653             var keyString = String(getKey(key));
74654             var group = map.get(keyString);
74655             if (group) {
74656                 group[1].push(value);
74657             }
74658             else {
74659                 map.set(keyString, [key, [value]]);
74660             }
74661         }
74662         function tryGetRootParameterDeclaration(node) {
74663             return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
74664         }
74665         function isValidUnusedLocalDeclaration(declaration) {
74666             if (ts.isBindingElement(declaration)) {
74667                 if (ts.isObjectBindingPattern(declaration.parent)) {
74668                     /**
74669                      * ignore starts with underscore names _
74670                      * const { a: _a } = { a: 1 }
74671                      */
74672                     return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name));
74673                 }
74674                 return isIdentifierThatStartsWithUnderscore(declaration.name);
74675             }
74676             return ts.isAmbientModule(declaration) ||
74677                 (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name);
74678         }
74679         function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
74680             // 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.
74681             var unusedImports = new ts.Map();
74682             var unusedDestructures = new ts.Map();
74683             var unusedVariables = new ts.Map();
74684             nodeWithLocals.locals.forEach(function (local) {
74685                 // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
74686                 // If it's a type parameter merged with a parameter, check if the parameter-side is used.
74687                 if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
74688                     return;
74689                 }
74690                 for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
74691                     var declaration = _a[_i];
74692                     if (isValidUnusedLocalDeclaration(declaration)) {
74693                         continue;
74694                     }
74695                     if (isImportedDeclaration(declaration)) {
74696                         addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
74697                     }
74698                     else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
74699                         // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
74700                         var lastElement = ts.last(declaration.parent.elements);
74701                         if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
74702                             addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
74703                         }
74704                     }
74705                     else if (ts.isVariableDeclaration(declaration)) {
74706                         addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
74707                     }
74708                     else {
74709                         var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
74710                         var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration);
74711                         if (parameter && name) {
74712                             if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
74713                                 if (ts.isBindingElement(declaration) && ts.isArrayBindingPattern(declaration.parent)) {
74714                                     addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
74715                                 }
74716                                 else {
74717                                     addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
74718                                 }
74719                             }
74720                         }
74721                         else {
74722                             errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
74723                         }
74724                     }
74725                 }
74726             });
74727             unusedImports.forEach(function (_a) {
74728                 var importClause = _a[0], unuseds = _a[1];
74729                 var importDecl = importClause.parent;
74730                 var nDeclarations = (importClause.name ? 1 : 0) +
74731                     (importClause.namedBindings ?
74732                         (importClause.namedBindings.kind === 263 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length)
74733                         : 0);
74734                 if (nDeclarations === unuseds.length) {
74735                     addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1
74736                         ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))
74737                         : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
74738                 }
74739                 else {
74740                     for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
74741                         var unused = unuseds_1[_i];
74742                         errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
74743                     }
74744                 }
74745             });
74746             unusedDestructures.forEach(function (_a) {
74747                 var bindingPattern = _a[0], bindingElements = _a[1];
74748                 var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
74749                 if (bindingPattern.elements.length === bindingElements.length) {
74750                     if (bindingElements.length === 1 && bindingPattern.parent.kind === 249 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 250 /* VariableDeclarationList */) {
74751                         addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
74752                     }
74753                     else {
74754                         addDiagnostic(bindingPattern, kind, bindingElements.length === 1
74755                             ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name))
74756                             : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
74757                     }
74758                 }
74759                 else {
74760                     for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
74761                         var e = bindingElements_1[_i];
74762                         addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
74763                     }
74764                 }
74765             });
74766             unusedVariables.forEach(function (_a) {
74767                 var declarationList = _a[0], declarations = _a[1];
74768                 if (declarationList.declarations.length === declarations.length) {
74769                     addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1
74770                         ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name))
74771                         : ts.createDiagnosticForNode(declarationList.parent.kind === 232 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused));
74772                 }
74773                 else {
74774                     for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
74775                         var decl = declarations_5[_i];
74776                         addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
74777                     }
74778                 }
74779             });
74780         }
74781         function bindingNameText(name) {
74782             switch (name.kind) {
74783                 case 78 /* Identifier */:
74784                     return ts.idText(name);
74785                 case 197 /* ArrayBindingPattern */:
74786                 case 196 /* ObjectBindingPattern */:
74787                     return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name);
74788                 default:
74789                     return ts.Debug.assertNever(name);
74790             }
74791         }
74792         function isImportedDeclaration(node) {
74793             return node.kind === 262 /* ImportClause */ || node.kind === 265 /* ImportSpecifier */ || node.kind === 263 /* NamespaceImport */;
74794         }
74795         function importClauseFromImported(decl) {
74796             return decl.kind === 262 /* ImportClause */ ? decl : decl.kind === 263 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
74797         }
74798         function checkBlock(node) {
74799             // Grammar checking for SyntaxKind.Block
74800             if (node.kind === 230 /* Block */) {
74801                 checkGrammarStatementInAmbientContext(node);
74802             }
74803             if (ts.isFunctionOrModuleBlock(node)) {
74804                 var saveFlowAnalysisDisabled = flowAnalysisDisabled;
74805                 ts.forEach(node.statements, checkSourceElement);
74806                 flowAnalysisDisabled = saveFlowAnalysisDisabled;
74807             }
74808             else {
74809                 ts.forEach(node.statements, checkSourceElement);
74810             }
74811             if (node.locals) {
74812                 registerForUnusedIdentifiersCheck(node);
74813             }
74814         }
74815         function checkCollisionWithArgumentsInGeneratedCode(node) {
74816             // no rest parameters \ declaration context \ overload - no codegen impact
74817             if (languageVersion >= 2 /* ES2015 */ || !ts.hasRestParameter(node) || node.flags & 8388608 /* Ambient */ || ts.nodeIsMissing(node.body)) {
74818                 return;
74819             }
74820             ts.forEach(node.parameters, function (p) {
74821                 if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
74822                     errorSkippedOn("noEmit", p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
74823                 }
74824             });
74825         }
74826         function needCollisionCheckForIdentifier(node, identifier, name) {
74827             if (!(identifier && identifier.escapedText === name)) {
74828                 return false;
74829             }
74830             if (node.kind === 163 /* PropertyDeclaration */ ||
74831                 node.kind === 162 /* PropertySignature */ ||
74832                 node.kind === 165 /* MethodDeclaration */ ||
74833                 node.kind === 164 /* MethodSignature */ ||
74834                 node.kind === 167 /* GetAccessor */ ||
74835                 node.kind === 168 /* SetAccessor */) {
74836                 // it is ok to have member named '_super' or '_this' - member access is always qualified
74837                 return false;
74838             }
74839             if (node.flags & 8388608 /* Ambient */) {
74840                 // ambient context - no codegen impact
74841                 return false;
74842             }
74843             var root = ts.getRootDeclaration(node);
74844             if (root.kind === 160 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) {
74845                 // just an overload - no codegen impact
74846                 return false;
74847             }
74848             return true;
74849         }
74850         // this function will run after checking the source file so 'CaptureThis' is correct for all nodes
74851         function checkIfThisIsCapturedInEnclosingScope(node) {
74852             ts.findAncestor(node, function (current) {
74853                 if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
74854                     var isDeclaration_1 = node.kind !== 78 /* Identifier */;
74855                     if (isDeclaration_1) {
74856                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
74857                     }
74858                     else {
74859                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
74860                     }
74861                     return true;
74862                 }
74863                 return false;
74864             });
74865         }
74866         function checkIfNewTargetIsCapturedInEnclosingScope(node) {
74867             ts.findAncestor(node, function (current) {
74868                 if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
74869                     var isDeclaration_2 = node.kind !== 78 /* Identifier */;
74870                     if (isDeclaration_2) {
74871                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
74872                     }
74873                     else {
74874                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
74875                     }
74876                     return true;
74877                 }
74878                 return false;
74879             });
74880         }
74881         function checkWeakMapCollision(node) {
74882             var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node);
74883             if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) {
74884                 errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap");
74885             }
74886         }
74887         function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
74888             // No need to check for require or exports for ES6 modules and later
74889             if (moduleKind >= ts.ModuleKind.ES2015) {
74890                 return;
74891             }
74892             if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
74893                 return;
74894             }
74895             // Uninstantiated modules shouldnt do this check
74896             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
74897                 return;
74898             }
74899             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
74900             var parent = getDeclarationContainer(node);
74901             if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
74902                 // If the declaration happens to be in external module, report error that require and exports are reserved keywords
74903                 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));
74904             }
74905         }
74906         function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
74907             if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) {
74908                 return;
74909             }
74910             // Uninstantiated modules shouldnt do this check
74911             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
74912                 return;
74913             }
74914             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
74915             var parent = getDeclarationContainer(node);
74916             if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) {
74917                 // If the declaration happens to be in external module, report error that Promise is a reserved identifier.
74918                 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));
74919             }
74920         }
74921         function checkVarDeclaredNamesNotShadowed(node) {
74922             // - ScriptBody : StatementList
74923             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
74924             // also occurs in the VarDeclaredNames of StatementList.
74925             // - Block : { StatementList }
74926             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
74927             // also occurs in the VarDeclaredNames of StatementList.
74928             // Variable declarations are hoisted to the top of their function scope. They can shadow
74929             // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition
74930             // by the binder as the declaration scope is different.
74931             // A non-initialized declaration is a no-op as the block declaration will resolve before the var
74932             // declaration. the problem is if the declaration has an initializer. this will act as a write to the
74933             // block declared value. this is fine for let, but not const.
74934             // Only consider declarations with initializers, uninitialized const declarations will not
74935             // step on a let/const variable.
74936             // Do not consider const and const declarations, as duplicate block-scoped declarations
74937             // are handled by the binder.
74938             // We are only looking for const declarations that step on let\const declarations from a
74939             // different scope. e.g.:
74940             //      {
74941             //          const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
74942             //          const x = 0; // symbol for this declaration will be 'symbol'
74943             //      }
74944             // skip block-scoped variables and parameters
74945             if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
74946                 return;
74947             }
74948             // skip variable declarations that don't have initializers
74949             // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern
74950             // so we'll always treat binding elements as initialized
74951             if (node.kind === 249 /* VariableDeclaration */ && !node.initializer) {
74952                 return;
74953             }
74954             var symbol = getSymbolOfNode(node);
74955             if (symbol.flags & 1 /* FunctionScopedVariable */) {
74956                 if (!ts.isIdentifier(node.name))
74957                     return ts.Debug.fail();
74958                 var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
74959                 if (localDeclarationSymbol &&
74960                     localDeclarationSymbol !== symbol &&
74961                     localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
74962                     if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) {
74963                         var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 250 /* VariableDeclarationList */);
74964                         var container = varDeclList.parent.kind === 232 /* VariableStatement */ && varDeclList.parent.parent
74965                             ? varDeclList.parent.parent
74966                             : undefined;
74967                         // names of block-scoped and function scoped variables can collide only
74968                         // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting)
74969                         var namesShareScope = container &&
74970                             (container.kind === 230 /* Block */ && ts.isFunctionLike(container.parent) ||
74971                                 container.kind === 257 /* ModuleBlock */ ||
74972                                 container.kind === 256 /* ModuleDeclaration */ ||
74973                                 container.kind === 297 /* SourceFile */);
74974                         // here we know that function scoped variable is shadowed by block scoped one
74975                         // if they are defined in the same scope - binder has already reported redeclaration error
74976                         // otherwise if variable has an initializer - show error that initialization will fail
74977                         // since LHS will be block scoped name instead of function scoped
74978                         if (!namesShareScope) {
74979                             var name = symbolToString(localDeclarationSymbol);
74980                             error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
74981                         }
74982                     }
74983                 }
74984             }
74985         }
74986         function convertAutoToAny(type) {
74987             return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
74988         }
74989         // Check variable, parameter, or property declaration
74990         function checkVariableLikeDeclaration(node) {
74991             var _a;
74992             checkDecorators(node);
74993             if (!ts.isBindingElement(node)) {
74994                 checkSourceElement(node.type);
74995             }
74996             // JSDoc `function(string, string): string` syntax results in parameters with no name
74997             if (!node.name) {
74998                 return;
74999             }
75000             // For a computed property, just check the initializer and exit
75001             // Do not use hasDynamicName here, because that returns false for well known symbols.
75002             // We want to perform checkComputedPropertyName for all computed properties, including
75003             // well known symbols.
75004             if (node.name.kind === 158 /* ComputedPropertyName */) {
75005                 checkComputedPropertyName(node.name);
75006                 if (node.initializer) {
75007                     checkExpressionCached(node.initializer);
75008                 }
75009             }
75010             if (node.kind === 198 /* BindingElement */) {
75011                 if (node.parent.kind === 196 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) {
75012                     checkExternalEmitHelpers(node, 4 /* Rest */);
75013                 }
75014                 // check computed properties inside property names of binding elements
75015                 if (node.propertyName && node.propertyName.kind === 158 /* ComputedPropertyName */) {
75016                     checkComputedPropertyName(node.propertyName);
75017                 }
75018                 // check private/protected variable access
75019                 var parent = node.parent.parent;
75020                 var parentType = getTypeForBindingElementParent(parent);
75021                 var name = node.propertyName || node.name;
75022                 if (parentType && !ts.isBindingPattern(name)) {
75023                     var exprType = getLiteralTypeFromPropertyName(name);
75024                     if (isTypeUsableAsPropertyName(exprType)) {
75025                         var nameText = getPropertyNameFromType(exprType);
75026                         var property = getPropertyOfType(parentType, nameText);
75027                         if (property) {
75028                             markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
75029                             checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 105 /* SuperKeyword */, parentType, property);
75030                         }
75031                     }
75032                 }
75033             }
75034             // For a binding pattern, check contained binding elements
75035             if (ts.isBindingPattern(node.name)) {
75036                 if (node.name.kind === 197 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
75037                     checkExternalEmitHelpers(node, 512 /* Read */);
75038                 }
75039                 ts.forEach(node.name.elements, checkSourceElement);
75040             }
75041             // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body
75042             if (node.initializer && ts.isParameterDeclaration(node) && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
75043                 error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
75044                 return;
75045             }
75046             // For a binding pattern, validate the initializer and exit
75047             if (ts.isBindingPattern(node.name)) {
75048                 var needCheckInitializer = node.initializer && node.parent.parent.kind !== 238 /* ForInStatement */;
75049                 var needCheckWidenedType = node.name.elements.length === 0;
75050                 if (needCheckInitializer || needCheckWidenedType) {
75051                     // Don't validate for-in initializer as it is already an error
75052                     var widenedType = getWidenedTypeForVariableLikeDeclaration(node);
75053                     if (needCheckInitializer) {
75054                         var initializerType = checkExpressionCached(node.initializer);
75055                         if (strictNullChecks && needCheckWidenedType) {
75056                             checkNonNullNonVoidType(initializerType, node);
75057                         }
75058                         else {
75059                             checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
75060                         }
75061                     }
75062                     // check the binding pattern with empty elements
75063                     if (needCheckWidenedType) {
75064                         if (ts.isArrayBindingPattern(node.name)) {
75065                             checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node);
75066                         }
75067                         else if (strictNullChecks) {
75068                             checkNonNullNonVoidType(widenedType, node);
75069                         }
75070                     }
75071                 }
75072                 return;
75073             }
75074             // For a commonjs `const x = require`, validate the alias and exit
75075             var symbol = getSymbolOfNode(node);
75076             if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true)) {
75077                 checkAliasSymbol(node);
75078                 return;
75079             }
75080             var type = convertAutoToAny(getTypeOfSymbol(symbol));
75081             if (node === symbol.valueDeclaration) {
75082                 // Node is the primary declaration of the symbol, just validate the initializer
75083                 // Don't validate for-in initializer as it is already an error
75084                 var initializer = ts.getEffectiveInitializer(node);
75085                 if (initializer) {
75086                     var isJSObjectLiteralInitializer = ts.isInJSFile(node) &&
75087                         ts.isObjectLiteralExpression(initializer) &&
75088                         (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) &&
75089                         !!((_a = symbol.exports) === null || _a === void 0 ? void 0 : _a.size);
75090                     if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 238 /* ForInStatement */) {
75091                         checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined);
75092                     }
75093                 }
75094                 if (symbol.declarations.length > 1) {
75095                     if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) {
75096                         error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
75097                     }
75098                 }
75099             }
75100             else {
75101                 // Node is a secondary declaration, check that type is identical to primary declaration and check that
75102                 // initializer is consistent with type associated with the node
75103                 var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
75104                 if (type !== errorType && declarationType !== errorType &&
75105                     !isTypeIdenticalTo(type, declarationType) &&
75106                     !(symbol.flags & 67108864 /* Assignment */)) {
75107                     errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
75108                 }
75109                 if (node.initializer) {
75110                     checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined);
75111                 }
75112                 if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
75113                     error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
75114                 }
75115             }
75116             if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */) {
75117                 // We know we don't have a binding pattern or computed name here
75118                 checkExportsOnMergedDeclarations(node);
75119                 if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) {
75120                     checkVarDeclaredNamesNotShadowed(node);
75121                 }
75122                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
75123                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
75124                 if (languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) {
75125                     potentialWeakMapCollisions.push(node);
75126                 }
75127             }
75128         }
75129         function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) {
75130             var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration);
75131             var message = nextDeclaration.kind === 163 /* PropertyDeclaration */ || nextDeclaration.kind === 162 /* PropertySignature */
75132                 ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2
75133                 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
75134             var declName = ts.declarationNameToString(nextDeclarationName);
75135             var err = error(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType));
75136             if (firstDeclaration) {
75137                 ts.addRelatedInfo(err, ts.createDiagnosticForNode(firstDeclaration, ts.Diagnostics._0_was_also_declared_here, declName));
75138             }
75139         }
75140         function areDeclarationFlagsIdentical(left, right) {
75141             if ((left.kind === 160 /* Parameter */ && right.kind === 249 /* VariableDeclaration */) ||
75142                 (left.kind === 249 /* VariableDeclaration */ && right.kind === 160 /* Parameter */)) {
75143                 // Differences in optionality between parameters and variables are allowed.
75144                 return true;
75145             }
75146             if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) {
75147                 return false;
75148             }
75149             var interestingFlags = 8 /* Private */ |
75150                 16 /* Protected */ |
75151                 256 /* Async */ |
75152                 128 /* Abstract */ |
75153                 64 /* Readonly */ |
75154                 32 /* Static */;
75155             return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags);
75156         }
75157         function checkVariableDeclaration(node) {
75158             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end });
75159             checkGrammarVariableDeclaration(node);
75160             checkVariableLikeDeclaration(node);
75161             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
75162         }
75163         function checkBindingElement(node) {
75164             checkGrammarBindingElement(node);
75165             return checkVariableLikeDeclaration(node);
75166         }
75167         function checkVariableStatement(node) {
75168             // Grammar checking
75169             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList))
75170                 checkGrammarForDisallowedLetOrConstStatement(node);
75171             ts.forEach(node.declarationList.declarations, checkSourceElement);
75172         }
75173         function checkExpressionStatement(node) {
75174             // Grammar checking
75175             checkGrammarStatementInAmbientContext(node);
75176             checkExpression(node.expression);
75177         }
75178         function checkIfStatement(node) {
75179             // Grammar checking
75180             checkGrammarStatementInAmbientContext(node);
75181             var type = checkTruthinessExpression(node.expression);
75182             checkTestingKnownTruthyCallableType(node.expression, type, node.thenStatement);
75183             checkSourceElement(node.thenStatement);
75184             if (node.thenStatement.kind === 231 /* EmptyStatement */) {
75185                 error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
75186             }
75187             checkSourceElement(node.elseStatement);
75188         }
75189         function checkTestingKnownTruthyCallableType(condExpr, type, body) {
75190             if (!strictNullChecks) {
75191                 return;
75192             }
75193             var location = ts.isBinaryExpression(condExpr) ? condExpr.right : condExpr;
75194             var testedNode = ts.isIdentifier(location) ? location
75195                 : ts.isPropertyAccessExpression(location) ? location.name
75196                     : ts.isBinaryExpression(location) && ts.isIdentifier(location.right) ? location.right
75197                         : undefined;
75198             var isPropertyExpressionCast = ts.isPropertyAccessExpression(location)
75199                 && ts.isAssertionExpression(ts.skipParentheses(location.expression));
75200             if (!testedNode || isPropertyExpressionCast) {
75201                 return;
75202             }
75203             var possiblyFalsy = getFalsyFlags(type);
75204             if (possiblyFalsy) {
75205                 return;
75206             }
75207             // While it technically should be invalid for any known-truthy value
75208             // to be tested, we de-scope to functions unrefenced in the block as a
75209             // heuristic to identify the most common bugs. There are too many
75210             // false positives for values sourced from type definitions without
75211             // strictNullChecks otherwise.
75212             var callSignatures = getSignaturesOfType(type, 0 /* Call */);
75213             if (callSignatures.length === 0) {
75214                 return;
75215             }
75216             var testedSymbol = getSymbolAtLocation(testedNode);
75217             if (!testedSymbol) {
75218                 return;
75219             }
75220             var isUsed = ts.isBinaryExpression(condExpr.parent) && isFunctionUsedInBinaryExpressionChain(condExpr.parent, testedSymbol)
75221                 || body && isFunctionUsedInConditionBody(condExpr, body, testedNode, testedSymbol);
75222             if (!isUsed) {
75223                 error(location, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead);
75224             }
75225         }
75226         function isFunctionUsedInConditionBody(expr, body, testedNode, testedSymbol) {
75227             return !!ts.forEachChild(body, function check(childNode) {
75228                 if (ts.isIdentifier(childNode)) {
75229                     var childSymbol = getSymbolAtLocation(childNode);
75230                     if (childSymbol && childSymbol === testedSymbol) {
75231                         // If the test was a simple identifier, the above check is sufficient
75232                         if (ts.isIdentifier(expr)) {
75233                             return true;
75234                         }
75235                         // Otherwise we need to ensure the symbol is called on the same target
75236                         var testedExpression = testedNode.parent;
75237                         var childExpression = childNode.parent;
75238                         while (testedExpression && childExpression) {
75239                             if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) ||
75240                                 testedExpression.kind === 107 /* ThisKeyword */ && childExpression.kind === 107 /* ThisKeyword */) {
75241                                 return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression);
75242                             }
75243                             else if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) {
75244                                 if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) {
75245                                     return false;
75246                                 }
75247                                 childExpression = childExpression.expression;
75248                                 testedExpression = testedExpression.expression;
75249                             }
75250                             else if (ts.isCallExpression(testedExpression) && ts.isCallExpression(childExpression)) {
75251                                 childExpression = childExpression.expression;
75252                                 testedExpression = testedExpression.expression;
75253                             }
75254                             else {
75255                                 return false;
75256                             }
75257                         }
75258                     }
75259                 }
75260                 return ts.forEachChild(childNode, check);
75261             });
75262         }
75263         function isFunctionUsedInBinaryExpressionChain(node, testedSymbol) {
75264             while (ts.isBinaryExpression(node) && node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
75265                 var isUsed = ts.forEachChild(node.right, function visit(child) {
75266                     if (ts.isIdentifier(child)) {
75267                         var symbol = getSymbolAtLocation(child);
75268                         if (symbol && symbol === testedSymbol) {
75269                             return true;
75270                         }
75271                     }
75272                     return ts.forEachChild(child, visit);
75273                 });
75274                 if (isUsed) {
75275                     return true;
75276                 }
75277                 node = node.parent;
75278             }
75279             return false;
75280         }
75281         function checkDoStatement(node) {
75282             // Grammar checking
75283             checkGrammarStatementInAmbientContext(node);
75284             checkSourceElement(node.statement);
75285             checkTruthinessExpression(node.expression);
75286         }
75287         function checkWhileStatement(node) {
75288             // Grammar checking
75289             checkGrammarStatementInAmbientContext(node);
75290             checkTruthinessExpression(node.expression);
75291             checkSourceElement(node.statement);
75292         }
75293         function checkTruthinessOfType(type, node) {
75294             if (type.flags & 16384 /* Void */) {
75295                 error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
75296             }
75297             return type;
75298         }
75299         function checkTruthinessExpression(node, checkMode) {
75300             return checkTruthinessOfType(checkExpression(node, checkMode), node);
75301         }
75302         function checkForStatement(node) {
75303             // Grammar checking
75304             if (!checkGrammarStatementInAmbientContext(node)) {
75305                 if (node.initializer && node.initializer.kind === 250 /* VariableDeclarationList */) {
75306                     checkGrammarVariableDeclarationList(node.initializer);
75307                 }
75308             }
75309             if (node.initializer) {
75310                 if (node.initializer.kind === 250 /* VariableDeclarationList */) {
75311                     ts.forEach(node.initializer.declarations, checkVariableDeclaration);
75312                 }
75313                 else {
75314                     checkExpression(node.initializer);
75315                 }
75316             }
75317             if (node.condition)
75318                 checkTruthinessExpression(node.condition);
75319             if (node.incrementor)
75320                 checkExpression(node.incrementor);
75321             checkSourceElement(node.statement);
75322             if (node.locals) {
75323                 registerForUnusedIdentifiersCheck(node);
75324             }
75325         }
75326         function checkForOfStatement(node) {
75327             checkGrammarForInOrForOfStatement(node);
75328             if (node.awaitModifier) {
75329                 var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
75330                 if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 99 /* ESNext */) {
75331                     // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
75332                     checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */);
75333                 }
75334             }
75335             else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) {
75336                 // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled
75337                 checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
75338             }
75339             // Check the LHS and RHS
75340             // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS
75341             // via checkRightHandSideOfForOf.
75342             // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference.
75343             // Then check that the RHS is assignable to it.
75344             if (node.initializer.kind === 250 /* VariableDeclarationList */) {
75345                 checkForInOrForOfVariableDeclaration(node);
75346             }
75347             else {
75348                 var varExpr = node.initializer;
75349                 var iteratedType = checkRightHandSideOfForOf(node);
75350                 // There may be a destructuring assignment on the left side
75351                 if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) {
75352                     // iteratedType may be undefined. In this case, we still want to check the structure of
75353                     // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like
75354                     // to short circuit the type relation checking as much as possible, so we pass the unknownType.
75355                     checkDestructuringAssignment(varExpr, iteratedType || errorType);
75356                 }
75357                 else {
75358                     var leftType = checkExpression(varExpr);
75359                     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);
75360                     // iteratedType will be undefined if the rightType was missing properties/signatures
75361                     // required to get its iteratedType (like [Symbol.iterator] or next). This may be
75362                     // because we accessed properties from anyType, or it may have led to an error inside
75363                     // getElementTypeOfIterable.
75364                     if (iteratedType) {
75365                         checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
75366                     }
75367                 }
75368             }
75369             checkSourceElement(node.statement);
75370             if (node.locals) {
75371                 registerForUnusedIdentifiersCheck(node);
75372             }
75373         }
75374         function checkForInStatement(node) {
75375             // Grammar checking
75376             checkGrammarForInOrForOfStatement(node);
75377             var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
75378             // TypeScript 1.0 spec (April 2014): 5.4
75379             // In a 'for-in' statement of the form
75380             // for (let VarDecl in Expr) Statement
75381             //   VarDecl must be a variable declaration without a type annotation that declares a variable of type Any,
75382             //   and Expr must be an expression of type Any, an object type, or a type parameter type.
75383             if (node.initializer.kind === 250 /* VariableDeclarationList */) {
75384                 var variable = node.initializer.declarations[0];
75385                 if (variable && ts.isBindingPattern(variable.name)) {
75386                     error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
75387                 }
75388                 checkForInOrForOfVariableDeclaration(node);
75389             }
75390             else {
75391                 // In a 'for-in' statement of the form
75392                 // for (Var in Expr) Statement
75393                 //   Var must be an expression classified as a reference of type Any or the String primitive type,
75394                 //   and Expr must be an expression of type Any, an object type, or a type parameter type.
75395                 var varExpr = node.initializer;
75396                 var leftType = checkExpression(varExpr);
75397                 if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) {
75398                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
75399                 }
75400                 else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
75401                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
75402                 }
75403                 else {
75404                     // run check only former check succeeded to avoid cascading errors
75405                     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);
75406                 }
75407             }
75408             // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
75409             // in this case error about missing name is already reported - do not report extra one
75410             if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
75411                 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));
75412             }
75413             checkSourceElement(node.statement);
75414             if (node.locals) {
75415                 registerForUnusedIdentifiersCheck(node);
75416             }
75417         }
75418         function checkForInOrForOfVariableDeclaration(iterationStatement) {
75419             var variableDeclarationList = iterationStatement.initializer;
75420             // checkGrammarForInOrForOfStatement will check that there is exactly one declaration.
75421             if (variableDeclarationList.declarations.length >= 1) {
75422                 var decl = variableDeclarationList.declarations[0];
75423                 checkVariableDeclaration(decl);
75424             }
75425         }
75426         function checkRightHandSideOfForOf(statement) {
75427             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
75428             return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression);
75429         }
75430         function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) {
75431             if (isTypeAny(inputType)) {
75432                 return inputType;
75433             }
75434             return getIteratedTypeOrElementType(use, inputType, sentType, errorNode, /*checkAssignability*/ true) || anyType;
75435         }
75436         /**
75437          * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment
75438          * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
75439          * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
75440          */
75441         function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) {
75442             var allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0;
75443             if (inputType === neverType) {
75444                 reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217
75445                 return undefined;
75446             }
75447             var uplevelIteration = languageVersion >= 2 /* ES2015 */;
75448             var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
75449             var possibleOutOfBounds = compilerOptions.noUncheckedIndexedAccess && !!(use & 128 /* PossiblyOutOfBounds */);
75450             // Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
75451             // or higher, when inside of an async generator or for-await-if, or when
75452             // downlevelIteration is requested.
75453             if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
75454                 // We only report errors for an invalid iterable type in ES2015 or higher.
75455                 var iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : undefined);
75456                 if (checkAssignability) {
75457                     if (iterationTypes) {
75458                         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 :
75459                             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 :
75460                                 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 :
75461                                     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 :
75462                                         undefined;
75463                         if (diagnostic) {
75464                             checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic);
75465                         }
75466                     }
75467                 }
75468                 if (iterationTypes || uplevelIteration) {
75469                     return possibleOutOfBounds ? includeUndefinedInIndexSignature(iterationTypes && iterationTypes.yieldType) : (iterationTypes && iterationTypes.yieldType);
75470                 }
75471             }
75472             var arrayType = inputType;
75473             var reportedError = false;
75474             var hasStringConstituent = false;
75475             // If strings are permitted, remove any string-like constituents from the array type.
75476             // This allows us to find other non-string element types from an array unioned with
75477             // a string.
75478             if (use & 4 /* AllowsStringInputFlag */) {
75479                 if (arrayType.flags & 1048576 /* Union */) {
75480                     // After we remove all types that are StringLike, we will know if there was a string constituent
75481                     // based on whether the result of filter is a new array.
75482                     var arrayTypes = inputType.types;
75483                     var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 402653316 /* StringLike */); });
75484                     if (filteredTypes !== arrayTypes) {
75485                         arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
75486                     }
75487                 }
75488                 else if (arrayType.flags & 402653316 /* StringLike */) {
75489                     arrayType = neverType;
75490                 }
75491                 hasStringConstituent = arrayType !== inputType;
75492                 if (hasStringConstituent) {
75493                     if (languageVersion < 1 /* ES5 */) {
75494                         if (errorNode) {
75495                             error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
75496                             reportedError = true;
75497                         }
75498                     }
75499                     // Now that we've removed all the StringLike types, if no constituents remain, then the entire
75500                     // arrayOrStringType was a string.
75501                     if (arrayType.flags & 131072 /* Never */) {
75502                         return possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType;
75503                     }
75504                 }
75505             }
75506             if (!isArrayLikeType(arrayType)) {
75507                 if (errorNode && !reportedError) {
75508                     // Which error we report depends on whether we allow strings or if there was a
75509                     // string constituent. For example, if the input type is number | string, we
75510                     // want to say that number is not an array type. But if the input was just
75511                     // number and string input is allowed, we want to say that number is not an
75512                     // array type or a string type.
75513                     var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined);
75514                     var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent
75515                         ? downlevelIteration
75516                             ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]
75517                             : yieldType
75518                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
75519                                 : [ts.Diagnostics.Type_0_is_not_an_array_type, true]
75520                         : downlevelIteration
75521                             ? [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]
75522                             : yieldType
75523                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
75524                                 : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1];
75525                     errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType));
75526                 }
75527                 return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : undefined;
75528             }
75529             var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */);
75530             if (hasStringConstituent && arrayElementType) {
75531                 // This is just an optimization for the case where arrayOrStringType is string | string[]
75532                 if (arrayElementType.flags & 402653316 /* StringLike */ && !compilerOptions.noUncheckedIndexedAccess) {
75533                     return stringType;
75534                 }
75535                 return getUnionType(possibleOutOfBounds ? [arrayElementType, stringType, undefinedType] : [arrayElementType, stringType], 2 /* Subtype */);
75536             }
75537             return (use & 128 /* PossiblyOutOfBounds */) ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType;
75538         }
75539         /**
75540          * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type.
75541          */
75542         function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) {
75543             if (isTypeAny(inputType)) {
75544                 return undefined;
75545             }
75546             var iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode);
75547             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)];
75548         }
75549         function createIterationTypes(yieldType, returnType, nextType) {
75550             // `yieldType` and `returnType` are defaulted to `neverType` they each will be combined
75551             // via `getUnionType` when merging iteration types. `nextType` is defined as `unknownType`
75552             // as it is combined via `getIntersectionType` when merging iteration types.
75553             if (yieldType === void 0) { yieldType = neverType; }
75554             if (returnType === void 0) { returnType = neverType; }
75555             if (nextType === void 0) { nextType = unknownType; }
75556             // Use the cache only for intrinsic types to keep it small as they are likely to be
75557             // more frequently created (i.e. `Iterator<number, void, unknown>`). Iteration types
75558             // are also cached on the type they are requested for, so we shouldn't need to maintain
75559             // the cache for less-frequently used types.
75560             if (yieldType.flags & 67359327 /* Intrinsic */ &&
75561                 returnType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */) &&
75562                 nextType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */)) {
75563                 var id = getTypeListId([yieldType, returnType, nextType]);
75564                 var iterationTypes = iterationTypesCache.get(id);
75565                 if (!iterationTypes) {
75566                     iterationTypes = { yieldType: yieldType, returnType: returnType, nextType: nextType };
75567                     iterationTypesCache.set(id, iterationTypes);
75568                 }
75569                 return iterationTypes;
75570             }
75571             return { yieldType: yieldType, returnType: returnType, nextType: nextType };
75572         }
75573         /**
75574          * Combines multiple `IterationTypes` records.
75575          *
75576          * If `array` is empty or all elements are missing or are references to `noIterationTypes`,
75577          * then `noIterationTypes` is returned. Otherwise, an `IterationTypes` record is returned
75578          * for the combined iteration types.
75579          */
75580         function combineIterationTypes(array) {
75581             var yieldTypes;
75582             var returnTypes;
75583             var nextTypes;
75584             for (var _i = 0, array_10 = array; _i < array_10.length; _i++) {
75585                 var iterationTypes = array_10[_i];
75586                 if (iterationTypes === undefined || iterationTypes === noIterationTypes) {
75587                     continue;
75588                 }
75589                 if (iterationTypes === anyIterationTypes) {
75590                     return anyIterationTypes;
75591                 }
75592                 yieldTypes = ts.append(yieldTypes, iterationTypes.yieldType);
75593                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
75594                 nextTypes = ts.append(nextTypes, iterationTypes.nextType);
75595             }
75596             if (yieldTypes || returnTypes || nextTypes) {
75597                 return createIterationTypes(yieldTypes && getUnionType(yieldTypes), returnTypes && getUnionType(returnTypes), nextTypes && getIntersectionType(nextTypes));
75598             }
75599             return noIterationTypes;
75600         }
75601         function getCachedIterationTypes(type, cacheKey) {
75602             return type[cacheKey];
75603         }
75604         function setCachedIterationTypes(type, cacheKey, cachedTypes) {
75605             return type[cacheKey] = cachedTypes;
75606         }
75607         /**
75608          * Gets the *yield*, *return*, and *next* types from an `Iterable`-like or `AsyncIterable`-like type.
75609          *
75610          * At every level that involves analyzing return types of signatures, we union the return types of all the signatures.
75611          *
75612          * Another thing to note is that at any step of this process, we could run into a dead end,
75613          * meaning either the property is missing, or we run into the anyType. If either of these things
75614          * happens, we return `undefined` to signal that we could not find the iteration type. If a property
75615          * is missing, and the previous step did not result in `any`, then we also give an error if the
75616          * caller requested it. Then the caller can decide what to do in the case where there is no iterated
75617          * type.
75618          *
75619          * For a **for-of** statement, `yield*` (in a normal generator), spread, array
75620          * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()`
75621          * method.
75622          *
75623          * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method.
75624          *
75625          * For a **for-await-of** statement or a `yield*` in an async generator we will look for
75626          * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
75627          */
75628         function getIterationTypesOfIterable(type, use, errorNode) {
75629             if (isTypeAny(type)) {
75630                 return anyIterationTypes;
75631             }
75632             if (!(type.flags & 1048576 /* Union */)) {
75633                 var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode);
75634                 if (iterationTypes_1 === noIterationTypes) {
75635                     if (errorNode) {
75636                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
75637                     }
75638                     return undefined;
75639                 }
75640                 return iterationTypes_1;
75641             }
75642             var cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable";
75643             var cachedTypes = getCachedIterationTypes(type, cacheKey);
75644             if (cachedTypes)
75645                 return cachedTypes === noIterationTypes ? undefined : cachedTypes;
75646             var allIterationTypes;
75647             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
75648                 var constituent = _a[_i];
75649                 var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode);
75650                 if (iterationTypes_2 === noIterationTypes) {
75651                     if (errorNode) {
75652                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
75653                     }
75654                     setCachedIterationTypes(type, cacheKey, noIterationTypes);
75655                     return undefined;
75656                 }
75657                 else {
75658                     allIterationTypes = ts.append(allIterationTypes, iterationTypes_2);
75659                 }
75660             }
75661             var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes;
75662             setCachedIterationTypes(type, cacheKey, iterationTypes);
75663             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
75664         }
75665         function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) {
75666             if (iterationTypes === noIterationTypes)
75667                 return noIterationTypes;
75668             if (iterationTypes === anyIterationTypes)
75669                 return anyIterationTypes;
75670             var yieldType = iterationTypes.yieldType, returnType = iterationTypes.returnType, nextType = iterationTypes.nextType;
75671             return createIterationTypes(getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, nextType);
75672         }
75673         /**
75674          * Gets the *yield*, *return*, and *next* types from a non-union type.
75675          *
75676          * If we are unable to find the *yield*, *return*, and *next* types, `noIterationTypes` is
75677          * returned to indicate to the caller that it should report an error. Otherwise, an
75678          * `IterationTypes` record is returned.
75679          *
75680          * NOTE: You probably don't want to call this directly and should be calling
75681          * `getIterationTypesOfIterable` instead.
75682          */
75683         function getIterationTypesOfIterableWorker(type, use, errorNode) {
75684             if (isTypeAny(type)) {
75685                 return anyIterationTypes;
75686             }
75687             if (use & 2 /* AllowsAsyncIterablesFlag */) {
75688                 var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) ||
75689                     getIterationTypesOfIterableFast(type, asyncIterationTypesResolver);
75690                 if (iterationTypes) {
75691                     return iterationTypes;
75692                 }
75693             }
75694             if (use & 1 /* AllowsSyncIterablesFlag */) {
75695                 var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) ||
75696                     getIterationTypesOfIterableFast(type, syncIterationTypesResolver);
75697                 if (iterationTypes) {
75698                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
75699                         // for a sync iterable in an async context, only use the cached types if they are valid.
75700                         if (iterationTypes !== noIterationTypes) {
75701                             return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode));
75702                         }
75703                     }
75704                     else {
75705                         return iterationTypes;
75706                     }
75707                 }
75708             }
75709             if (use & 2 /* AllowsAsyncIterablesFlag */) {
75710                 var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode);
75711                 if (iterationTypes !== noIterationTypes) {
75712                     return iterationTypes;
75713                 }
75714             }
75715             if (use & 1 /* AllowsSyncIterablesFlag */) {
75716                 var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode);
75717                 if (iterationTypes !== noIterationTypes) {
75718                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
75719                         return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes
75720                             ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode)
75721                             : noIterationTypes);
75722                     }
75723                     else {
75724                         return iterationTypes;
75725                     }
75726                 }
75727             }
75728             return noIterationTypes;
75729         }
75730         /**
75731          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or
75732          * `AsyncIterable`-like type from the cache.
75733          *
75734          * NOTE: You probably don't want to call this directly and should be calling
75735          * `getIterationTypesOfIterable` instead.
75736          */
75737         function getIterationTypesOfIterableCached(type, resolver) {
75738             return getCachedIterationTypes(type, resolver.iterableCacheKey);
75739         }
75740         function getIterationTypesOfGlobalIterableType(globalType, resolver) {
75741             var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) ||
75742                 getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined);
75743             return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes;
75744         }
75745         /**
75746          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
75747          * type from from common heuristics.
75748          *
75749          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
75750          * returned. If we found iteration types, an `IterationTypes` record is returned.
75751          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
75752          * exhaustive analysis.
75753          *
75754          * NOTE: You probably don't want to call this directly and should be calling
75755          * `getIterationTypesOfIterable` instead.
75756          */
75757         function getIterationTypesOfIterableFast(type, resolver) {
75758             // As an optimization, if the type is an instantiation of one of the following global types, then
75759             // just grab its related type argument:
75760             // - `Iterable<T>` or `AsyncIterable<T>`
75761             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
75762             var globalType;
75763             if (isReferenceToType(type, globalType = resolver.getGlobalIterableType(/*reportErrors*/ false)) ||
75764                 isReferenceToType(type, globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false))) {
75765                 var yieldType = getTypeArguments(type)[0];
75766                 // The "return" and "next" types of `Iterable` and `IterableIterator` are defined by the
75767                 // iteration types of their `[Symbol.iterator]()` method. The same is true for their async cousins.
75768                 // While we define these as `any` and `undefined` in our libs by default, a custom lib *could* use
75769                 // different definitions.
75770                 var _a = getIterationTypesOfGlobalIterableType(globalType, resolver), returnType = _a.returnType, nextType = _a.nextType;
75771                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
75772             }
75773             // As an optimization, if the type is an instantiation of the following global type, then
75774             // just grab its related type arguments:
75775             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
75776             if (isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
75777                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
75778                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
75779             }
75780         }
75781         /**
75782          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
75783          * type from its members.
75784          *
75785          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
75786          * record is returned. Otherwise, `noIterationTypes` is returned.
75787          *
75788          * NOTE: You probably don't want to call this directly and should be calling
75789          * `getIterationTypesOfIterable` instead.
75790          */
75791         function getIterationTypesOfIterableSlow(type, resolver, errorNode) {
75792             var _a;
75793             var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName));
75794             var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined;
75795             if (isTypeAny(methodType)) {
75796                 return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes);
75797             }
75798             var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined;
75799             if (!ts.some(signatures)) {
75800                 return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes);
75801             }
75802             var iteratorType = getIntersectionType(ts.map(signatures, getReturnTypeOfSignature));
75803             var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes;
75804             return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes);
75805         }
75806         function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
75807             var message = allowAsyncIterables
75808                 ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
75809                 : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
75810             errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type));
75811         }
75812         /**
75813          * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type.
75814          *
75815          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
75816          * record is returned. Otherwise, `undefined` is returned.
75817          */
75818         function getIterationTypesOfIterator(type, resolver, errorNode) {
75819             if (isTypeAny(type)) {
75820                 return anyIterationTypes;
75821             }
75822             var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) ||
75823                 getIterationTypesOfIteratorFast(type, resolver) ||
75824                 getIterationTypesOfIteratorSlow(type, resolver, errorNode);
75825             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
75826         }
75827         /**
75828          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
75829          * cache.
75830          *
75831          * NOTE: You probably don't want to call this directly and should be calling
75832          * `getIterationTypesOfIterator` instead.
75833          */
75834         function getIterationTypesOfIteratorCached(type, resolver) {
75835             return getCachedIterationTypes(type, resolver.iteratorCacheKey);
75836         }
75837         /**
75838          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
75839          * cache or from common heuristics.
75840          *
75841          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
75842          * returned. If we found iteration types, an `IterationTypes` record is returned.
75843          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
75844          * exhaustive analysis.
75845          *
75846          * NOTE: You probably don't want to call this directly and should be calling
75847          * `getIterationTypesOfIterator` instead.
75848          */
75849         function getIterationTypesOfIteratorFast(type, resolver) {
75850             // As an optimization, if the type is an instantiation of one of the following global types,
75851             // then just grab its related type argument:
75852             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
75853             // - `Iterator<T, TReturn, TNext>` or `AsyncIterator<T, TReturn, TNext>`
75854             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
75855             var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
75856             if (isReferenceToType(type, globalType)) {
75857                 var yieldType = getTypeArguments(type)[0];
75858                 // The "return" and "next" types of `IterableIterator` and `AsyncIterableIterator` are defined by the
75859                 // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any`
75860                 // and `undefined` in our libs by default, a custom lib *could* use different definitions.
75861                 var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) ||
75862                     getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined);
75863                 var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType;
75864                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
75865             }
75866             if (isReferenceToType(type, resolver.getGlobalIteratorType(/*reportErrors*/ false)) ||
75867                 isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
75868                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
75869                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
75870             }
75871         }
75872         function isIteratorResult(type, kind) {
75873             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface:
75874             // > [done] is the result status of an iterator `next` method call. If the end of the iterator was reached `done` is `true`.
75875             // > If the end was not reached `done` is `false` and a value is available.
75876             // > If a `done` property (either own or inherited) does not exist, it is consider to have the value `false`.
75877             var doneType = getTypeOfPropertyOfType(type, "done") || falseType;
75878             return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType);
75879         }
75880         function isYieldIteratorResult(type) {
75881             return isIteratorResult(type, 0 /* Yield */);
75882         }
75883         function isReturnIteratorResult(type) {
75884             return isIteratorResult(type, 1 /* Return */);
75885         }
75886         /**
75887          * Gets the *yield* and *return* types of an `IteratorResult`-like type.
75888          *
75889          * If we are unable to determine a *yield* or a *return* type, `noIterationTypes` is
75890          * returned to indicate to the caller that it should handle the error. Otherwise, an
75891          * `IterationTypes` record is returned.
75892          */
75893         function getIterationTypesOfIteratorResult(type) {
75894             if (isTypeAny(type)) {
75895                 return anyIterationTypes;
75896             }
75897             var cachedTypes = getCachedIterationTypes(type, "iterationTypesOfIteratorResult");
75898             if (cachedTypes) {
75899                 return cachedTypes;
75900             }
75901             // As an optimization, if the type is an instantiation of one of the global `IteratorYieldResult<T>`
75902             // or `IteratorReturnResult<TReturn>` types, then just grab its type argument.
75903             if (isReferenceToType(type, getGlobalIteratorYieldResultType(/*reportErrors*/ false))) {
75904                 var yieldType_1 = getTypeArguments(type)[0];
75905                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType_1, /*returnType*/ undefined, /*nextType*/ undefined));
75906             }
75907             if (isReferenceToType(type, getGlobalIteratorReturnResultType(/*reportErrors*/ false))) {
75908                 var returnType_1 = getTypeArguments(type)[0];
75909                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(/*yieldType*/ undefined, returnType_1, /*nextType*/ undefined));
75910             }
75911             // Choose any constituents that can produce the requested iteration type.
75912             var yieldIteratorResult = filterType(type, isYieldIteratorResult);
75913             var yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : undefined;
75914             var returnIteratorResult = filterType(type, isReturnIteratorResult);
75915             var returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : undefined;
75916             if (!yieldType && !returnType) {
75917                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes);
75918             }
75919             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface
75920             // > ... If the iterator does not have a return value, `value` is `undefined`. In that case, the
75921             // > `value` property may be absent from the conforming object if it does not inherit an explicit
75922             // > `value` property.
75923             return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType, returnType || voidType, /*nextType*/ undefined));
75924         }
75925         /**
75926          * Gets the *yield*, *return*, and *next* types of a the `next()`, `return()`, or
75927          * `throw()` method of an `Iterator`-like or `AsyncIterator`-like type.
75928          *
75929          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
75930          * record is returned. Otherwise, we return `undefined`.
75931          */
75932         function getIterationTypesOfMethod(type, resolver, methodName, errorNode) {
75933             var _a, _b, _c, _d;
75934             var method = getPropertyOfType(type, methodName);
75935             // Ignore 'return' or 'throw' if they are missing.
75936             if (!method && methodName !== "next") {
75937                 return undefined;
75938             }
75939             var methodType = method && !(methodName === "next" && (method.flags & 16777216 /* Optional */))
75940                 ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */)
75941                 : undefined;
75942             if (isTypeAny(methodType)) {
75943                 // `return()` and `throw()` don't provide a *next* type.
75944                 return methodName === "next" ? anyIterationTypes : anyIterationTypesExceptNext;
75945             }
75946             // Both async and non-async iterators *must* have a `next` method.
75947             var methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : ts.emptyArray;
75948             if (methodSignatures.length === 0) {
75949                 if (errorNode) {
75950                     var diagnostic = methodName === "next"
75951                         ? resolver.mustHaveANextMethodDiagnostic
75952                         : resolver.mustBeAMethodDiagnostic;
75953                     error(errorNode, diagnostic, methodName);
75954                 }
75955                 return methodName === "next" ? anyIterationTypes : undefined;
75956             }
75957             // If the method signature comes exclusively from the global iterator or generator type,
75958             // create iteration types from its type arguments like `getIterationTypesOfIteratorFast`
75959             // does (so as to remove `undefined` from the next and return types). We arrive here when
75960             // a contextual type for a generator was not a direct reference to one of those global types,
75961             // but looking up `methodType` referred to one of them (and nothing else). E.g., in
75962             // `interface SpecialIterator extends Iterator<number> {}`, `SpecialIterator` is not a
75963             // reference to `Iterator`, but its `next` member derives exclusively from `Iterator`.
75964             if ((methodType === null || methodType === void 0 ? void 0 : methodType.symbol) && methodSignatures.length === 1) {
75965                 var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
75966                 var globalIteratorType = resolver.getGlobalIteratorType(/*reportErrors*/ false);
75967                 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;
75968                 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;
75969                 if (isGeneratorMethod || isIteratorMethod) {
75970                     var globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType;
75971                     var mapper = methodType.mapper;
75972                     return createIterationTypes(getMappedType(globalType.typeParameters[0], mapper), getMappedType(globalType.typeParameters[1], mapper), methodName === "next" ? getMappedType(globalType.typeParameters[2], mapper) : undefined);
75973                 }
75974             }
75975             // Extract the first parameter and return type of each signature.
75976             var methodParameterTypes;
75977             var methodReturnTypes;
75978             for (var _i = 0, methodSignatures_1 = methodSignatures; _i < methodSignatures_1.length; _i++) {
75979                 var signature = methodSignatures_1[_i];
75980                 if (methodName !== "throw" && ts.some(signature.parameters)) {
75981                     methodParameterTypes = ts.append(methodParameterTypes, getTypeAtPosition(signature, 0));
75982                 }
75983                 methodReturnTypes = ts.append(methodReturnTypes, getReturnTypeOfSignature(signature));
75984             }
75985             // Resolve the *next* or *return* type from the first parameter of a `next()` or
75986             // `return()` method, respectively.
75987             var returnTypes;
75988             var nextType;
75989             if (methodName !== "throw") {
75990                 var methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType;
75991                 if (methodName === "next") {
75992                     // The value of `next(value)` is *not* awaited by async generators
75993                     nextType = methodParameterType;
75994                 }
75995                 else if (methodName === "return") {
75996                     // The value of `return(value)` *is* awaited by async generators
75997                     var resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType;
75998                     returnTypes = ts.append(returnTypes, resolvedMethodParameterType);
75999                 }
76000             }
76001             // Resolve the *yield* and *return* types from the return type of the method (i.e. `IteratorResult`)
76002             var yieldType;
76003             var methodReturnType = methodReturnTypes ? getIntersectionType(methodReturnTypes) : neverType;
76004             var resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType;
76005             var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType);
76006             if (iterationTypes === noIterationTypes) {
76007                 if (errorNode) {
76008                     error(errorNode, resolver.mustHaveAValueDiagnostic, methodName);
76009                 }
76010                 yieldType = anyType;
76011                 returnTypes = ts.append(returnTypes, anyType);
76012             }
76013             else {
76014                 yieldType = iterationTypes.yieldType;
76015                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
76016             }
76017             return createIterationTypes(yieldType, getUnionType(returnTypes), nextType);
76018         }
76019         /**
76020          * Gets the *yield*, *return*, and *next* types of an `Iterator`-like or `AsyncIterator`-like
76021          * type from its members.
76022          *
76023          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
76024          * record is returned. Otherwise, `noIterationTypes` is returned.
76025          *
76026          * NOTE: You probably don't want to call this directly and should be calling
76027          * `getIterationTypesOfIterator` instead.
76028          */
76029         function getIterationTypesOfIteratorSlow(type, resolver, errorNode) {
76030             var iterationTypes = combineIterationTypes([
76031                 getIterationTypesOfMethod(type, resolver, "next", errorNode),
76032                 getIterationTypesOfMethod(type, resolver, "return", errorNode),
76033                 getIterationTypesOfMethod(type, resolver, "throw", errorNode),
76034             ]);
76035             return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes);
76036         }
76037         /**
76038          * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like,
76039          * `IterableIterator`-like, or `Generator`-like (for a non-async generator); or `AsyncIterable`-like,
76040          * `AsyncIterator`-like, `AsyncIterableIterator`-like, or `AsyncGenerator`-like (for an async generator).
76041          */
76042         function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) {
76043             if (isTypeAny(returnType)) {
76044                 return undefined;
76045             }
76046             var iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator);
76047             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)];
76048         }
76049         function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) {
76050             if (isTypeAny(type)) {
76051                 return anyIterationTypes;
76052             }
76053             var use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
76054             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
76055             return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) ||
76056                 getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined);
76057         }
76058         function checkBreakOrContinueStatement(node) {
76059             // Grammar checking
76060             if (!checkGrammarStatementInAmbientContext(node))
76061                 checkGrammarBreakOrContinueStatement(node);
76062             // TODO: Check that target label is valid
76063         }
76064         function unwrapReturnType(returnType, functionFlags) {
76065             var _a, _b;
76066             var isGenerator = !!(functionFlags & 1 /* Generator */);
76067             var isAsync = !!(functionFlags & 2 /* Async */);
76068             return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType :
76069                 isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType :
76070                     returnType;
76071         }
76072         function isUnwrappedReturnTypeVoidOrAny(func, returnType) {
76073             var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func));
76074             return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */);
76075         }
76076         function checkReturnStatement(node) {
76077             var _a;
76078             // Grammar checking
76079             if (checkGrammarStatementInAmbientContext(node)) {
76080                 return;
76081             }
76082             var func = ts.getContainingFunction(node);
76083             if (!func) {
76084                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
76085                 return;
76086             }
76087             var signature = getSignatureFromDeclaration(func);
76088             var returnType = getReturnTypeOfSignature(signature);
76089             var functionFlags = ts.getFunctionFlags(func);
76090             if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) {
76091                 var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
76092                 if (func.kind === 168 /* SetAccessor */) {
76093                     if (node.expression) {
76094                         error(node, ts.Diagnostics.Setters_cannot_return_a_value);
76095                     }
76096                 }
76097                 else if (func.kind === 166 /* Constructor */) {
76098                     if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
76099                         error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
76100                     }
76101                 }
76102                 else if (getReturnTypeFromAnnotation(func)) {
76103                     var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType;
76104                     var unwrappedExprType = functionFlags & 2 /* Async */
76105                         ? checkAwaitedType(exprType, node, ts.Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member)
76106                         : exprType;
76107                     if (unwrappedReturnType) {
76108                         // If the function has a return type, but promisedType is
76109                         // undefined, an error will be reported in checkAsyncFunctionReturnType
76110                         // so we don't need to report one here.
76111                         checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression);
76112                     }
76113                 }
76114             }
76115             else if (func.kind !== 166 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) {
76116                 // The function has a return type, but the return statement doesn't have an expression.
76117                 error(node, ts.Diagnostics.Not_all_code_paths_return_a_value);
76118             }
76119         }
76120         function checkWithStatement(node) {
76121             // Grammar checking for withStatement
76122             if (!checkGrammarStatementInAmbientContext(node)) {
76123                 if (node.flags & 32768 /* AwaitContext */) {
76124                     grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
76125                 }
76126             }
76127             checkExpression(node.expression);
76128             var sourceFile = ts.getSourceFileOfNode(node);
76129             if (!hasParseDiagnostics(sourceFile)) {
76130                 var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start;
76131                 var end = node.statement.pos;
76132                 grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
76133             }
76134         }
76135         function checkSwitchStatement(node) {
76136             // Grammar checking
76137             checkGrammarStatementInAmbientContext(node);
76138             var firstDefaultClause;
76139             var hasDuplicateDefaultClause = false;
76140             var expressionType = checkExpression(node.expression);
76141             var expressionIsLiteral = isLiteralType(expressionType);
76142             ts.forEach(node.caseBlock.clauses, function (clause) {
76143                 // Grammar check for duplicate default clauses, skip if we already report duplicate default clause
76144                 if (clause.kind === 285 /* DefaultClause */ && !hasDuplicateDefaultClause) {
76145                     if (firstDefaultClause === undefined) {
76146                         firstDefaultClause = clause;
76147                     }
76148                     else {
76149                         grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
76150                         hasDuplicateDefaultClause = true;
76151                     }
76152                 }
76153                 if (produceDiagnostics && clause.kind === 284 /* CaseClause */) {
76154                     // TypeScript 1.0 spec (April 2014): 5.9
76155                     // In a 'switch' statement, each 'case' expression must be of a type that is comparable
76156                     // to or from the type of the 'switch' expression.
76157                     var caseType = checkExpression(clause.expression);
76158                     var caseIsLiteral = isLiteralType(caseType);
76159                     var comparedExpressionType = expressionType;
76160                     if (!caseIsLiteral || !expressionIsLiteral) {
76161                         caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType;
76162                         comparedExpressionType = getBaseTypeOfLiteralType(expressionType);
76163                     }
76164                     if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) {
76165                         // expressionType is not comparable to caseType, try the reversed check and report errors if it fails
76166                         checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined);
76167                     }
76168                 }
76169                 ts.forEach(clause.statements, checkSourceElement);
76170                 if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) {
76171                     error(clause, ts.Diagnostics.Fallthrough_case_in_switch);
76172                 }
76173             });
76174             if (node.caseBlock.locals) {
76175                 registerForUnusedIdentifiersCheck(node.caseBlock);
76176             }
76177         }
76178         function checkLabeledStatement(node) {
76179             // Grammar checking
76180             if (!checkGrammarStatementInAmbientContext(node)) {
76181                 ts.findAncestor(node.parent, function (current) {
76182                     if (ts.isFunctionLike(current)) {
76183                         return "quit";
76184                     }
76185                     if (current.kind === 245 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
76186                         grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label));
76187                         return true;
76188                     }
76189                     return false;
76190                 });
76191             }
76192             // ensure that label is unique
76193             checkSourceElement(node.statement);
76194         }
76195         function checkThrowStatement(node) {
76196             // Grammar checking
76197             if (!checkGrammarStatementInAmbientContext(node)) {
76198                 if (ts.isIdentifier(node.expression) && !node.expression.escapedText) {
76199                     grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here);
76200                 }
76201             }
76202             if (node.expression) {
76203                 checkExpression(node.expression);
76204             }
76205         }
76206         function checkTryStatement(node) {
76207             // Grammar checking
76208             checkGrammarStatementInAmbientContext(node);
76209             checkBlock(node.tryBlock);
76210             var catchClause = node.catchClause;
76211             if (catchClause) {
76212                 // Grammar checking
76213                 if (catchClause.variableDeclaration) {
76214                     var declaration = catchClause.variableDeclaration;
76215                     if (declaration.type) {
76216                         var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ false);
76217                         if (type && !(type.flags & 3 /* AnyOrUnknown */)) {
76218                             grammarErrorOnFirstToken(declaration.type, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified);
76219                         }
76220                     }
76221                     else if (declaration.initializer) {
76222                         grammarErrorOnFirstToken(declaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
76223                     }
76224                     else {
76225                         var blockLocals_1 = catchClause.block.locals;
76226                         if (blockLocals_1) {
76227                             ts.forEachKey(catchClause.locals, function (caughtName) {
76228                                 var blockLocal = blockLocals_1.get(caughtName);
76229                                 if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
76230                                     grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName);
76231                                 }
76232                             });
76233                         }
76234                     }
76235                 }
76236                 checkBlock(catchClause.block);
76237             }
76238             if (node.finallyBlock) {
76239                 checkBlock(node.finallyBlock);
76240             }
76241         }
76242         function checkIndexConstraints(type) {
76243             var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */);
76244             var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */);
76245             var stringIndexType = getIndexTypeOfType(type, 0 /* String */);
76246             var numberIndexType = getIndexTypeOfType(type, 1 /* Number */);
76247             if (stringIndexType || numberIndexType) {
76248                 ts.forEach(getPropertiesOfObjectType(type), function (prop) {
76249                     var propType = getTypeOfSymbol(prop);
76250                     checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
76251                     checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
76252                 });
76253                 var classDeclaration = type.symbol.valueDeclaration;
76254                 if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) {
76255                     for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) {
76256                         var member = _a[_i];
76257                         // Only process instance properties with computed names here.
76258                         // Static properties cannot be in conflict with indexers,
76259                         // and properties with literal names were already checked.
76260                         if (!ts.hasSyntacticModifier(member, 32 /* Static */) && !hasBindableName(member)) {
76261                             var symbol = getSymbolOfNode(member);
76262                             var propType = getTypeOfSymbol(symbol);
76263                             checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
76264                             checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
76265                         }
76266                     }
76267                 }
76268             }
76269             var errorNode;
76270             if (stringIndexType && numberIndexType) {
76271                 errorNode = declaredNumberIndexer || declaredStringIndexer;
76272                 // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer
76273                 if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) {
76274                     var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); });
76275                     errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0];
76276                 }
76277             }
76278             if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217
76279                 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType));
76280             }
76281             function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) {
76282                 // ESSymbol properties apply to neither string nor numeric indexers.
76283                 if (!indexType || ts.isKnownSymbol(prop)) {
76284                     return;
76285                 }
76286                 var propDeclaration = prop.valueDeclaration;
76287                 var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration);
76288                 if (name && ts.isPrivateIdentifier(name)) {
76289                     return;
76290                 }
76291                 // index is numeric and property name is not valid numeric literal
76292                 if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) {
76293                     return;
76294                 }
76295                 // perform property check if property or indexer is declared in 'type'
76296                 // this allows us to rule out cases when both property and indexer are inherited from the base class
76297                 var errorNode;
76298                 if (propDeclaration && name &&
76299                     (propDeclaration.kind === 216 /* BinaryExpression */ ||
76300                         name.kind === 158 /* ComputedPropertyName */ ||
76301                         prop.parent === containingType.symbol)) {
76302                     errorNode = propDeclaration;
76303                 }
76304                 else if (indexDeclaration) {
76305                     errorNode = indexDeclaration;
76306                 }
76307                 else if (ts.getObjectFlags(containingType) & 2 /* Interface */) {
76308                     // for interfaces property and indexer might be inherited from different bases
76309                     // check if any base class already has both property and indexer.
76310                     // check should be performed only if 'type' is the first type that brings property\indexer together
76311                     var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); });
76312                     errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0];
76313                 }
76314                 if (errorNode && !isTypeAssignableTo(propertyType, indexType)) {
76315                     var errorMessage = indexKind === 0 /* String */
76316                         ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2
76317                         : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2;
76318                     error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType));
76319                 }
76320             }
76321         }
76322         function checkTypeNameIsReserved(name, message) {
76323             // TS 1.0 spec (April 2014): 3.6.1
76324             // The predefined type keywords are reserved and cannot be used as names of user defined types.
76325             switch (name.escapedText) {
76326                 case "any":
76327                 case "unknown":
76328                 case "number":
76329                 case "bigint":
76330                 case "boolean":
76331                 case "string":
76332                 case "symbol":
76333                 case "void":
76334                 case "object":
76335                     error(name, message, name.escapedText);
76336             }
76337         }
76338         /**
76339          * The name cannot be used as 'Object' of user defined types with special target.
76340          */
76341         function checkClassNameCollisionWithObject(name) {
76342             if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object"
76343                 && moduleKind < ts.ModuleKind.ES2015) {
76344                 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
76345             }
76346         }
76347         /**
76348          * Check each type parameter and check that type parameters have no duplicate type parameter declarations
76349          */
76350         function checkTypeParameters(typeParameterDeclarations) {
76351             if (typeParameterDeclarations) {
76352                 var seenDefault = false;
76353                 for (var i = 0; i < typeParameterDeclarations.length; i++) {
76354                     var node = typeParameterDeclarations[i];
76355                     checkTypeParameter(node);
76356                     if (produceDiagnostics) {
76357                         if (node.default) {
76358                             seenDefault = true;
76359                             checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
76360                         }
76361                         else if (seenDefault) {
76362                             error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
76363                         }
76364                         for (var j = 0; j < i; j++) {
76365                             if (typeParameterDeclarations[j].symbol === node.symbol) {
76366                                 error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));
76367                             }
76368                         }
76369                     }
76370                 }
76371             }
76372         }
76373         /** Check that type parameter defaults only reference previously declared type parameters */
76374         function checkTypeParametersNotReferenced(root, typeParameters, index) {
76375             visit(root);
76376             function visit(node) {
76377                 if (node.kind === 173 /* TypeReference */) {
76378                     var type = getTypeFromTypeReference(node);
76379                     if (type.flags & 262144 /* TypeParameter */) {
76380                         for (var i = index; i < typeParameters.length; i++) {
76381                             if (type.symbol === getSymbolOfNode(typeParameters[i])) {
76382                                 error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
76383                             }
76384                         }
76385                     }
76386                 }
76387                 ts.forEachChild(node, visit);
76388             }
76389         }
76390         /** Check that type parameter lists are identical across multiple declarations */
76391         function checkTypeParameterListsIdentical(symbol) {
76392             if (symbol.declarations.length === 1) {
76393                 return;
76394             }
76395             var links = getSymbolLinks(symbol);
76396             if (!links.typeParametersChecked) {
76397                 links.typeParametersChecked = true;
76398                 var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
76399                 if (declarations.length <= 1) {
76400                     return;
76401                 }
76402                 var type = getDeclaredTypeOfSymbol(symbol);
76403                 if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) {
76404                     // Report an error on every conflicting declaration.
76405                     var name = symbolToString(symbol);
76406                     for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
76407                         var declaration = declarations_6[_i];
76408                         error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
76409                     }
76410                 }
76411             }
76412         }
76413         function areTypeParametersIdentical(declarations, targetParameters) {
76414             var maxTypeArgumentCount = ts.length(targetParameters);
76415             var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
76416             for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
76417                 var declaration = declarations_7[_i];
76418                 // If this declaration has too few or too many type parameters, we report an error
76419                 var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
76420                 var numTypeParameters = sourceParameters.length;
76421                 if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
76422                     return false;
76423                 }
76424                 for (var i = 0; i < numTypeParameters; i++) {
76425                     var source = sourceParameters[i];
76426                     var target = targetParameters[i];
76427                     // If the type parameter node does not have the same as the resolved type
76428                     // parameter at this position, we report an error.
76429                     if (source.name.escapedText !== target.symbol.escapedName) {
76430                         return false;
76431                     }
76432                     // If the type parameter node does not have an identical constraint as the resolved
76433                     // type parameter at this position, we report an error.
76434                     var constraint = ts.getEffectiveConstraintOfTypeParameter(source);
76435                     var sourceConstraint = constraint && getTypeFromTypeNode(constraint);
76436                     var targetConstraint = getConstraintOfTypeParameter(target);
76437                     // relax check if later interface augmentation has no constraint, it's more broad and is OK to merge with
76438                     // a more constrained interface (this could be generalized to a full hierarchy check, but that's maybe overkill)
76439                     if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
76440                         return false;
76441                     }
76442                     // If the type parameter node has a default and it is not identical to the default
76443                     // for the type parameter at this position, we report an error.
76444                     var sourceDefault = source.default && getTypeFromTypeNode(source.default);
76445                     var targetDefault = getDefaultFromTypeParameter(target);
76446                     if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
76447                         return false;
76448                     }
76449                 }
76450             }
76451             return true;
76452         }
76453         function checkClassExpression(node) {
76454             checkClassLikeDeclaration(node);
76455             checkNodeDeferred(node);
76456             return getTypeOfSymbol(getSymbolOfNode(node));
76457         }
76458         function checkClassExpressionDeferred(node) {
76459             ts.forEach(node.members, checkSourceElement);
76460             registerForUnusedIdentifiersCheck(node);
76461         }
76462         function checkClassDeclaration(node) {
76463             if (!node.name && !ts.hasSyntacticModifier(node, 512 /* Default */)) {
76464                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
76465             }
76466             checkClassLikeDeclaration(node);
76467             ts.forEach(node.members, checkSourceElement);
76468             registerForUnusedIdentifiersCheck(node);
76469         }
76470         function checkClassLikeDeclaration(node) {
76471             checkGrammarClassLikeDeclaration(node);
76472             checkDecorators(node);
76473             if (node.name) {
76474                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0);
76475                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
76476                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
76477                 if (!(node.flags & 8388608 /* Ambient */)) {
76478                     checkClassNameCollisionWithObject(node.name);
76479                 }
76480             }
76481             checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
76482             checkExportsOnMergedDeclarations(node);
76483             var symbol = getSymbolOfNode(node);
76484             var type = getDeclaredTypeOfSymbol(symbol);
76485             var typeWithThis = getTypeWithThisArgument(type);
76486             var staticType = getTypeOfSymbol(symbol);
76487             checkTypeParameterListsIdentical(symbol);
76488             checkFunctionOrConstructorSymbol(symbol);
76489             checkClassForDuplicateDeclarations(node);
76490             // Only check for reserved static identifiers on non-ambient context.
76491             if (!(node.flags & 8388608 /* Ambient */)) {
76492                 checkClassForStaticPropertyNameConflicts(node);
76493             }
76494             var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
76495             if (baseTypeNode) {
76496                 ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
76497                 if (languageVersion < 2 /* ES2015 */) {
76498                     checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
76499                 }
76500                 // check both @extends and extends if both are specified.
76501                 var extendsNode = ts.getClassExtendsHeritageElement(node);
76502                 if (extendsNode && extendsNode !== baseTypeNode) {
76503                     checkExpression(extendsNode.expression);
76504                 }
76505                 var baseTypes = getBaseTypes(type);
76506                 if (baseTypes.length && produceDiagnostics) {
76507                     var baseType_1 = baseTypes[0];
76508                     var baseConstructorType = getBaseConstructorTypeOfClass(type);
76509                     var staticBaseType = getApparentType(baseConstructorType);
76510                     checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
76511                     checkSourceElement(baseTypeNode.expression);
76512                     if (ts.some(baseTypeNode.typeArguments)) {
76513                         ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
76514                         for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) {
76515                             var constructor = _a[_i];
76516                             if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
76517                                 break;
76518                             }
76519                         }
76520                     }
76521                     var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType);
76522                     if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
76523                         issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1);
76524                     }
76525                     else {
76526                         // Report static side error only when instance type is assignable
76527                         checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
76528                     }
76529                     if (baseConstructorType.flags & 8650752 /* TypeVariable */) {
76530                         if (!isMixinConstructorType(staticType)) {
76531                             error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
76532                         }
76533                         else {
76534                             var constructSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
76535                             if (constructSignatures.some(function (signature) { return signature.flags & 4 /* Abstract */; }) && !ts.hasSyntacticModifier(node, 128 /* Abstract */)) {
76536                                 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);
76537                             }
76538                         }
76539                     }
76540                     if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
76541                         // When the static base type is a "class-like" constructor function (but not actually a class), we verify
76542                         // that all instantiated base constructor signatures return the same type.
76543                         var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
76544                         if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType_1); })) {
76545                             error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type);
76546                         }
76547                     }
76548                     checkKindsOfPropertyMemberOverrides(type, baseType_1);
76549                 }
76550             }
76551             var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node);
76552             if (implementedTypeNodes) {
76553                 for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) {
76554                     var typeRefNode = implementedTypeNodes_1[_b];
76555                     if (!ts.isEntityNameExpression(typeRefNode.expression) || ts.isOptionalChain(typeRefNode.expression)) {
76556                         error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
76557                     }
76558                     checkTypeReferenceNode(typeRefNode);
76559                     if (produceDiagnostics) {
76560                         var t = getReducedType(getTypeFromTypeNode(typeRefNode));
76561                         if (t !== errorType) {
76562                             if (isValidBaseType(t)) {
76563                                 var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ?
76564                                     ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass :
76565                                     ts.Diagnostics.Class_0_incorrectly_implements_interface_1;
76566                                 var baseWithThis = getTypeWithThisArgument(t, type.thisType);
76567                                 if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
76568                                     issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
76569                                 }
76570                             }
76571                             else {
76572                                 error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
76573                             }
76574                         }
76575                     }
76576                 }
76577             }
76578             if (produceDiagnostics) {
76579                 checkIndexConstraints(type);
76580                 checkTypeForDuplicateIndexSignatures(node);
76581                 checkPropertyInitialization(node);
76582             }
76583         }
76584         function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
76585             // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
76586             var issuedMemberError = false;
76587             var _loop_23 = function (member) {
76588                 if (ts.hasStaticModifier(member)) {
76589                     return "continue";
76590                 }
76591                 var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
76592                 if (declaredProp) {
76593                     var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
76594                     var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
76595                     if (prop && baseProp) {
76596                         var rootChain = function () { return ts.chainDiagnosticMessages(
76597                         /*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)); };
76598                         if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
76599                             issuedMemberError = true;
76600                         }
76601                     }
76602                 }
76603             };
76604             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
76605                 var member = _a[_i];
76606                 _loop_23(member);
76607             }
76608             if (!issuedMemberError) {
76609                 // check again with diagnostics to generate a less-specific error
76610                 checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
76611             }
76612         }
76613         function checkBaseTypeAccessibility(type, node) {
76614             var signatures = getSignaturesOfType(type, 1 /* Construct */);
76615             if (signatures.length) {
76616                 var declaration = signatures[0].declaration;
76617                 if (declaration && ts.hasEffectiveModifier(declaration, 8 /* Private */)) {
76618                     var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
76619                     if (!isNodeWithinClass(node, typeClassDeclaration)) {
76620                         error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
76621                     }
76622                 }
76623             }
76624         }
76625         function getTargetSymbol(s) {
76626             // if symbol is instantiated its flags are not copied from the 'target'
76627             // so we'll need to get back original 'target' symbol to work with correct set of flags
76628             return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s;
76629         }
76630         function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
76631             return ts.filter(symbol.declarations, function (d) {
76632                 return d.kind === 252 /* ClassDeclaration */ || d.kind === 253 /* InterfaceDeclaration */;
76633             });
76634         }
76635         function checkKindsOfPropertyMemberOverrides(type, baseType) {
76636             // TypeScript 1.0 spec (April 2014): 8.2.3
76637             // A derived class inherits all members from its base class it doesn't override.
76638             // Inheritance means that a derived class implicitly contains all non - overridden members of the base class.
76639             // Both public and private property members are inherited, but only public property members can be overridden.
76640             // A property member in a derived class is said to override a property member in a base class
76641             // when the derived class property member has the same name and kind(instance or static)
76642             // as the base class property member.
76643             // The type of an overriding property member must be assignable(section 3.8.4)
76644             // to the type of the overridden property member, or otherwise a compile - time error occurs.
76645             // Base class instance member functions can be overridden by derived class instance member functions,
76646             // but not by other kinds of members.
76647             // Base class instance member variables and accessors can be overridden by
76648             // derived class instance member variables and accessors, but not by other kinds of members.
76649             // NOTE: assignability is checked in checkClassDeclaration
76650             var baseProperties = getPropertiesOfType(baseType);
76651             basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) {
76652                 var baseProperty = baseProperties_1[_i];
76653                 var base = getTargetSymbol(baseProperty);
76654                 if (base.flags & 4194304 /* Prototype */) {
76655                     continue;
76656                 }
76657                 var baseSymbol = getPropertyOfObjectType(type, base.escapedName);
76658                 if (!baseSymbol) {
76659                     continue;
76660                 }
76661                 var derived = getTargetSymbol(baseSymbol);
76662                 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base);
76663                 ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
76664                 // In order to resolve whether the inherited method was overridden in the base class or not,
76665                 // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated*
76666                 // type declaration, derived and base resolve to the same symbol even in the case of generic classes.
76667                 if (derived === base) {
76668                     // derived class inherits base without override/redeclaration
76669                     var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol);
76670                     // It is an error to inherit an abstract member without implementing it or being declared abstract.
76671                     // If there is no declaration for the derived class (as in the case of class expressions),
76672                     // then the class cannot be declared abstract.
76673                     if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasSyntacticModifier(derivedClassDecl, 128 /* Abstract */))) {
76674                         // Searches other base types for a declaration that would satisfy the inherited abstract member.
76675                         // (The class may have more than one base type via declaration merging with an interface with the
76676                         // same name.)
76677                         for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) {
76678                             var otherBaseType = _b[_a];
76679                             if (otherBaseType === baseType)
76680                                 continue;
76681                             var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName);
76682                             var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1);
76683                             if (derivedElsewhere && derivedElsewhere !== base) {
76684                                 continue basePropertyCheck;
76685                             }
76686                         }
76687                         if (derivedClassDecl.kind === 221 /* ClassExpression */) {
76688                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType));
76689                         }
76690                         else {
76691                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType));
76692                         }
76693                     }
76694                 }
76695                 else {
76696                     // derived overrides base.
76697                     var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived);
76698                     if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) {
76699                         // either base or derived property is private - not override, skip it
76700                         continue;
76701                     }
76702                     var errorMessage = void 0;
76703                     var basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */;
76704                     var derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */;
76705                     if (basePropertyFlags && derivedPropertyFlags) {
76706                         // property/accessor is overridden with property/accessor
76707                         if (baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer)
76708                             || base.valueDeclaration && base.valueDeclaration.parent.kind === 253 /* InterfaceDeclaration */
76709                             || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) {
76710                             // when the base property is abstract or from an interface, base/derived flags don't need to match
76711                             // same when the derived property is from an assignment
76712                             continue;
76713                         }
76714                         var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */;
76715                         var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */;
76716                         if (overriddenInstanceProperty || overriddenInstanceAccessor) {
76717                             var errorMessage_1 = overriddenInstanceProperty ?
76718                                 ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property :
76719                                 ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
76720                             error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type));
76721                         }
76722                         else if (compilerOptions.useDefineForClassFields) {
76723                             var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 163 /* PropertyDeclaration */ && !d.initializer; });
76724                             if (uninitialized
76725                                 && !(derived.flags & 33554432 /* Transient */)
76726                                 && !(baseDeclarationFlags & 128 /* Abstract */)
76727                                 && !(derivedDeclarationFlags & 128 /* Abstract */)
76728                                 && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) {
76729                                 var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol));
76730                                 var propName = uninitialized.name;
76731                                 if (uninitialized.exclamationToken
76732                                     || !constructor
76733                                     || !ts.isIdentifier(propName)
76734                                     || !strictNullChecks
76735                                     || !isPropertyInitializedInConstructor(propName, type, constructor)) {
76736                                     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;
76737                                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType));
76738                                 }
76739                             }
76740                         }
76741                         // correct case
76742                         continue;
76743                     }
76744                     else if (isPrototypeProperty(base)) {
76745                         if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) {
76746                             // method is overridden with method or property -- correct case
76747                             continue;
76748                         }
76749                         else {
76750                             ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */));
76751                             errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
76752                         }
76753                     }
76754                     else if (base.flags & 98304 /* Accessor */) {
76755                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
76756                     }
76757                     else {
76758                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
76759                     }
76760                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
76761                 }
76762             }
76763         }
76764         function getNonInterhitedProperties(type, baseTypes, properties) {
76765             if (!ts.length(baseTypes)) {
76766                 return properties;
76767             }
76768             var seen = new ts.Map();
76769             ts.forEach(properties, function (p) { seen.set(p.escapedName, p); });
76770             for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
76771                 var base = baseTypes_2[_i];
76772                 var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
76773                 for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) {
76774                     var prop = properties_4[_a];
76775                     var existing = seen.get(prop.escapedName);
76776                     if (existing && !isPropertyIdenticalTo(existing, prop)) {
76777                         seen.delete(prop.escapedName);
76778                     }
76779                 }
76780             }
76781             return ts.arrayFrom(seen.values());
76782         }
76783         function checkInheritedPropertiesAreIdentical(type, typeNode) {
76784             var baseTypes = getBaseTypes(type);
76785             if (baseTypes.length < 2) {
76786                 return true;
76787             }
76788             var seen = new ts.Map();
76789             ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); });
76790             var ok = true;
76791             for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) {
76792                 var base = baseTypes_3[_i];
76793                 var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
76794                 for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
76795                     var prop = properties_6[_a];
76796                     var existing = seen.get(prop.escapedName);
76797                     if (!existing) {
76798                         seen.set(prop.escapedName, { prop: prop, containingType: base });
76799                     }
76800                     else {
76801                         var isInheritedProperty = existing.containingType !== type;
76802                         if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
76803                             ok = false;
76804                             var typeName1 = typeToString(existing.containingType);
76805                             var typeName2 = typeToString(base);
76806                             var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
76807                             errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
76808                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));
76809                         }
76810                     }
76811                 }
76812             }
76813             return ok;
76814         }
76815         function checkPropertyInitialization(node) {
76816             if (!strictNullChecks || !strictPropertyInitialization || node.flags & 8388608 /* Ambient */) {
76817                 return;
76818             }
76819             var constructor = findConstructorDeclaration(node);
76820             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
76821                 var member = _a[_i];
76822                 if (ts.getEffectiveModifierFlags(member) & 2 /* Ambient */) {
76823                     continue;
76824                 }
76825                 if (isInstancePropertyWithoutInitializer(member)) {
76826                     var propName = member.name;
76827                     if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName)) {
76828                         var type = getTypeOfSymbol(getSymbolOfNode(member));
76829                         if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) {
76830                             if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
76831                                 error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName));
76832                             }
76833                         }
76834                     }
76835                 }
76836             }
76837         }
76838         function isInstancePropertyWithoutInitializer(node) {
76839             return node.kind === 163 /* PropertyDeclaration */ &&
76840                 !ts.hasSyntacticModifier(node, 32 /* Static */ | 128 /* Abstract */) &&
76841                 !node.exclamationToken &&
76842                 !node.initializer;
76843         }
76844         function isPropertyInitializedInConstructor(propName, propType, constructor) {
76845             var reference = ts.factory.createPropertyAccessExpression(ts.factory.createThis(), propName);
76846             ts.setParent(reference.expression, reference);
76847             ts.setParent(reference, constructor);
76848             reference.flowNode = constructor.returnFlowNode;
76849             var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
76850             return !(getFalsyFlags(flowType) & 32768 /* Undefined */);
76851         }
76852         function checkInterfaceDeclaration(node) {
76853             // Grammar checking
76854             if (!checkGrammarDecoratorsAndModifiers(node))
76855                 checkGrammarInterfaceDeclaration(node);
76856             checkTypeParameters(node.typeParameters);
76857             if (produceDiagnostics) {
76858                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0);
76859                 checkExportsOnMergedDeclarations(node);
76860                 var symbol = getSymbolOfNode(node);
76861                 checkTypeParameterListsIdentical(symbol);
76862                 // Only check this symbol once
76863                 var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */);
76864                 if (node === firstInterfaceDecl) {
76865                     var type = getDeclaredTypeOfSymbol(symbol);
76866                     var typeWithThis = getTypeWithThisArgument(type);
76867                     // run subsequent checks only if first set succeeded
76868                     if (checkInheritedPropertiesAreIdentical(type, node.name)) {
76869                         for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) {
76870                             var baseType = _a[_i];
76871                             checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1);
76872                         }
76873                         checkIndexConstraints(type);
76874                     }
76875                 }
76876                 checkObjectTypeForDuplicateDeclarations(node);
76877             }
76878             ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) {
76879                 if (!ts.isEntityNameExpression(heritageElement.expression) || ts.isOptionalChain(heritageElement.expression)) {
76880                     error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
76881                 }
76882                 checkTypeReferenceNode(heritageElement);
76883             });
76884             ts.forEach(node.members, checkSourceElement);
76885             if (produceDiagnostics) {
76886                 checkTypeForDuplicateIndexSignatures(node);
76887                 registerForUnusedIdentifiersCheck(node);
76888             }
76889         }
76890         function checkTypeAliasDeclaration(node) {
76891             // Grammar checking
76892             checkGrammarDecoratorsAndModifiers(node);
76893             checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
76894             checkExportsOnMergedDeclarations(node);
76895             checkTypeParameters(node.typeParameters);
76896             if (node.type.kind === 136 /* IntrinsicKeyword */) {
76897                 if (!intrinsicTypeKinds.has(node.name.escapedText) || ts.length(node.typeParameters) !== 1) {
76898                     error(node.type, ts.Diagnostics.The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types);
76899                 }
76900             }
76901             else {
76902                 checkSourceElement(node.type);
76903                 registerForUnusedIdentifiersCheck(node);
76904             }
76905         }
76906         function computeEnumMemberValues(node) {
76907             var nodeLinks = getNodeLinks(node);
76908             if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) {
76909                 nodeLinks.flags |= 16384 /* EnumValuesComputed */;
76910                 var autoValue = 0;
76911                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
76912                     var member = _a[_i];
76913                     var value = computeMemberValue(member, autoValue);
76914                     getNodeLinks(member).enumMemberValue = value;
76915                     autoValue = typeof value === "number" ? value + 1 : undefined;
76916                 }
76917             }
76918         }
76919         function computeMemberValue(member, autoValue) {
76920             if (ts.isComputedNonLiteralName(member.name)) {
76921                 error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
76922             }
76923             else {
76924                 var text = ts.getTextOfPropertyName(member.name);
76925                 if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
76926                     error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
76927                 }
76928             }
76929             if (member.initializer) {
76930                 return computeConstantValue(member);
76931             }
76932             // In ambient non-const numeric enum declarations, enum members without initializers are
76933             // considered computed members (as opposed to having auto-incremented values).
76934             if (member.parent.flags & 8388608 /* Ambient */ && !ts.isEnumConst(member.parent) && getEnumKind(getSymbolOfNode(member.parent)) === 0 /* Numeric */) {
76935                 return undefined;
76936             }
76937             // If the member declaration specifies no value, the member is considered a constant enum member.
76938             // If the member is the first member in the enum declaration, it is assigned the value zero.
76939             // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error
76940             // occurs if the immediately preceding member is not a constant enum member.
76941             if (autoValue !== undefined) {
76942                 return autoValue;
76943             }
76944             error(member.name, ts.Diagnostics.Enum_member_must_have_initializer);
76945             return undefined;
76946         }
76947         function computeConstantValue(member) {
76948             var enumKind = getEnumKind(getSymbolOfNode(member.parent));
76949             var isConstEnum = ts.isEnumConst(member.parent);
76950             var initializer = member.initializer;
76951             var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer);
76952             if (value !== undefined) {
76953                 if (isConstEnum && typeof value === "number" && !isFinite(value)) {
76954                     error(initializer, isNaN(value) ?
76955                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN :
76956                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
76957                 }
76958             }
76959             else if (enumKind === 1 /* Literal */) {
76960                 error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members);
76961                 return 0;
76962             }
76963             else if (isConstEnum) {
76964                 error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values);
76965             }
76966             else if (member.parent.flags & 8388608 /* Ambient */) {
76967                 error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
76968             }
76969             else {
76970                 // Only here do we need to check that the initializer is assignable to the enum type.
76971                 var source = checkExpression(initializer);
76972                 if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) {
76973                     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));
76974                 }
76975                 else {
76976                     checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined);
76977                 }
76978             }
76979             return value;
76980             function evaluate(expr) {
76981                 switch (expr.kind) {
76982                     case 214 /* PrefixUnaryExpression */:
76983                         var value_2 = evaluate(expr.operand);
76984                         if (typeof value_2 === "number") {
76985                             switch (expr.operator) {
76986                                 case 39 /* PlusToken */: return value_2;
76987                                 case 40 /* MinusToken */: return -value_2;
76988                                 case 54 /* TildeToken */: return ~value_2;
76989                             }
76990                         }
76991                         break;
76992                     case 216 /* BinaryExpression */:
76993                         var left = evaluate(expr.left);
76994                         var right = evaluate(expr.right);
76995                         if (typeof left === "number" && typeof right === "number") {
76996                             switch (expr.operatorToken.kind) {
76997                                 case 51 /* BarToken */: return left | right;
76998                                 case 50 /* AmpersandToken */: return left & right;
76999                                 case 48 /* GreaterThanGreaterThanToken */: return left >> right;
77000                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right;
77001                                 case 47 /* LessThanLessThanToken */: return left << right;
77002                                 case 52 /* CaretToken */: return left ^ right;
77003                                 case 41 /* AsteriskToken */: return left * right;
77004                                 case 43 /* SlashToken */: return left / right;
77005                                 case 39 /* PlusToken */: return left + right;
77006                                 case 40 /* MinusToken */: return left - right;
77007                                 case 44 /* PercentToken */: return left % right;
77008                                 case 42 /* AsteriskAsteriskToken */: return Math.pow(left, right);
77009                             }
77010                         }
77011                         else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 39 /* PlusToken */) {
77012                             return left + right;
77013                         }
77014                         break;
77015                     case 10 /* StringLiteral */:
77016                     case 14 /* NoSubstitutionTemplateLiteral */:
77017                         return expr.text;
77018                     case 8 /* NumericLiteral */:
77019                         checkGrammarNumericLiteral(expr);
77020                         return +expr.text;
77021                     case 207 /* ParenthesizedExpression */:
77022                         return evaluate(expr.expression);
77023                     case 78 /* Identifier */:
77024                         var identifier = expr;
77025                         if (isInfinityOrNaNString(identifier.escapedText)) {
77026                             return +(identifier.escapedText);
77027                         }
77028                         return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText);
77029                     case 202 /* ElementAccessExpression */:
77030                     case 201 /* PropertyAccessExpression */:
77031                         var ex = expr;
77032                         if (isConstantMemberAccess(ex)) {
77033                             var type = getTypeOfExpression(ex.expression);
77034                             if (type.symbol && type.symbol.flags & 384 /* Enum */) {
77035                                 var name = void 0;
77036                                 if (ex.kind === 201 /* PropertyAccessExpression */) {
77037                                     name = ex.name.escapedText;
77038                                 }
77039                                 else {
77040                                     name = ts.escapeLeadingUnderscores(ts.cast(ex.argumentExpression, ts.isLiteralExpression).text);
77041                                 }
77042                                 return evaluateEnumMember(expr, type.symbol, name);
77043                             }
77044                         }
77045                         break;
77046                 }
77047                 return undefined;
77048             }
77049             function evaluateEnumMember(expr, enumSymbol, name) {
77050                 var memberSymbol = enumSymbol.exports.get(name);
77051                 if (memberSymbol) {
77052                     var declaration = memberSymbol.valueDeclaration;
77053                     if (declaration !== member) {
77054                         if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) {
77055                             return getEnumMemberValue(declaration);
77056                         }
77057                         error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
77058                         return 0;
77059                     }
77060                     else {
77061                         error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol));
77062                     }
77063                 }
77064                 return undefined;
77065             }
77066         }
77067         function isConstantMemberAccess(node) {
77068             return node.kind === 78 /* Identifier */ ||
77069                 node.kind === 201 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) ||
77070                 node.kind === 202 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) &&
77071                     ts.isStringLiteralLike(node.argumentExpression);
77072         }
77073         function checkEnumDeclaration(node) {
77074             if (!produceDiagnostics) {
77075                 return;
77076             }
77077             // Grammar checking
77078             checkGrammarDecoratorsAndModifiers(node);
77079             checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0);
77080             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
77081             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
77082             checkExportsOnMergedDeclarations(node);
77083             node.members.forEach(checkEnumMember);
77084             computeEnumMemberValues(node);
77085             // Spec 2014 - Section 9.3:
77086             // It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
77087             // and when an enum type has multiple declarations, only one declaration is permitted to omit a value
77088             // for the first member.
77089             //
77090             // Only perform this check once per symbol
77091             var enumSymbol = getSymbolOfNode(node);
77092             var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
77093             if (node === firstDeclaration) {
77094                 if (enumSymbol.declarations.length > 1) {
77095                     var enumIsConst_1 = ts.isEnumConst(node);
77096                     // check that const is placed\omitted on all enum declarations
77097                     ts.forEach(enumSymbol.declarations, function (decl) {
77098                         if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
77099                             error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
77100                         }
77101                     });
77102                 }
77103                 var seenEnumMissingInitialInitializer_1 = false;
77104                 ts.forEach(enumSymbol.declarations, function (declaration) {
77105                     // return true if we hit a violation of the rule, false otherwise
77106                     if (declaration.kind !== 255 /* EnumDeclaration */) {
77107                         return false;
77108                     }
77109                     var enumDeclaration = declaration;
77110                     if (!enumDeclaration.members.length) {
77111                         return false;
77112                     }
77113                     var firstEnumMember = enumDeclaration.members[0];
77114                     if (!firstEnumMember.initializer) {
77115                         if (seenEnumMissingInitialInitializer_1) {
77116                             error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
77117                         }
77118                         else {
77119                             seenEnumMissingInitialInitializer_1 = true;
77120                         }
77121                     }
77122                 });
77123             }
77124         }
77125         function checkEnumMember(node) {
77126             if (ts.isPrivateIdentifier(node.name)) {
77127                 error(node, ts.Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier);
77128             }
77129         }
77130         function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
77131             var declarations = symbol.declarations;
77132             for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
77133                 var declaration = declarations_8[_i];
77134                 if ((declaration.kind === 252 /* ClassDeclaration */ ||
77135                     (declaration.kind === 251 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
77136                     !(declaration.flags & 8388608 /* Ambient */)) {
77137                     return declaration;
77138                 }
77139             }
77140             return undefined;
77141         }
77142         function inSameLexicalScope(node1, node2) {
77143             var container1 = ts.getEnclosingBlockScopeContainer(node1);
77144             var container2 = ts.getEnclosingBlockScopeContainer(node2);
77145             if (isGlobalSourceFile(container1)) {
77146                 return isGlobalSourceFile(container2);
77147             }
77148             else if (isGlobalSourceFile(container2)) {
77149                 return false;
77150             }
77151             else {
77152                 return container1 === container2;
77153             }
77154         }
77155         function checkModuleDeclaration(node) {
77156             if (produceDiagnostics) {
77157                 // Grammar checking
77158                 var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node);
77159                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
77160                 if (isGlobalAugmentation && !inAmbientContext) {
77161                     error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
77162                 }
77163                 var isAmbientExternalModule = ts.isAmbientModule(node);
77164                 var contextErrorMessage = isAmbientExternalModule
77165                     ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file
77166                     : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module;
77167                 if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
77168                     // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors.
77169                     return;
77170                 }
77171                 if (!checkGrammarDecoratorsAndModifiers(node)) {
77172                     if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) {
77173                         grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names);
77174                     }
77175                 }
77176                 if (ts.isIdentifier(node.name)) {
77177                     checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
77178                     checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
77179                 }
77180                 checkExportsOnMergedDeclarations(node);
77181                 var symbol = getSymbolOfNode(node);
77182                 // The following checks only apply on a non-ambient instantiated module declaration.
77183                 if (symbol.flags & 512 /* ValueModule */
77184                     && !inAmbientContext
77185                     && symbol.declarations.length > 1
77186                     && isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions))) {
77187                     var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
77188                     if (firstNonAmbientClassOrFunc) {
77189                         if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
77190                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
77191                         }
77192                         else if (node.pos < firstNonAmbientClassOrFunc.pos) {
77193                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
77194                         }
77195                     }
77196                     // if the module merges with a class declaration in the same lexical scope,
77197                     // we need to track this to ensure the correct emit.
77198                     var mergedClass = ts.getDeclarationOfKind(symbol, 252 /* ClassDeclaration */);
77199                     if (mergedClass &&
77200                         inSameLexicalScope(node, mergedClass)) {
77201                         getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */;
77202                     }
77203                 }
77204                 if (isAmbientExternalModule) {
77205                     if (ts.isExternalModuleAugmentation(node)) {
77206                         // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module)
77207                         // otherwise we'll be swamped in cascading errors.
77208                         // We can detect if augmentation was applied using following rules:
77209                         // - augmentation for a global scope is always applied
77210                         // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
77211                         var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
77212                         if (checkBody && node.body) {
77213                             for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
77214                                 var statement = _a[_i];
77215                                 checkModuleAugmentationElement(statement, isGlobalAugmentation);
77216                             }
77217                         }
77218                     }
77219                     else if (isGlobalSourceFile(node.parent)) {
77220                         if (isGlobalAugmentation) {
77221                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
77222                         }
77223                         else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) {
77224                             error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
77225                         }
77226                     }
77227                     else {
77228                         if (isGlobalAugmentation) {
77229                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
77230                         }
77231                         else {
77232                             // Node is not an augmentation and is not located on the script level.
77233                             // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited.
77234                             error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
77235                         }
77236                     }
77237                 }
77238             }
77239             if (node.body) {
77240                 checkSourceElement(node.body);
77241                 if (!ts.isGlobalScopeAugmentation(node)) {
77242                     registerForUnusedIdentifiersCheck(node);
77243                 }
77244             }
77245         }
77246         function checkModuleAugmentationElement(node, isGlobalAugmentation) {
77247             switch (node.kind) {
77248                 case 232 /* VariableStatement */:
77249                     // error each individual name in variable statement instead of marking the entire variable statement
77250                     for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
77251                         var decl = _a[_i];
77252                         checkModuleAugmentationElement(decl, isGlobalAugmentation);
77253                     }
77254                     break;
77255                 case 266 /* ExportAssignment */:
77256                 case 267 /* ExportDeclaration */:
77257                     grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
77258                     break;
77259                 case 260 /* ImportEqualsDeclaration */:
77260                 case 261 /* ImportDeclaration */:
77261                     grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
77262                     break;
77263                 case 198 /* BindingElement */:
77264                 case 249 /* VariableDeclaration */:
77265                     var name = node.name;
77266                     if (ts.isBindingPattern(name)) {
77267                         for (var _b = 0, _c = name.elements; _b < _c.length; _b++) {
77268                             var el = _c[_b];
77269                             // mark individual names in binding pattern
77270                             checkModuleAugmentationElement(el, isGlobalAugmentation);
77271                         }
77272                         break;
77273                     }
77274                 // falls through
77275                 case 252 /* ClassDeclaration */:
77276                 case 255 /* EnumDeclaration */:
77277                 case 251 /* FunctionDeclaration */:
77278                 case 253 /* InterfaceDeclaration */:
77279                 case 256 /* ModuleDeclaration */:
77280                 case 254 /* TypeAliasDeclaration */:
77281                     if (isGlobalAugmentation) {
77282                         return;
77283                     }
77284                     var symbol = getSymbolOfNode(node);
77285                     if (symbol) {
77286                         // module augmentations cannot introduce new names on the top level scope of the module
77287                         // this is done it two steps
77288                         // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
77289                         // 2. main check - report error if value declaration of the parent symbol is module augmentation)
77290                         var reportError = !(symbol.flags & 33554432 /* Transient */);
77291                         if (!reportError) {
77292                             // symbol should not originate in augmentation
77293                             reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]);
77294                         }
77295                     }
77296                     break;
77297             }
77298         }
77299         function getFirstNonModuleExportsIdentifier(node) {
77300             switch (node.kind) {
77301                 case 78 /* Identifier */:
77302                     return node;
77303                 case 157 /* QualifiedName */:
77304                     do {
77305                         node = node.left;
77306                     } while (node.kind !== 78 /* Identifier */);
77307                     return node;
77308                 case 201 /* PropertyAccessExpression */:
77309                     do {
77310                         if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) {
77311                             return node.name;
77312                         }
77313                         node = node.expression;
77314                     } while (node.kind !== 78 /* Identifier */);
77315                     return node;
77316             }
77317         }
77318         function checkExternalImportOrExportDeclaration(node) {
77319             var moduleName = ts.getExternalModuleName(node);
77320             if (!moduleName || ts.nodeIsMissing(moduleName)) {
77321                 // Should be a parse error.
77322                 return false;
77323             }
77324             if (!ts.isStringLiteral(moduleName)) {
77325                 error(moduleName, ts.Diagnostics.String_literal_expected);
77326                 return false;
77327             }
77328             var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
77329             if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule) {
77330                 error(moduleName, node.kind === 267 /* ExportDeclaration */ ?
77331                     ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
77332                     ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
77333                 return false;
77334             }
77335             if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
77336                 // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration
77337                 // no need to do this again.
77338                 if (!isTopLevelInExternalModuleAugmentation(node)) {
77339                     // TypeScript 1.0 spec (April 2013): 12.1.6
77340                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference
77341                     // other external modules only through top - level external module names.
77342                     // Relative external module names are not permitted.
77343                     error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
77344                     return false;
77345                 }
77346             }
77347             return true;
77348         }
77349         function checkAliasSymbol(node) {
77350             var _a;
77351             var symbol = getSymbolOfNode(node);
77352             var target = resolveAlias(symbol);
77353             if (target !== unknownSymbol) {
77354                 // For external modules, `symbol` represents the local symbol for an alias.
77355                 // This local symbol will merge any other local declarations (excluding other aliases)
77356                 // and symbol.flags will contains combined representation for all merged declaration.
77357                 // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have,
77358                 // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export*
77359                 // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names).
77360                 symbol = getMergedSymbol(symbol.exportSymbol || symbol);
77361                 var excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) |
77362                     (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) |
77363                     (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
77364                 if (target.flags & excludedMeanings) {
77365                     var message = node.kind === 270 /* ExportSpecifier */ ?
77366                         ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
77367                         ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
77368                     error(node, message, symbolToString(symbol));
77369                 }
77370                 // Don't allow to re-export something with no value side when `--isolatedModules` is set.
77371                 if (compilerOptions.isolatedModules
77372                     && node.kind === 270 /* ExportSpecifier */
77373                     && !node.parent.parent.isTypeOnly
77374                     && !(target.flags & 111551 /* Value */)
77375                     && !(node.flags & 8388608 /* Ambient */)) {
77376                     error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type);
77377                 }
77378                 if (ts.isImportSpecifier(node) && ((_a = target.declarations) === null || _a === void 0 ? void 0 : _a.every(function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); }))) {
77379                     addDeprecatedSuggestion(node.name, target.declarations, symbol.escapedName);
77380                 }
77381             }
77382         }
77383         function checkImportBinding(node) {
77384             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
77385             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
77386             checkAliasSymbol(node);
77387             if (node.kind === 265 /* ImportSpecifier */ &&
77388                 ts.idText(node.propertyName || node.name) === "default" &&
77389                 compilerOptions.esModuleInterop &&
77390                 moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
77391                 checkExternalEmitHelpers(node, 131072 /* ImportDefault */);
77392             }
77393         }
77394         function checkImportDeclaration(node) {
77395             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
77396                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
77397                 return;
77398             }
77399             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasEffectiveModifiers(node)) {
77400                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers);
77401             }
77402             if (checkExternalImportOrExportDeclaration(node)) {
77403                 var importClause = node.importClause;
77404                 if (importClause && !checkGrammarImportClause(importClause)) {
77405                     if (importClause.name) {
77406                         checkImportBinding(importClause);
77407                     }
77408                     if (importClause.namedBindings) {
77409                         if (importClause.namedBindings.kind === 263 /* NamespaceImport */) {
77410                             checkImportBinding(importClause.namedBindings);
77411                             if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015 && compilerOptions.esModuleInterop) {
77412                                 // import * as ns from "foo";
77413                                 checkExternalEmitHelpers(node, 65536 /* ImportStar */);
77414                             }
77415                         }
77416                         else {
77417                             var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier);
77418                             if (moduleExisted) {
77419                                 ts.forEach(importClause.namedBindings.elements, checkImportBinding);
77420                             }
77421                         }
77422                     }
77423                 }
77424             }
77425         }
77426         function checkImportEqualsDeclaration(node) {
77427             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
77428                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
77429                 return;
77430             }
77431             checkGrammarDecoratorsAndModifiers(node);
77432             if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
77433                 checkImportBinding(node);
77434                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
77435                     markExportAsReferenced(node);
77436                 }
77437                 if (node.moduleReference.kind !== 272 /* ExternalModuleReference */) {
77438                     var target = resolveAlias(getSymbolOfNode(node));
77439                     if (target !== unknownSymbol) {
77440                         if (target.flags & 111551 /* Value */) {
77441                             // Target is a value symbol, check that it is not hidden by a local declaration with the same name
77442                             var moduleName = ts.getFirstIdentifier(node.moduleReference);
77443                             if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
77444                                 error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName));
77445                             }
77446                         }
77447                         if (target.flags & 788968 /* Type */) {
77448                             checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
77449                         }
77450                     }
77451                     if (node.isTypeOnly) {
77452                         grammarErrorOnNode(node, ts.Diagnostics.An_import_alias_cannot_use_import_type);
77453                     }
77454                 }
77455                 else {
77456                     if (moduleKind >= ts.ModuleKind.ES2015 && !node.isTypeOnly && !(node.flags & 8388608 /* Ambient */)) {
77457                         // Import equals declaration is deprecated in es6 or above
77458                         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);
77459                     }
77460                 }
77461             }
77462         }
77463         function checkExportDeclaration(node) {
77464             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) {
77465                 // If we hit an export in an illegal context, just bail out to avoid cascading errors.
77466                 return;
77467             }
77468             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasEffectiveModifiers(node)) {
77469                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers);
77470             }
77471             if (node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause) && ts.length(node.exportClause.elements) && languageVersion === 0 /* ES3 */) {
77472                 checkExternalEmitHelpers(node, 2097152 /* CreateBinding */);
77473             }
77474             checkGrammarExportDeclaration(node);
77475             if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
77476                 if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) {
77477                     // export { x, y }
77478                     // export { x, y } from "foo"
77479                     ts.forEach(node.exportClause.elements, checkExportSpecifier);
77480                     var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
77481                     var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 257 /* ModuleBlock */ &&
77482                         !node.moduleSpecifier && node.flags & 8388608 /* Ambient */;
77483                     if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
77484                         error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
77485                     }
77486                 }
77487                 else {
77488                     // export * from "foo"
77489                     // export * as ns from "foo";
77490                     var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
77491                     if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
77492                         error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
77493                     }
77494                     else if (node.exportClause) {
77495                         checkAliasSymbol(node.exportClause);
77496                     }
77497                     if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
77498                         if (node.exportClause) {
77499                             // export * as ns from "foo";
77500                             // 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.
77501                             // We only use the helper here when in esModuleInterop
77502                             if (compilerOptions.esModuleInterop) {
77503                                 checkExternalEmitHelpers(node, 65536 /* ImportStar */);
77504                             }
77505                         }
77506                         else {
77507                             // export * from "foo"
77508                             checkExternalEmitHelpers(node, 32768 /* ExportStar */);
77509                         }
77510                     }
77511                 }
77512             }
77513         }
77514         function checkGrammarExportDeclaration(node) {
77515             var _a;
77516             var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 268 /* NamedExports */;
77517             if (isTypeOnlyExportStar) {
77518                 grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type);
77519             }
77520             return !isTypeOnlyExportStar;
77521         }
77522         function checkGrammarModuleElementContext(node, errorMessage) {
77523             var isInAppropriateContext = node.parent.kind === 297 /* SourceFile */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 256 /* ModuleDeclaration */;
77524             if (!isInAppropriateContext) {
77525                 grammarErrorOnFirstToken(node, errorMessage);
77526             }
77527             return !isInAppropriateContext;
77528         }
77529         function importClauseContainsReferencedImport(importClause) {
77530             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
77531                 return !!getSymbolOfNode(declaration).isReferenced;
77532             });
77533         }
77534         function importClauseContainsConstEnumUsedAsValue(importClause) {
77535             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
77536                 return !!getSymbolLinks(getSymbolOfNode(declaration)).constEnumReferenced;
77537             });
77538         }
77539         function canConvertImportDeclarationToTypeOnly(statement) {
77540             return ts.isImportDeclaration(statement) &&
77541                 statement.importClause &&
77542                 !statement.importClause.isTypeOnly &&
77543                 importClauseContainsReferencedImport(statement.importClause) &&
77544                 !isReferencedAliasDeclaration(statement.importClause, /*checkChildren*/ true) &&
77545                 !importClauseContainsConstEnumUsedAsValue(statement.importClause);
77546         }
77547         function canConvertImportEqualsDeclarationToTypeOnly(statement) {
77548             return ts.isImportEqualsDeclaration(statement) &&
77549                 ts.isExternalModuleReference(statement.moduleReference) &&
77550                 !statement.isTypeOnly &&
77551                 getSymbolOfNode(statement).isReferenced &&
77552                 !isReferencedAliasDeclaration(statement, /*checkChildren*/ false) &&
77553                 !getSymbolLinks(getSymbolOfNode(statement)).constEnumReferenced;
77554         }
77555         function checkImportsForTypeOnlyConversion(sourceFile) {
77556             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
77557                 var statement = _a[_i];
77558                 if (canConvertImportDeclarationToTypeOnly(statement) || canConvertImportEqualsDeclarationToTypeOnly(statement)) {
77559                     error(statement, ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_importsNotUsedAsValues_is_set_to_error);
77560                 }
77561             }
77562         }
77563         function checkExportSpecifier(node) {
77564             checkAliasSymbol(node);
77565             if (ts.getEmitDeclarations(compilerOptions)) {
77566                 collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
77567             }
77568             if (!node.parent.parent.moduleSpecifier) {
77569                 var exportedName = node.propertyName || node.name;
77570                 // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases)
77571                 var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, 
77572                 /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
77573                 if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
77574                     error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName));
77575                 }
77576                 else {
77577                     markExportAsReferenced(node);
77578                     var target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol);
77579                     if (!target || target === unknownSymbol || target.flags & 111551 /* Value */) {
77580                         checkExpressionCached(node.propertyName || node.name);
77581                     }
77582                 }
77583             }
77584             else {
77585                 if (compilerOptions.esModuleInterop &&
77586                     moduleKind !== ts.ModuleKind.System &&
77587                     moduleKind < ts.ModuleKind.ES2015 &&
77588                     ts.idText(node.propertyName || node.name) === "default") {
77589                     checkExternalEmitHelpers(node, 131072 /* ImportDefault */);
77590                 }
77591             }
77592         }
77593         function checkExportAssignment(node) {
77594             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) {
77595                 // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
77596                 return;
77597             }
77598             var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent;
77599             if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
77600                 if (node.isExportEquals) {
77601                     error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
77602                 }
77603                 else {
77604                     error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
77605                 }
77606                 return;
77607             }
77608             // Grammar checking
77609             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasEffectiveModifiers(node)) {
77610                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers);
77611             }
77612             if (node.expression.kind === 78 /* Identifier */) {
77613                 var id = node.expression;
77614                 var sym = resolveEntityName(id, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, node);
77615                 if (sym) {
77616                     markAliasReferenced(sym, id);
77617                     // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`)
77618                     var target = sym.flags & 2097152 /* Alias */ ? resolveAlias(sym) : sym;
77619                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
77620                         // However if it is a value, we need to check it's being used correctly
77621                         checkExpressionCached(node.expression);
77622                     }
77623                 }
77624                 else {
77625                     checkExpressionCached(node.expression); // doesn't resolve, check as expression to mark as error
77626                 }
77627                 if (ts.getEmitDeclarations(compilerOptions)) {
77628                     collectLinkedAliases(node.expression, /*setVisibility*/ true);
77629                 }
77630             }
77631             else {
77632                 checkExpressionCached(node.expression);
77633             }
77634             checkExternalModuleExports(container);
77635             if ((node.flags & 8388608 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) {
77636                 grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
77637             }
77638             if (node.isExportEquals && !(node.flags & 8388608 /* Ambient */)) {
77639                 if (moduleKind >= ts.ModuleKind.ES2015) {
77640                     // export assignment is not supported in es6 modules
77641                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
77642                 }
77643                 else if (moduleKind === ts.ModuleKind.System) {
77644                     // system modules does not support export assignment
77645                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
77646                 }
77647             }
77648         }
77649         function hasExportedMembers(moduleSymbol) {
77650             return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; });
77651         }
77652         function checkExternalModuleExports(node) {
77653             var moduleSymbol = getSymbolOfNode(node);
77654             var links = getSymbolLinks(moduleSymbol);
77655             if (!links.exportsChecked) {
77656                 var exportEqualsSymbol = moduleSymbol.exports.get("export=");
77657                 if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
77658                     var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
77659                     if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) {
77660                         error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
77661                     }
77662                 }
77663                 // Checks for export * conflicts
77664                 var exports_2 = getExportsOfModule(moduleSymbol);
77665                 if (exports_2) {
77666                     exports_2.forEach(function (_a, id) {
77667                         var declarations = _a.declarations, flags = _a.flags;
77668                         if (id === "__export") {
77669                             return;
77670                         }
77671                         // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
77672                         // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
77673                         if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) {
77674                             return;
77675                         }
77676                         var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor);
77677                         if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
77678                             // it is legal to merge type alias with other values
77679                             // so count should be either 1 (just type alias) or 2 (type alias + merged value)
77680                             return;
77681                         }
77682                         if (exportedDeclarationsCount > 1) {
77683                             for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
77684                                 var declaration = declarations_9[_i];
77685                                 if (isNotOverload(declaration)) {
77686                                     diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id)));
77687                                 }
77688                             }
77689                         }
77690                     });
77691                 }
77692                 links.exportsChecked = true;
77693             }
77694         }
77695         function checkSourceElement(node) {
77696             if (node) {
77697                 var saveCurrentNode = currentNode;
77698                 currentNode = node;
77699                 instantiationCount = 0;
77700                 checkSourceElementWorker(node);
77701                 currentNode = saveCurrentNode;
77702             }
77703         }
77704         function checkSourceElementWorker(node) {
77705             if (ts.isInJSFile(node)) {
77706                 ts.forEach(node.jsDoc, function (_a) {
77707                     var tags = _a.tags;
77708                     return ts.forEach(tags, checkSourceElement);
77709                 });
77710             }
77711             var kind = node.kind;
77712             if (cancellationToken) {
77713                 // Only bother checking on a few construct kinds.  We don't want to be excessively
77714                 // hitting the cancellation token on every node we check.
77715                 switch (kind) {
77716                     case 256 /* ModuleDeclaration */:
77717                     case 252 /* ClassDeclaration */:
77718                     case 253 /* InterfaceDeclaration */:
77719                     case 251 /* FunctionDeclaration */:
77720                         cancellationToken.throwIfCancellationRequested();
77721                 }
77722             }
77723             if (kind >= 232 /* FirstStatement */ && kind <= 248 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) {
77724                 errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected);
77725             }
77726             switch (kind) {
77727                 case 159 /* TypeParameter */:
77728                     return checkTypeParameter(node);
77729                 case 160 /* Parameter */:
77730                     return checkParameter(node);
77731                 case 163 /* PropertyDeclaration */:
77732                     return checkPropertyDeclaration(node);
77733                 case 162 /* PropertySignature */:
77734                     return checkPropertySignature(node);
77735                 case 175 /* ConstructorType */:
77736                 case 174 /* FunctionType */:
77737                 case 169 /* CallSignature */:
77738                 case 170 /* ConstructSignature */:
77739                 case 171 /* IndexSignature */:
77740                     return checkSignatureDeclaration(node);
77741                 case 165 /* MethodDeclaration */:
77742                 case 164 /* MethodSignature */:
77743                     return checkMethodDeclaration(node);
77744                 case 166 /* Constructor */:
77745                     return checkConstructorDeclaration(node);
77746                 case 167 /* GetAccessor */:
77747                 case 168 /* SetAccessor */:
77748                     return checkAccessorDeclaration(node);
77749                 case 173 /* TypeReference */:
77750                     return checkTypeReferenceNode(node);
77751                 case 172 /* TypePredicate */:
77752                     return checkTypePredicate(node);
77753                 case 176 /* TypeQuery */:
77754                     return checkTypeQuery(node);
77755                 case 177 /* TypeLiteral */:
77756                     return checkTypeLiteral(node);
77757                 case 178 /* ArrayType */:
77758                     return checkArrayType(node);
77759                 case 179 /* TupleType */:
77760                     return checkTupleType(node);
77761                 case 182 /* UnionType */:
77762                 case 183 /* IntersectionType */:
77763                     return checkUnionOrIntersectionType(node);
77764                 case 186 /* ParenthesizedType */:
77765                 case 180 /* OptionalType */:
77766                 case 181 /* RestType */:
77767                     return checkSourceElement(node.type);
77768                 case 187 /* ThisType */:
77769                     return checkThisType(node);
77770                 case 188 /* TypeOperator */:
77771                     return checkTypeOperator(node);
77772                 case 184 /* ConditionalType */:
77773                     return checkConditionalType(node);
77774                 case 185 /* InferType */:
77775                     return checkInferType(node);
77776                 case 193 /* TemplateLiteralType */:
77777                     return checkTemplateLiteralType(node);
77778                 case 195 /* ImportType */:
77779                     return checkImportType(node);
77780                 case 192 /* NamedTupleMember */:
77781                     return checkNamedTupleMember(node);
77782                 case 315 /* JSDocAugmentsTag */:
77783                     return checkJSDocAugmentsTag(node);
77784                 case 316 /* JSDocImplementsTag */:
77785                     return checkJSDocImplementsTag(node);
77786                 case 331 /* JSDocTypedefTag */:
77787                 case 324 /* JSDocCallbackTag */:
77788                 case 325 /* JSDocEnumTag */:
77789                     return checkJSDocTypeAliasTag(node);
77790                 case 330 /* JSDocTemplateTag */:
77791                     return checkJSDocTemplateTag(node);
77792                 case 329 /* JSDocTypeTag */:
77793                     return checkJSDocTypeTag(node);
77794                 case 326 /* JSDocParameterTag */:
77795                     return checkJSDocParameterTag(node);
77796                 case 333 /* JSDocPropertyTag */:
77797                     return checkJSDocPropertyTag(node);
77798                 case 308 /* JSDocFunctionType */:
77799                     checkJSDocFunctionType(node);
77800                 // falls through
77801                 case 306 /* JSDocNonNullableType */:
77802                 case 305 /* JSDocNullableType */:
77803                 case 303 /* JSDocAllType */:
77804                 case 304 /* JSDocUnknownType */:
77805                 case 312 /* JSDocTypeLiteral */:
77806                     checkJSDocTypeIsInJsFile(node);
77807                     ts.forEachChild(node, checkSourceElement);
77808                     return;
77809                 case 309 /* JSDocVariadicType */:
77810                     checkJSDocVariadicType(node);
77811                     return;
77812                 case 301 /* JSDocTypeExpression */:
77813                     return checkSourceElement(node.type);
77814                 case 189 /* IndexedAccessType */:
77815                     return checkIndexedAccessType(node);
77816                 case 190 /* MappedType */:
77817                     return checkMappedType(node);
77818                 case 251 /* FunctionDeclaration */:
77819                     return checkFunctionDeclaration(node);
77820                 case 230 /* Block */:
77821                 case 257 /* ModuleBlock */:
77822                     return checkBlock(node);
77823                 case 232 /* VariableStatement */:
77824                     return checkVariableStatement(node);
77825                 case 233 /* ExpressionStatement */:
77826                     return checkExpressionStatement(node);
77827                 case 234 /* IfStatement */:
77828                     return checkIfStatement(node);
77829                 case 235 /* DoStatement */:
77830                     return checkDoStatement(node);
77831                 case 236 /* WhileStatement */:
77832                     return checkWhileStatement(node);
77833                 case 237 /* ForStatement */:
77834                     return checkForStatement(node);
77835                 case 238 /* ForInStatement */:
77836                     return checkForInStatement(node);
77837                 case 239 /* ForOfStatement */:
77838                     return checkForOfStatement(node);
77839                 case 240 /* ContinueStatement */:
77840                 case 241 /* BreakStatement */:
77841                     return checkBreakOrContinueStatement(node);
77842                 case 242 /* ReturnStatement */:
77843                     return checkReturnStatement(node);
77844                 case 243 /* WithStatement */:
77845                     return checkWithStatement(node);
77846                 case 244 /* SwitchStatement */:
77847                     return checkSwitchStatement(node);
77848                 case 245 /* LabeledStatement */:
77849                     return checkLabeledStatement(node);
77850                 case 246 /* ThrowStatement */:
77851                     return checkThrowStatement(node);
77852                 case 247 /* TryStatement */:
77853                     return checkTryStatement(node);
77854                 case 249 /* VariableDeclaration */:
77855                     return checkVariableDeclaration(node);
77856                 case 198 /* BindingElement */:
77857                     return checkBindingElement(node);
77858                 case 252 /* ClassDeclaration */:
77859                     return checkClassDeclaration(node);
77860                 case 253 /* InterfaceDeclaration */:
77861                     return checkInterfaceDeclaration(node);
77862                 case 254 /* TypeAliasDeclaration */:
77863                     return checkTypeAliasDeclaration(node);
77864                 case 255 /* EnumDeclaration */:
77865                     return checkEnumDeclaration(node);
77866                 case 256 /* ModuleDeclaration */:
77867                     return checkModuleDeclaration(node);
77868                 case 261 /* ImportDeclaration */:
77869                     return checkImportDeclaration(node);
77870                 case 260 /* ImportEqualsDeclaration */:
77871                     return checkImportEqualsDeclaration(node);
77872                 case 267 /* ExportDeclaration */:
77873                     return checkExportDeclaration(node);
77874                 case 266 /* ExportAssignment */:
77875                     return checkExportAssignment(node);
77876                 case 231 /* EmptyStatement */:
77877                 case 248 /* DebuggerStatement */:
77878                     checkGrammarStatementInAmbientContext(node);
77879                     return;
77880                 case 271 /* MissingDeclaration */:
77881                     return checkMissingDeclaration(node);
77882             }
77883         }
77884         function checkJSDocTypeIsInJsFile(node) {
77885             if (!ts.isInJSFile(node)) {
77886                 grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
77887             }
77888         }
77889         function checkJSDocVariadicType(node) {
77890             checkJSDocTypeIsInJsFile(node);
77891             checkSourceElement(node.type);
77892             // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function.
77893             var parent = node.parent;
77894             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
77895                 if (ts.last(parent.parent.parameters) !== parent) {
77896                     error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
77897                 }
77898                 return;
77899             }
77900             if (!ts.isJSDocTypeExpression(parent)) {
77901                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
77902             }
77903             var paramTag = node.parent.parent;
77904             if (!ts.isJSDocParameterTag(paramTag)) {
77905                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
77906                 return;
77907             }
77908             var param = ts.getParameterSymbolFromJSDoc(paramTag);
77909             if (!param) {
77910                 // We will error in `checkJSDocParameterTag`.
77911                 return;
77912             }
77913             var host = ts.getHostSignatureFromJSDoc(paramTag);
77914             if (!host || ts.last(host.parameters).symbol !== param) {
77915                 error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
77916             }
77917         }
77918         function getTypeFromJSDocVariadicType(node) {
77919             var type = getTypeFromTypeNode(node.type);
77920             var parent = node.parent;
77921             var paramTag = node.parent.parent;
77922             if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) {
77923                 // Else we will add a diagnostic, see `checkJSDocVariadicType`.
77924                 var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
77925                 if (host_1) {
77926                     /*
77927                     Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
77928                     So in the following situation we will not create an array type:
77929                         /** @param {...number} a * /
77930                         function f(a) {}
77931                     Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
77932                     */
77933                     var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters);
77934                     var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
77935                     if (!lastParamDeclaration ||
77936                         symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
77937                         return createArrayType(type);
77938                     }
77939                 }
77940             }
77941             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
77942                 return createArrayType(type);
77943             }
77944             return addOptionality(type);
77945         }
77946         // Function and class expression bodies are checked after all statements in the enclosing body. This is
77947         // to ensure constructs like the following are permitted:
77948         //     const foo = function () {
77949         //        const s = foo();
77950         //        return "hello";
77951         //     }
77952         // Here, performing a full type check of the body of the function expression whilst in the process of
77953         // determining the type of foo would cause foo to be given type any because of the recursive reference.
77954         // Delaying the type check of the body ensures foo has been assigned a type.
77955         function checkNodeDeferred(node) {
77956             var enclosingFile = ts.getSourceFileOfNode(node);
77957             var links = getNodeLinks(enclosingFile);
77958             if (!(links.flags & 1 /* TypeChecked */)) {
77959                 links.deferredNodes = links.deferredNodes || new ts.Map();
77960                 var id = getNodeId(node);
77961                 links.deferredNodes.set(id, node);
77962             }
77963         }
77964         function checkDeferredNodes(context) {
77965             var links = getNodeLinks(context);
77966             if (links.deferredNodes) {
77967                 links.deferredNodes.forEach(checkDeferredNode);
77968             }
77969         }
77970         function checkDeferredNode(node) {
77971             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end });
77972             var saveCurrentNode = currentNode;
77973             currentNode = node;
77974             instantiationCount = 0;
77975             switch (node.kind) {
77976                 case 203 /* CallExpression */:
77977                 case 204 /* NewExpression */:
77978                 case 205 /* TaggedTemplateExpression */:
77979                 case 161 /* Decorator */:
77980                 case 275 /* JsxOpeningElement */:
77981                     // These node kinds are deferred checked when overload resolution fails
77982                     // To save on work, we ensure the arguments are checked just once, in
77983                     // a deferred way
77984                     resolveUntypedCall(node);
77985                     break;
77986                 case 208 /* FunctionExpression */:
77987                 case 209 /* ArrowFunction */:
77988                 case 165 /* MethodDeclaration */:
77989                 case 164 /* MethodSignature */:
77990                     checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
77991                     break;
77992                 case 167 /* GetAccessor */:
77993                 case 168 /* SetAccessor */:
77994                     checkAccessorDeclaration(node);
77995                     break;
77996                 case 221 /* ClassExpression */:
77997                     checkClassExpressionDeferred(node);
77998                     break;
77999                 case 274 /* JsxSelfClosingElement */:
78000                     checkJsxSelfClosingElementDeferred(node);
78001                     break;
78002                 case 273 /* JsxElement */:
78003                     checkJsxElementDeferred(node);
78004                     break;
78005             }
78006             currentNode = saveCurrentNode;
78007             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
78008         }
78009         function checkSourceFile(node) {
78010             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true);
78011             ts.performance.mark("beforeCheck");
78012             checkSourceFileWorker(node);
78013             ts.performance.mark("afterCheck");
78014             ts.performance.measure("Check", "beforeCheck", "afterCheck");
78015             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
78016         }
78017         function unusedIsError(kind, isAmbient) {
78018             if (isAmbient) {
78019                 return false;
78020             }
78021             switch (kind) {
78022                 case 0 /* Local */:
78023                     return !!compilerOptions.noUnusedLocals;
78024                 case 1 /* Parameter */:
78025                     return !!compilerOptions.noUnusedParameters;
78026                 default:
78027                     return ts.Debug.assertNever(kind);
78028             }
78029         }
78030         function getPotentiallyUnusedIdentifiers(sourceFile) {
78031             return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
78032         }
78033         // Fully type check a source file and collect the relevant diagnostics.
78034         function checkSourceFileWorker(node) {
78035             var links = getNodeLinks(node);
78036             if (!(links.flags & 1 /* TypeChecked */)) {
78037                 if (ts.skipTypeChecking(node, compilerOptions, host)) {
78038                     return;
78039                 }
78040                 // Grammar checking
78041                 checkGrammarSourceFile(node);
78042                 ts.clear(potentialThisCollisions);
78043                 ts.clear(potentialNewTargetCollisions);
78044                 ts.clear(potentialWeakMapCollisions);
78045                 ts.forEach(node.statements, checkSourceElement);
78046                 checkSourceElement(node.endOfFileToken);
78047                 checkDeferredNodes(node);
78048                 if (ts.isExternalOrCommonJsModule(node)) {
78049                     registerForUnusedIdentifiersCheck(node);
78050                 }
78051                 if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
78052                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) {
78053                         if (!ts.containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
78054                             diagnostics.add(diag);
78055                         }
78056                     });
78057                 }
78058                 if (compilerOptions.importsNotUsedAsValues === 2 /* Error */ &&
78059                     !node.isDeclarationFile &&
78060                     ts.isExternalModule(node)) {
78061                     checkImportsForTypeOnlyConversion(node);
78062                 }
78063                 if (ts.isExternalOrCommonJsModule(node)) {
78064                     checkExternalModuleExports(node);
78065                 }
78066                 if (potentialThisCollisions.length) {
78067                     ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
78068                     ts.clear(potentialThisCollisions);
78069                 }
78070                 if (potentialNewTargetCollisions.length) {
78071                     ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
78072                     ts.clear(potentialNewTargetCollisions);
78073                 }
78074                 if (potentialWeakMapCollisions.length) {
78075                     ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision);
78076                     ts.clear(potentialWeakMapCollisions);
78077                 }
78078                 links.flags |= 1 /* TypeChecked */;
78079             }
78080         }
78081         function getDiagnostics(sourceFile, ct) {
78082             try {
78083                 // Record the cancellation token so it can be checked later on during checkSourceElement.
78084                 // Do this in a finally block so we can ensure that it gets reset back to nothing after
78085                 // this call is done.
78086                 cancellationToken = ct;
78087                 return getDiagnosticsWorker(sourceFile);
78088             }
78089             finally {
78090                 cancellationToken = undefined;
78091             }
78092         }
78093         function getDiagnosticsWorker(sourceFile) {
78094             throwIfNonDiagnosticsProducing();
78095             if (sourceFile) {
78096                 // Some global diagnostics are deferred until they are needed and
78097                 // may not be reported in the first call to getGlobalDiagnostics.
78098                 // We should catch these changes and report them.
78099                 var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
78100                 var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
78101                 checkSourceFile(sourceFile);
78102                 var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
78103                 var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
78104                 if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
78105                     // If the arrays are not the same reference, new diagnostics were added.
78106                     var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics);
78107                     return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
78108                 }
78109                 else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
78110                     // If the arrays are the same reference, but the length has changed, a single
78111                     // new diagnostic was added as DiagnosticCollection attempts to reuse the
78112                     // same array.
78113                     return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics);
78114                 }
78115                 return semanticDiagnostics;
78116             }
78117             // Global diagnostics are always added when a file is not provided to
78118             // getDiagnostics
78119             ts.forEach(host.getSourceFiles(), checkSourceFile);
78120             return diagnostics.getDiagnostics();
78121         }
78122         function getGlobalDiagnostics() {
78123             throwIfNonDiagnosticsProducing();
78124             return diagnostics.getGlobalDiagnostics();
78125         }
78126         function throwIfNonDiagnosticsProducing() {
78127             if (!produceDiagnostics) {
78128                 throw new Error("Trying to get diagnostics from a type checker that does not produce them.");
78129             }
78130         }
78131         // Language service support
78132         function getSymbolsInScope(location, meaning) {
78133             if (location.flags & 16777216 /* InWithStatement */) {
78134                 // We cannot answer semantic questions within a with block, do not proceed any further
78135                 return [];
78136             }
78137             var symbols = ts.createSymbolTable();
78138             var isStatic = false;
78139             populateSymbols();
78140             symbols.delete("this" /* This */); // Not a symbol, a keyword
78141             return symbolsToArray(symbols);
78142             function populateSymbols() {
78143                 while (location) {
78144                     if (location.locals && !isGlobalSourceFile(location)) {
78145                         copySymbols(location.locals, meaning);
78146                     }
78147                     switch (location.kind) {
78148                         case 297 /* SourceFile */:
78149                             if (!ts.isExternalOrCommonJsModule(location))
78150                                 break;
78151                         // falls through
78152                         case 256 /* ModuleDeclaration */:
78153                             copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */);
78154                             break;
78155                         case 255 /* EnumDeclaration */:
78156                             copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */);
78157                             break;
78158                         case 221 /* ClassExpression */:
78159                             var className = location.name;
78160                             if (className) {
78161                                 copySymbol(location.symbol, meaning);
78162                             }
78163                         // this fall-through is necessary because we would like to handle
78164                         // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration.
78165                         // falls through
78166                         case 252 /* ClassDeclaration */:
78167                         case 253 /* InterfaceDeclaration */:
78168                             // If we didn't come from static member of class or interface,
78169                             // add the type parameters into the symbol table
78170                             // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
78171                             // Note: that the memberFlags come from previous iteration.
78172                             if (!isStatic) {
78173                                 copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */);
78174                             }
78175                             break;
78176                         case 208 /* FunctionExpression */:
78177                             var funcName = location.name;
78178                             if (funcName) {
78179                                 copySymbol(location.symbol, meaning);
78180                             }
78181                             break;
78182                     }
78183                     if (ts.introducesArgumentsExoticObject(location)) {
78184                         copySymbol(argumentsSymbol, meaning);
78185                     }
78186                     isStatic = ts.hasSyntacticModifier(location, 32 /* Static */);
78187                     location = location.parent;
78188                 }
78189                 copySymbols(globals, meaning);
78190             }
78191             /**
78192              * Copy the given symbol into symbol tables if the symbol has the given meaning
78193              * and it doesn't already existed in the symbol table
78194              * @param key a key for storing in symbol table; if undefined, use symbol.name
78195              * @param symbol the symbol to be added into symbol table
78196              * @param meaning meaning of symbol to filter by before adding to symbol table
78197              */
78198             function copySymbol(symbol, meaning) {
78199                 if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) {
78200                     var id = symbol.escapedName;
78201                     // We will copy all symbol regardless of its reserved name because
78202                     // symbolsToArray will check whether the key is a reserved name and
78203                     // it will not copy symbol with reserved name to the array
78204                     if (!symbols.has(id)) {
78205                         symbols.set(id, symbol);
78206                     }
78207                 }
78208             }
78209             function copySymbols(source, meaning) {
78210                 if (meaning) {
78211                     source.forEach(function (symbol) {
78212                         copySymbol(symbol, meaning);
78213                     });
78214                 }
78215             }
78216         }
78217         function isTypeDeclarationName(name) {
78218             return name.kind === 78 /* Identifier */ &&
78219                 isTypeDeclaration(name.parent) &&
78220                 ts.getNameOfDeclaration(name.parent) === name;
78221         }
78222         function isTypeDeclaration(node) {
78223             switch (node.kind) {
78224                 case 159 /* TypeParameter */:
78225                 case 252 /* ClassDeclaration */:
78226                 case 253 /* InterfaceDeclaration */:
78227                 case 254 /* TypeAliasDeclaration */:
78228                 case 255 /* EnumDeclaration */:
78229                 case 331 /* JSDocTypedefTag */:
78230                 case 324 /* JSDocCallbackTag */:
78231                 case 325 /* JSDocEnumTag */:
78232                     return true;
78233                 case 262 /* ImportClause */:
78234                     return node.isTypeOnly;
78235                 case 265 /* ImportSpecifier */:
78236                 case 270 /* ExportSpecifier */:
78237                     return node.parent.parent.isTypeOnly;
78238                 default:
78239                     return false;
78240             }
78241         }
78242         // True if the given identifier is part of a type reference
78243         function isTypeReferenceIdentifier(node) {
78244             while (node.parent.kind === 157 /* QualifiedName */) {
78245                 node = node.parent;
78246             }
78247             return node.parent.kind === 173 /* TypeReference */;
78248         }
78249         function isHeritageClauseElementIdentifier(node) {
78250             while (node.parent.kind === 201 /* PropertyAccessExpression */) {
78251                 node = node.parent;
78252             }
78253             return node.parent.kind === 223 /* ExpressionWithTypeArguments */;
78254         }
78255         function isJSDocEntryNameReference(node) {
78256             while (node.parent.kind === 157 /* QualifiedName */) {
78257                 node = node.parent;
78258             }
78259             while (node.parent.kind === 201 /* PropertyAccessExpression */) {
78260                 node = node.parent;
78261             }
78262             return node.parent.kind === 302 /* JSDocNameReference */;
78263         }
78264         function forEachEnclosingClass(node, callback) {
78265             var result;
78266             while (true) {
78267                 node = ts.getContainingClass(node);
78268                 if (!node)
78269                     break;
78270                 if (result = callback(node))
78271                     break;
78272             }
78273             return result;
78274         }
78275         function isNodeUsedDuringClassInitialization(node) {
78276             return !!ts.findAncestor(node, function (element) {
78277                 if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) {
78278                     return true;
78279                 }
78280                 else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) {
78281                     return "quit";
78282                 }
78283                 return false;
78284             });
78285         }
78286         function isNodeWithinClass(node, classDeclaration) {
78287             return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; });
78288         }
78289         function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
78290             while (nodeOnRightSide.parent.kind === 157 /* QualifiedName */) {
78291                 nodeOnRightSide = nodeOnRightSide.parent;
78292             }
78293             if (nodeOnRightSide.parent.kind === 260 /* ImportEqualsDeclaration */) {
78294                 return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
78295             }
78296             if (nodeOnRightSide.parent.kind === 266 /* ExportAssignment */) {
78297                 return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
78298             }
78299             return undefined;
78300         }
78301         function isInRightSideOfImportOrExportAssignment(node) {
78302             return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined;
78303         }
78304         function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
78305             var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent);
78306             switch (specialPropertyAssignmentKind) {
78307                 case 1 /* ExportsProperty */:
78308                 case 3 /* PrototypeProperty */:
78309                     return getSymbolOfNode(entityName.parent);
78310                 case 4 /* ThisProperty */:
78311                 case 2 /* ModuleExports */:
78312                 case 5 /* Property */:
78313                     return getSymbolOfNode(entityName.parent.parent);
78314             }
78315         }
78316         function isImportTypeQualifierPart(node) {
78317             var parent = node.parent;
78318             while (ts.isQualifiedName(parent)) {
78319                 node = parent;
78320                 parent = parent.parent;
78321             }
78322             if (parent && parent.kind === 195 /* ImportType */ && parent.qualifier === node) {
78323                 return parent;
78324             }
78325             return undefined;
78326         }
78327         function getSymbolOfNameOrPropertyAccessExpression(name) {
78328             if (ts.isDeclarationName(name)) {
78329                 return getSymbolOfNode(name.parent);
78330             }
78331             if (ts.isInJSFile(name) &&
78332                 name.parent.kind === 201 /* PropertyAccessExpression */ &&
78333                 name.parent === name.parent.parent.left) {
78334                 // Check if this is a special property assignment
78335                 if (!ts.isPrivateIdentifier(name)) {
78336                     var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name);
78337                     if (specialPropertyAssignmentSymbol) {
78338                         return specialPropertyAssignmentSymbol;
78339                     }
78340                 }
78341             }
78342             if (name.parent.kind === 266 /* ExportAssignment */ && ts.isEntityNameExpression(name)) {
78343                 // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression
78344                 var success = resolveEntityName(name, 
78345                 /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
78346                 if (success && success !== unknownSymbol) {
78347                     return success;
78348                 }
78349             }
78350             else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) {
78351                 // Since we already checked for ExportAssignment, this really could only be an Import
78352                 var importEqualsDeclaration = ts.getAncestor(name, 260 /* ImportEqualsDeclaration */);
78353                 ts.Debug.assert(importEqualsDeclaration !== undefined);
78354                 return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true);
78355             }
78356             if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name)) {
78357                 var possibleImportNode = isImportTypeQualifierPart(name);
78358                 if (possibleImportNode) {
78359                     getTypeFromTypeNode(possibleImportNode);
78360                     var sym = getNodeLinks(name).resolvedSymbol;
78361                     return sym === unknownSymbol ? undefined : sym;
78362                 }
78363             }
78364             while (ts.isRightSideOfQualifiedNameOrPropertyAccess(name)) {
78365                 name = name.parent;
78366             }
78367             if (isHeritageClauseElementIdentifier(name)) {
78368                 var meaning = 0 /* None */;
78369                 // In an interface or class, we're definitely interested in a type.
78370                 if (name.parent.kind === 223 /* ExpressionWithTypeArguments */) {
78371                     meaning = 788968 /* Type */;
78372                     // In a class 'extends' clause we are also looking for a value.
78373                     if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) {
78374                         meaning |= 111551 /* Value */;
78375                     }
78376                 }
78377                 else {
78378                     meaning = 1920 /* Namespace */;
78379                 }
78380                 meaning |= 2097152 /* Alias */;
78381                 var entityNameSymbol = ts.isEntityNameExpression(name) ? resolveEntityName(name, meaning) : undefined;
78382                 if (entityNameSymbol) {
78383                     return entityNameSymbol;
78384                 }
78385             }
78386             if (name.parent.kind === 326 /* JSDocParameterTag */) {
78387                 return ts.getParameterSymbolFromJSDoc(name.parent);
78388             }
78389             if (name.parent.kind === 159 /* TypeParameter */ && name.parent.parent.kind === 330 /* JSDocTemplateTag */) {
78390                 ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true.
78391                 var typeParameter = ts.getTypeParameterFromJsDoc(name.parent);
78392                 return typeParameter && typeParameter.symbol;
78393             }
78394             if (ts.isExpressionNode(name)) {
78395                 if (ts.nodeIsMissing(name)) {
78396                     // Missing entity name.
78397                     return undefined;
78398                 }
78399                 if (name.kind === 78 /* Identifier */) {
78400                     if (ts.isJSXTagName(name) && isJsxIntrinsicIdentifier(name)) {
78401                         var symbol = getIntrinsicTagSymbol(name.parent);
78402                         return symbol === unknownSymbol ? undefined : symbol;
78403                     }
78404                     return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
78405                 }
78406                 else if (name.kind === 201 /* PropertyAccessExpression */ || name.kind === 157 /* QualifiedName */) {
78407                     var links = getNodeLinks(name);
78408                     if (links.resolvedSymbol) {
78409                         return links.resolvedSymbol;
78410                     }
78411                     if (name.kind === 201 /* PropertyAccessExpression */) {
78412                         checkPropertyAccessExpression(name);
78413                     }
78414                     else {
78415                         checkQualifiedName(name);
78416                     }
78417                     return links.resolvedSymbol;
78418                 }
78419             }
78420             else if (isTypeReferenceIdentifier(name)) {
78421                 var meaning = name.parent.kind === 173 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */;
78422                 return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
78423             }
78424             else if (isJSDocEntryNameReference(name)) {
78425                 var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */;
78426                 return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name));
78427             }
78428             if (name.parent.kind === 172 /* TypePredicate */) {
78429                 return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */);
78430             }
78431             // Do we want to return undefined here?
78432             return undefined;
78433         }
78434         function getSymbolAtLocation(node, ignoreErrors) {
78435             if (node.kind === 297 /* SourceFile */) {
78436                 return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
78437             }
78438             var parent = node.parent;
78439             var grandParent = parent.parent;
78440             if (node.flags & 16777216 /* InWithStatement */) {
78441                 // We cannot answer semantic questions within a with block, do not proceed any further
78442                 return undefined;
78443             }
78444             if (isDeclarationNameOrImportPropertyName(node)) {
78445                 // This is a declaration, call getSymbolOfNode
78446                 var parentSymbol = getSymbolOfNode(parent);
78447                 return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
78448                     ? getImmediateAliasedSymbol(parentSymbol)
78449                     : parentSymbol;
78450             }
78451             else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
78452                 return getSymbolOfNode(parent.parent);
78453             }
78454             if (node.kind === 78 /* Identifier */) {
78455                 if (isInRightSideOfImportOrExportAssignment(node)) {
78456                     return getSymbolOfNameOrPropertyAccessExpression(node);
78457                 }
78458                 else if (parent.kind === 198 /* BindingElement */ &&
78459                     grandParent.kind === 196 /* ObjectBindingPattern */ &&
78460                     node === parent.propertyName) {
78461                     var typeOfPattern = getTypeOfNode(grandParent);
78462                     var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
78463                     if (propertyDeclaration) {
78464                         return propertyDeclaration;
78465                     }
78466                 }
78467             }
78468             switch (node.kind) {
78469                 case 78 /* Identifier */:
78470                 case 79 /* PrivateIdentifier */:
78471                 case 201 /* PropertyAccessExpression */:
78472                 case 157 /* QualifiedName */:
78473                     return getSymbolOfNameOrPropertyAccessExpression(node);
78474                 case 107 /* ThisKeyword */:
78475                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
78476                     if (ts.isFunctionLike(container)) {
78477                         var sig = getSignatureFromDeclaration(container);
78478                         if (sig.thisParameter) {
78479                             return sig.thisParameter;
78480                         }
78481                     }
78482                     if (ts.isInExpressionContext(node)) {
78483                         return checkExpression(node).symbol;
78484                     }
78485                 // falls through
78486                 case 187 /* ThisType */:
78487                     return getTypeFromThisTypeNode(node).symbol;
78488                 case 105 /* SuperKeyword */:
78489                     return checkExpression(node).symbol;
78490                 case 132 /* ConstructorKeyword */:
78491                     // constructor keyword for an overload, should take us to the definition if it exist
78492                     var constructorDeclaration = node.parent;
78493                     if (constructorDeclaration && constructorDeclaration.kind === 166 /* Constructor */) {
78494                         return constructorDeclaration.parent.symbol;
78495                     }
78496                     return undefined;
78497                 case 10 /* StringLiteral */:
78498                 case 14 /* NoSubstitutionTemplateLiteral */:
78499                     // 1). import x = require("./mo/*gotToDefinitionHere*/d")
78500                     // 2). External module name in an import declaration
78501                     // 3). Dynamic import call or require in javascript
78502                     // 4). type A = import("./f/*gotToDefinitionHere*/oo")
78503                     if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
78504                         ((node.parent.kind === 261 /* ImportDeclaration */ || node.parent.kind === 267 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) ||
78505                         ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) ||
78506                         (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) {
78507                         return resolveExternalModuleName(node, node, ignoreErrors);
78508                     }
78509                     if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
78510                         return getSymbolOfNode(parent);
78511                     }
78512                 // falls through
78513                 case 8 /* NumericLiteral */:
78514                     // index access
78515                     var objectType = ts.isElementAccessExpression(parent)
78516                         ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined
78517                         : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent)
78518                             ? getTypeFromTypeNode(grandParent.objectType)
78519                             : undefined;
78520                     return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text));
78521                 case 87 /* DefaultKeyword */:
78522                 case 97 /* FunctionKeyword */:
78523                 case 38 /* EqualsGreaterThanToken */:
78524                 case 83 /* ClassKeyword */:
78525                     return getSymbolOfNode(node.parent);
78526                 case 195 /* ImportType */:
78527                     return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined;
78528                 case 92 /* ExportKeyword */:
78529                     return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined;
78530                 default:
78531                     return undefined;
78532             }
78533         }
78534         function getShorthandAssignmentValueSymbol(location) {
78535             if (location && location.kind === 289 /* ShorthandPropertyAssignment */) {
78536                 return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */);
78537             }
78538             return undefined;
78539         }
78540         /** Returns the target of an export specifier without following aliases */
78541         function getExportSpecifierLocalTargetSymbol(node) {
78542             if (ts.isExportSpecifier(node)) {
78543                 return node.parent.parent.moduleSpecifier ?
78544                     getExternalModuleMember(node.parent.parent, node) :
78545                     resolveEntityName(node.propertyName || node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
78546             }
78547             else {
78548                 return resolveEntityName(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
78549             }
78550         }
78551         function getTypeOfNode(node) {
78552             if (ts.isSourceFile(node) && !ts.isExternalModule(node)) {
78553                 return errorType;
78554             }
78555             if (node.flags & 16777216 /* InWithStatement */) {
78556                 // We cannot answer semantic questions within a with block, do not proceed any further
78557                 return errorType;
78558             }
78559             var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
78560             var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class));
78561             if (ts.isPartOfTypeNode(node)) {
78562                 var typeFromTypeNode = getTypeFromTypeNode(node);
78563                 return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
78564             }
78565             if (ts.isExpressionNode(node)) {
78566                 return getRegularTypeOfExpression(node);
78567             }
78568             if (classType && !classDecl.isImplements) {
78569                 // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
78570                 // extends clause of a class. We handle that case here.
78571                 var baseType = ts.firstOrUndefined(getBaseTypes(classType));
78572                 return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
78573             }
78574             if (isTypeDeclaration(node)) {
78575                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
78576                 var symbol = getSymbolOfNode(node);
78577                 return getDeclaredTypeOfSymbol(symbol);
78578             }
78579             if (isTypeDeclarationName(node)) {
78580                 var symbol = getSymbolAtLocation(node);
78581                 return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
78582             }
78583             if (ts.isDeclaration(node)) {
78584                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
78585                 var symbol = getSymbolOfNode(node);
78586                 return getTypeOfSymbol(symbol);
78587             }
78588             if (isDeclarationNameOrImportPropertyName(node)) {
78589                 var symbol = getSymbolAtLocation(node);
78590                 if (symbol) {
78591                     return getTypeOfSymbol(symbol);
78592                 }
78593                 return errorType;
78594             }
78595             if (ts.isBindingPattern(node)) {
78596                 return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType;
78597             }
78598             if (isInRightSideOfImportOrExportAssignment(node)) {
78599                 var symbol = getSymbolAtLocation(node);
78600                 if (symbol) {
78601                     var declaredType = getDeclaredTypeOfSymbol(symbol);
78602                     return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol);
78603                 }
78604             }
78605             return errorType;
78606         }
78607         // Gets the type of object literal or array literal of destructuring assignment.
78608         // { a } from
78609         //     for ( { a } of elems) {
78610         //     }
78611         // [ a ] from
78612         //     [a] = [ some array ...]
78613         function getTypeOfAssignmentPattern(expr) {
78614             ts.Debug.assert(expr.kind === 200 /* ObjectLiteralExpression */ || expr.kind === 199 /* ArrayLiteralExpression */);
78615             // If this is from "for of"
78616             //     for ( { a } of elems) {
78617             //     }
78618             if (expr.parent.kind === 239 /* ForOfStatement */) {
78619                 var iteratedType = checkRightHandSideOfForOf(expr.parent);
78620                 return checkDestructuringAssignment(expr, iteratedType || errorType);
78621             }
78622             // If this is from "for" initializer
78623             //     for ({a } = elems[0];.....) { }
78624             if (expr.parent.kind === 216 /* BinaryExpression */) {
78625                 var iteratedType = getTypeOfExpression(expr.parent.right);
78626                 return checkDestructuringAssignment(expr, iteratedType || errorType);
78627             }
78628             // If this is from nested object binding pattern
78629             //     for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
78630             if (expr.parent.kind === 288 /* PropertyAssignment */) {
78631                 var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression);
78632                 var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType;
78633                 var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent);
78634                 return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex);
78635             }
78636             // Array literal assignment - array destructuring pattern
78637             var node = ts.cast(expr.parent, ts.isArrayLiteralExpression);
78638             //    [{ property1: p1, property2 }] = elems;
78639             var typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
78640             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType;
78641             return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
78642         }
78643         // Gets the property symbol corresponding to the property in destructuring assignment
78644         // 'property1' from
78645         //     for ( { property1: a } of elems) {
78646         //     }
78647         // 'property1' at location 'a' from:
78648         //     [a] = [ property1, property2 ]
78649         function getPropertySymbolOfDestructuringAssignment(location) {
78650             // Get the type of the object or array literal and then look for property of given name in the type
78651             var typeOfObjectLiteral = getTypeOfAssignmentPattern(ts.cast(location.parent.parent, ts.isAssignmentPattern));
78652             return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
78653         }
78654         function getRegularTypeOfExpression(expr) {
78655             if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
78656                 expr = expr.parent;
78657             }
78658             return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
78659         }
78660         /**
78661          * Gets either the static or instance type of a class element, based on
78662          * whether the element is declared as "static".
78663          */
78664         function getParentTypeOfClassElement(node) {
78665             var classSymbol = getSymbolOfNode(node.parent);
78666             return ts.hasSyntacticModifier(node, 32 /* Static */)
78667                 ? getTypeOfSymbol(classSymbol)
78668                 : getDeclaredTypeOfSymbol(classSymbol);
78669         }
78670         function getClassElementPropertyKeyType(element) {
78671             var name = element.name;
78672             switch (name.kind) {
78673                 case 78 /* Identifier */:
78674                     return getLiteralType(ts.idText(name));
78675                 case 8 /* NumericLiteral */:
78676                 case 10 /* StringLiteral */:
78677                     return getLiteralType(name.text);
78678                 case 158 /* ComputedPropertyName */:
78679                     var nameType = checkComputedPropertyName(name);
78680                     return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType;
78681                 default:
78682                     return ts.Debug.fail("Unsupported property name.");
78683             }
78684         }
78685         // Return the list of properties of the given type, augmented with properties from Function
78686         // if the type has call or construct signatures
78687         function getAugmentedPropertiesOfType(type) {
78688             type = getApparentType(type);
78689             var propsByName = ts.createSymbolTable(getPropertiesOfType(type));
78690             var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType :
78691                 getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType :
78692                     undefined;
78693             if (functionType) {
78694                 ts.forEach(getPropertiesOfType(functionType), function (p) {
78695                     if (!propsByName.has(p.escapedName)) {
78696                         propsByName.set(p.escapedName, p);
78697                     }
78698                 });
78699             }
78700             return getNamedMembers(propsByName);
78701         }
78702         function typeHasCallOrConstructSignatures(type) {
78703             return ts.typeHasCallOrConstructSignatures(type, checker);
78704         }
78705         function getRootSymbols(symbol) {
78706             var roots = getImmediateRootSymbols(symbol);
78707             return roots ? ts.flatMap(roots, getRootSymbols) : [symbol];
78708         }
78709         function getImmediateRootSymbols(symbol) {
78710             if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) {
78711                 return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); });
78712             }
78713             else if (symbol.flags & 33554432 /* Transient */) {
78714                 var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin;
78715                 return leftSpread ? [leftSpread, rightSpread]
78716                     : syntheticOrigin ? [syntheticOrigin]
78717                         : ts.singleElementArray(tryGetAliasTarget(symbol));
78718             }
78719             return undefined;
78720         }
78721         function tryGetAliasTarget(symbol) {
78722             var target;
78723             var next = symbol;
78724             while (next = getSymbolLinks(next).target) {
78725                 target = next;
78726             }
78727             return target;
78728         }
78729         // Emitter support
78730         function isArgumentsLocalBinding(nodeIn) {
78731             // Note: does not handle isShorthandPropertyAssignment (and probably a few more)
78732             if (ts.isGeneratedIdentifier(nodeIn))
78733                 return false;
78734             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
78735             if (!node)
78736                 return false;
78737             var parent = node.parent;
78738             if (!parent)
78739                 return false;
78740             var isPropertyName = ((ts.isPropertyAccessExpression(parent)
78741                 || ts.isPropertyAssignment(parent))
78742                 && parent.name === node);
78743             return !isPropertyName && getReferencedValueSymbol(node) === argumentsSymbol;
78744         }
78745         function moduleExportsSomeValue(moduleReferenceExpression) {
78746             var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression);
78747             if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
78748                 // If the module is not found or is shorthand, assume that it may export a value.
78749                 return true;
78750             }
78751             var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol);
78752             // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment
78753             // otherwise it will return moduleSymbol itself
78754             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
78755             var symbolLinks = getSymbolLinks(moduleSymbol);
78756             if (symbolLinks.exportsSomeValue === undefined) {
78757                 // for export assignments - check if resolved symbol for RHS is itself a value
78758                 // otherwise - check if at least one export is value
78759                 symbolLinks.exportsSomeValue = hasExportAssignment
78760                     ? !!(moduleSymbol.flags & 111551 /* Value */)
78761                     : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
78762             }
78763             return symbolLinks.exportsSomeValue;
78764             function isValue(s) {
78765                 s = resolveSymbol(s);
78766                 return s && !!(s.flags & 111551 /* Value */);
78767             }
78768         }
78769         function isNameOfModuleOrEnumDeclaration(node) {
78770             return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
78771         }
78772         // When resolved as an expression identifier, if the given node references an exported entity, return the declaration
78773         // node of the exported entity's container. Otherwise, return undefined.
78774         function getReferencedExportContainer(nodeIn, prefixLocals) {
78775             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
78776             if (node) {
78777                 // When resolving the export container for the name of a module or enum
78778                 // declaration, we need to start resolution at the declaration's container.
78779                 // Otherwise, we could incorrectly resolve the export container as the
78780                 // declaration if it contains an exported member with the same name.
78781                 var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node));
78782                 if (symbol) {
78783                     if (symbol.flags & 1048576 /* ExportValue */) {
78784                         // If we reference an exported entity within the same module declaration, then whether
78785                         // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the
78786                         // kinds that we do NOT prefix.
78787                         var exportSymbol = getMergedSymbol(symbol.exportSymbol);
78788                         if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
78789                             return undefined;
78790                         }
78791                         symbol = exportSymbol;
78792                     }
78793                     var parentSymbol_1 = getParentOfSymbol(symbol);
78794                     if (parentSymbol_1) {
78795                         if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 297 /* SourceFile */) {
78796                             var symbolFile = parentSymbol_1.valueDeclaration;
78797                             var referenceFile = ts.getSourceFileOfNode(node);
78798                             // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
78799                             var symbolIsUmdExport = symbolFile !== referenceFile;
78800                             return symbolIsUmdExport ? undefined : symbolFile;
78801                         }
78802                         return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; });
78803                     }
78804                 }
78805             }
78806         }
78807         // When resolved as an expression identifier, if the given node references an import, return the declaration of
78808         // that import. Otherwise, return undefined.
78809         function getReferencedImportDeclaration(nodeIn) {
78810             if (nodeIn.generatedImportReference) {
78811                 return nodeIn.generatedImportReference;
78812             }
78813             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
78814             if (node) {
78815                 var symbol = getReferencedValueSymbol(node);
78816                 // We should only get the declaration of an alias if there isn't a local value
78817                 // declaration for the symbol
78818                 if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !getTypeOnlyAliasDeclaration(symbol)) {
78819                     return getDeclarationOfAliasSymbol(symbol);
78820                 }
78821             }
78822             return undefined;
78823         }
78824         function isSymbolOfDestructuredElementOfCatchBinding(symbol) {
78825             return ts.isBindingElement(symbol.valueDeclaration)
78826                 && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 287 /* CatchClause */;
78827         }
78828         function isSymbolOfDeclarationWithCollidingName(symbol) {
78829             if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
78830                 var links = getSymbolLinks(symbol);
78831                 if (links.isDeclarationWithCollidingName === undefined) {
78832                     var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
78833                     if (ts.isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
78834                         var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration);
78835                         if (resolveName(container.parent, symbol.escapedName, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
78836                             // redeclaration - always should be renamed
78837                             links.isDeclarationWithCollidingName = true;
78838                         }
78839                         else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) {
78840                             // binding is captured in the function
78841                             // should be renamed if:
78842                             // - binding is not top level - top level bindings never collide with anything
78843                             // AND
78844                             //   - binding is not declared in loop, should be renamed to avoid name reuse across siblings
78845                             //     let a, b
78846                             //     { let x = 1; a = () => x; }
78847                             //     { let x = 100; b = () => x; }
78848                             //     console.log(a()); // should print '1'
78849                             //     console.log(b()); // should print '100'
78850                             //     OR
78851                             //   - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body
78852                             //     * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly
78853                             //     * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus
78854                             //       they will not collide with anything
78855                             var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */;
78856                             var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false);
78857                             var inLoopBodyBlock = container.kind === 230 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
78858                             links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock));
78859                         }
78860                         else {
78861                             links.isDeclarationWithCollidingName = false;
78862                         }
78863                     }
78864                 }
78865                 return links.isDeclarationWithCollidingName;
78866             }
78867             return false;
78868         }
78869         // When resolved as an expression identifier, if the given node references a nested block scoped entity with
78870         // a name that either hides an existing name or might hide it when compiled downlevel,
78871         // return the declaration of that entity. Otherwise, return undefined.
78872         function getReferencedDeclarationWithCollidingName(nodeIn) {
78873             if (!ts.isGeneratedIdentifier(nodeIn)) {
78874                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
78875                 if (node) {
78876                     var symbol = getReferencedValueSymbol(node);
78877                     if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
78878                         return symbol.valueDeclaration;
78879                     }
78880                 }
78881             }
78882             return undefined;
78883         }
78884         // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an
78885         // existing name or might hide a name when compiled downlevel
78886         function isDeclarationWithCollidingName(nodeIn) {
78887             var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
78888             if (node) {
78889                 var symbol = getSymbolOfNode(node);
78890                 if (symbol) {
78891                     return isSymbolOfDeclarationWithCollidingName(symbol);
78892                 }
78893             }
78894             return false;
78895         }
78896         function isValueAliasDeclaration(node) {
78897             switch (node.kind) {
78898                 case 260 /* ImportEqualsDeclaration */:
78899                     return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol);
78900                 case 262 /* ImportClause */:
78901                 case 263 /* NamespaceImport */:
78902                 case 265 /* ImportSpecifier */:
78903                 case 270 /* ExportSpecifier */:
78904                     var symbol = getSymbolOfNode(node) || unknownSymbol;
78905                     return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol);
78906                 case 267 /* ExportDeclaration */:
78907                     var exportClause = node.exportClause;
78908                     return !!exportClause && (ts.isNamespaceExport(exportClause) ||
78909                         ts.some(exportClause.elements, isValueAliasDeclaration));
78910                 case 266 /* ExportAssignment */:
78911                     return node.expression && node.expression.kind === 78 /* Identifier */ ?
78912                         isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) :
78913                         true;
78914             }
78915             return false;
78916         }
78917         function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
78918             var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
78919             if (node === undefined || node.parent.kind !== 297 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
78920                 // parent is not source file or it is not reference to internal module
78921                 return false;
78922             }
78923             var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
78924             return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference);
78925         }
78926         function isAliasResolvedToValue(symbol) {
78927             var target = resolveAlias(symbol);
78928             if (target === unknownSymbol) {
78929                 return true;
78930             }
78931             // const enums and modules that contain only const enums are not considered values from the emit perspective
78932             // unless 'preserveConstEnums' option is set to true
78933             return !!(target.flags & 111551 /* Value */) &&
78934                 (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target));
78935         }
78936         function isConstEnumOrConstEnumOnlyModule(s) {
78937             return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
78938         }
78939         function isReferencedAliasDeclaration(node, checkChildren) {
78940             if (isAliasSymbolDeclaration(node)) {
78941                 var symbol = getSymbolOfNode(node);
78942                 var links = symbol && getSymbolLinks(symbol);
78943                 if (links === null || links === void 0 ? void 0 : links.referenced) {
78944                     return true;
78945                 }
78946                 var target = getSymbolLinks(symbol).target; // TODO: GH#18217
78947                 if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ &&
78948                     target.flags & 111551 /* Value */ &&
78949                     (ts.shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) {
78950                     // An `export import ... =` of a value symbol is always considered referenced
78951                     return true;
78952                 }
78953             }
78954             if (checkChildren) {
78955                 return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); });
78956             }
78957             return false;
78958         }
78959         function isImplementationOfOverload(node) {
78960             if (ts.nodeIsPresent(node.body)) {
78961                 if (ts.isGetAccessor(node) || ts.isSetAccessor(node))
78962                     return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures
78963                 var symbol = getSymbolOfNode(node);
78964                 var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
78965                 // If this function body corresponds to function with multiple signature, it is implementation of overload
78966                 // e.g.: function foo(a: string): string;
78967                 //       function foo(a: number): number;
78968                 //       function foo(a: any) { // This is implementation of the overloads
78969                 //           return a;
78970                 //       }
78971                 return signaturesOfSymbol.length > 1 ||
78972                     // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
78973                     // e.g.: function foo(a: string): string;
78974                     //       function foo(a: any) { // This is implementation of the overloads
78975                     //           return a;
78976                     //       }
78977                     (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node);
78978             }
78979             return false;
78980         }
78981         function isRequiredInitializedParameter(parameter) {
78982             return !!strictNullChecks &&
78983                 !isOptionalParameter(parameter) &&
78984                 !ts.isJSDocParameterTag(parameter) &&
78985                 !!parameter.initializer &&
78986                 !ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */);
78987         }
78988         function isOptionalUninitializedParameterProperty(parameter) {
78989             return strictNullChecks &&
78990                 isOptionalParameter(parameter) &&
78991                 !parameter.initializer &&
78992                 ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */);
78993         }
78994         function isOptionalUninitializedParameter(parameter) {
78995             return !!strictNullChecks &&
78996                 isOptionalParameter(parameter) &&
78997                 !parameter.initializer;
78998         }
78999         function isExpandoFunctionDeclaration(node) {
79000             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
79001             if (!declaration) {
79002                 return false;
79003             }
79004             var symbol = getSymbolOfNode(declaration);
79005             if (!symbol || !(symbol.flags & 16 /* Function */)) {
79006                 return false;
79007             }
79008             return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 111551 /* Value */ && p.valueDeclaration && ts.isPropertyAccessExpression(p.valueDeclaration); });
79009         }
79010         function getPropertiesOfContainerFunction(node) {
79011             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
79012             if (!declaration) {
79013                 return ts.emptyArray;
79014             }
79015             var symbol = getSymbolOfNode(declaration);
79016             return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray;
79017         }
79018         function getNodeCheckFlags(node) {
79019             return getNodeLinks(node).flags || 0;
79020         }
79021         function getEnumMemberValue(node) {
79022             computeEnumMemberValues(node.parent);
79023             return getNodeLinks(node).enumMemberValue;
79024         }
79025         function canHaveConstantValue(node) {
79026             switch (node.kind) {
79027                 case 291 /* EnumMember */:
79028                 case 201 /* PropertyAccessExpression */:
79029                 case 202 /* ElementAccessExpression */:
79030                     return true;
79031             }
79032             return false;
79033         }
79034         function getConstantValue(node) {
79035             if (node.kind === 291 /* EnumMember */) {
79036                 return getEnumMemberValue(node);
79037             }
79038             var symbol = getNodeLinks(node).resolvedSymbol;
79039             if (symbol && (symbol.flags & 8 /* EnumMember */)) {
79040                 // inline property\index accesses only for const enums
79041                 var member = symbol.valueDeclaration;
79042                 if (ts.isEnumConst(member.parent)) {
79043                     return getEnumMemberValue(member);
79044                 }
79045             }
79046             return undefined;
79047         }
79048         function isFunctionType(type) {
79049             return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
79050         }
79051         function getTypeReferenceSerializationKind(typeNameIn, location) {
79052             var _a;
79053             // ensure both `typeName` and `location` are parse tree nodes.
79054             var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName);
79055             if (!typeName)
79056                 return ts.TypeReferenceSerializationKind.Unknown;
79057             if (location) {
79058                 location = ts.getParseTreeNode(location);
79059                 if (!location)
79060                     return ts.TypeReferenceSerializationKind.Unknown;
79061             }
79062             // Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
79063             var valueSymbol = resolveEntityName(typeName, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, location);
79064             var isTypeOnly = ((_a = valueSymbol === null || valueSymbol === void 0 ? void 0 : valueSymbol.declarations) === null || _a === void 0 ? void 0 : _a.every(ts.isTypeOnlyImportOrExportDeclaration)) || false;
79065             var resolvedSymbol = valueSymbol && valueSymbol.flags & 2097152 /* Alias */ ? resolveAlias(valueSymbol) : valueSymbol;
79066             // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
79067             var typeSymbol = resolveEntityName(typeName, 788968 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
79068             if (resolvedSymbol && resolvedSymbol === typeSymbol) {
79069                 var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
79070                 if (globalPromiseSymbol && resolvedSymbol === globalPromiseSymbol) {
79071                     return ts.TypeReferenceSerializationKind.Promise;
79072                 }
79073                 var constructorType = getTypeOfSymbol(resolvedSymbol);
79074                 if (constructorType && isConstructorType(constructorType)) {
79075                     return isTypeOnly ? ts.TypeReferenceSerializationKind.TypeWithCallSignature : ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
79076                 }
79077             }
79078             // We might not be able to resolve type symbol so use unknown type in that case (eg error case)
79079             if (!typeSymbol) {
79080                 return isTypeOnly ? ts.TypeReferenceSerializationKind.ObjectType : ts.TypeReferenceSerializationKind.Unknown;
79081             }
79082             var type = getDeclaredTypeOfSymbol(typeSymbol);
79083             if (type === errorType) {
79084                 return isTypeOnly ? ts.TypeReferenceSerializationKind.ObjectType : ts.TypeReferenceSerializationKind.Unknown;
79085             }
79086             else if (type.flags & 3 /* AnyOrUnknown */) {
79087                 return ts.TypeReferenceSerializationKind.ObjectType;
79088             }
79089             else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) {
79090                 return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType;
79091             }
79092             else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) {
79093                 return ts.TypeReferenceSerializationKind.BooleanType;
79094             }
79095             else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) {
79096                 return ts.TypeReferenceSerializationKind.NumberLikeType;
79097             }
79098             else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) {
79099                 return ts.TypeReferenceSerializationKind.BigIntLikeType;
79100             }
79101             else if (isTypeAssignableToKind(type, 402653316 /* StringLike */)) {
79102                 return ts.TypeReferenceSerializationKind.StringLikeType;
79103             }
79104             else if (isTupleType(type)) {
79105                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
79106             }
79107             else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) {
79108                 return ts.TypeReferenceSerializationKind.ESSymbolType;
79109             }
79110             else if (isFunctionType(type)) {
79111                 return ts.TypeReferenceSerializationKind.TypeWithCallSignature;
79112             }
79113             else if (isArrayType(type)) {
79114                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
79115             }
79116             else {
79117                 return ts.TypeReferenceSerializationKind.ObjectType;
79118             }
79119         }
79120         function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) {
79121             var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor);
79122             if (!declaration) {
79123                 return ts.factory.createToken(128 /* AnyKeyword */);
79124             }
79125             // Get type of the symbol if this is the valid symbol otherwise get type at location
79126             var symbol = getSymbolOfNode(declaration);
79127             var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */))
79128                 ? getWidenedLiteralType(getTypeOfSymbol(symbol))
79129                 : errorType;
79130             if (type.flags & 8192 /* UniqueESSymbol */ &&
79131                 type.symbol === symbol) {
79132                 flags |= 1048576 /* AllowUniqueESSymbolType */;
79133             }
79134             if (addUndefined) {
79135                 type = getOptionalType(type);
79136             }
79137             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
79138         }
79139         function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) {
79140             var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike);
79141             if (!signatureDeclaration) {
79142                 return ts.factory.createToken(128 /* AnyKeyword */);
79143             }
79144             var signature = getSignatureFromDeclaration(signatureDeclaration);
79145             return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
79146         }
79147         function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) {
79148             var expr = ts.getParseTreeNode(exprIn, ts.isExpression);
79149             if (!expr) {
79150                 return ts.factory.createToken(128 /* AnyKeyword */);
79151             }
79152             var type = getWidenedType(getRegularTypeOfExpression(expr));
79153             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
79154         }
79155         function hasGlobalName(name) {
79156             return globals.has(ts.escapeLeadingUnderscores(name));
79157         }
79158         function getReferencedValueSymbol(reference, startInDeclarationContainer) {
79159             var resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
79160             if (resolvedSymbol) {
79161                 return resolvedSymbol;
79162             }
79163             var location = reference;
79164             if (startInDeclarationContainer) {
79165                 // When resolving the name of a declaration as a value, we need to start resolution
79166                 // at a point outside of the declaration.
79167                 var parent = reference.parent;
79168                 if (ts.isDeclaration(parent) && reference === parent.name) {
79169                     location = getDeclarationContainer(parent);
79170                 }
79171             }
79172             return resolveName(location, reference.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
79173         }
79174         function getReferencedValueDeclaration(referenceIn) {
79175             if (!ts.isGeneratedIdentifier(referenceIn)) {
79176                 var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier);
79177                 if (reference) {
79178                     var symbol = getReferencedValueSymbol(reference);
79179                     if (symbol) {
79180                         return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
79181                     }
79182                 }
79183             }
79184             return undefined;
79185         }
79186         function isLiteralConstDeclaration(node) {
79187             if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
79188                 return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node)));
79189             }
79190             return false;
79191         }
79192         function literalTypeToNode(type, enclosing, tracker) {
79193             var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 111551 /* Value */, enclosing, /*flags*/ undefined, tracker)
79194                 : type === trueType ? ts.factory.createTrue() : type === falseType && ts.factory.createFalse();
79195             if (enumResult)
79196                 return enumResult;
79197             var literalValue = type.value;
79198             return typeof literalValue === "object" ? ts.factory.createBigIntLiteral(literalValue) :
79199                 typeof literalValue === "number" ? ts.factory.createNumericLiteral(literalValue) :
79200                     ts.factory.createStringLiteral(literalValue);
79201         }
79202         function createLiteralConstValue(node, tracker) {
79203             var type = getTypeOfSymbol(getSymbolOfNode(node));
79204             return literalTypeToNode(type, node, tracker);
79205         }
79206         function getJsxFactoryEntity(location) {
79207             return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity;
79208         }
79209         function getJsxFragmentFactoryEntity(location) {
79210             if (location) {
79211                 var file = ts.getSourceFileOfNode(location);
79212                 if (file) {
79213                     if (file.localJsxFragmentFactory) {
79214                         return file.localJsxFragmentFactory;
79215                     }
79216                     var jsxFragPragmas = file.pragmas.get("jsxfrag");
79217                     var jsxFragPragma = ts.isArray(jsxFragPragmas) ? jsxFragPragmas[0] : jsxFragPragmas;
79218                     if (jsxFragPragma) {
79219                         file.localJsxFragmentFactory = ts.parseIsolatedEntityName(jsxFragPragma.arguments.factory, languageVersion);
79220                         return file.localJsxFragmentFactory;
79221                     }
79222                 }
79223             }
79224             if (compilerOptions.jsxFragmentFactory) {
79225                 return ts.parseIsolatedEntityName(compilerOptions.jsxFragmentFactory, languageVersion);
79226             }
79227         }
79228         function createResolver() {
79229             // this variable and functions that use it are deliberately moved here from the outer scope
79230             // to avoid scope pollution
79231             var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives();
79232             var fileToDirective;
79233             if (resolvedTypeReferenceDirectives) {
79234                 // populate reverse mapping: file path -> type reference directive that was resolved to this file
79235                 fileToDirective = new ts.Map();
79236                 resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
79237                     if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
79238                         return;
79239                     }
79240                     var file = host.getSourceFile(resolvedDirective.resolvedFileName);
79241                     if (file) {
79242                         // Add the transitive closure of path references loaded by this file (as long as they are not)
79243                         // part of an existing type reference.
79244                         addReferencedFilesToTypeDirective(file, key);
79245                     }
79246                 });
79247             }
79248             return {
79249                 getReferencedExportContainer: getReferencedExportContainer,
79250                 getReferencedImportDeclaration: getReferencedImportDeclaration,
79251                 getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName,
79252                 isDeclarationWithCollidingName: isDeclarationWithCollidingName,
79253                 isValueAliasDeclaration: function (nodeIn) {
79254                     var node = ts.getParseTreeNode(nodeIn);
79255                     // Synthesized nodes are always treated like values.
79256                     return node ? isValueAliasDeclaration(node) : true;
79257                 },
79258                 hasGlobalName: hasGlobalName,
79259                 isReferencedAliasDeclaration: function (nodeIn, checkChildren) {
79260                     var node = ts.getParseTreeNode(nodeIn);
79261                     // Synthesized nodes are always treated as referenced.
79262                     return node ? isReferencedAliasDeclaration(node, checkChildren) : true;
79263                 },
79264                 getNodeCheckFlags: function (nodeIn) {
79265                     var node = ts.getParseTreeNode(nodeIn);
79266                     return node ? getNodeCheckFlags(node) : 0;
79267                 },
79268                 isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName,
79269                 isDeclarationVisible: isDeclarationVisible,
79270                 isImplementationOfOverload: isImplementationOfOverload,
79271                 isRequiredInitializedParameter: isRequiredInitializedParameter,
79272                 isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty,
79273                 isExpandoFunctionDeclaration: isExpandoFunctionDeclaration,
79274                 getPropertiesOfContainerFunction: getPropertiesOfContainerFunction,
79275                 createTypeOfDeclaration: createTypeOfDeclaration,
79276                 createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration,
79277                 createTypeOfExpression: createTypeOfExpression,
79278                 createLiteralConstValue: createLiteralConstValue,
79279                 isSymbolAccessible: isSymbolAccessible,
79280                 isEntityNameVisible: isEntityNameVisible,
79281                 getConstantValue: function (nodeIn) {
79282                     var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
79283                     return node ? getConstantValue(node) : undefined;
79284                 },
79285                 collectLinkedAliases: collectLinkedAliases,
79286                 getReferencedValueDeclaration: getReferencedValueDeclaration,
79287                 getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
79288                 isOptionalParameter: isOptionalParameter,
79289                 moduleExportsSomeValue: moduleExportsSomeValue,
79290                 isArgumentsLocalBinding: isArgumentsLocalBinding,
79291                 getExternalModuleFileFromDeclaration: function (nodeIn) {
79292                     var node = ts.getParseTreeNode(nodeIn, ts.hasPossibleExternalModuleReference);
79293                     return node && getExternalModuleFileFromDeclaration(node);
79294                 },
79295                 getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName,
79296                 getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol,
79297                 isLiteralConstDeclaration: isLiteralConstDeclaration,
79298                 isLateBound: function (nodeIn) {
79299                     var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
79300                     var symbol = node && getSymbolOfNode(node);
79301                     return !!(symbol && ts.getCheckFlags(symbol) & 4096 /* Late */);
79302                 },
79303                 getJsxFactoryEntity: getJsxFactoryEntity,
79304                 getJsxFragmentFactoryEntity: getJsxFragmentFactoryEntity,
79305                 getAllAccessorDeclarations: function (accessor) {
79306                     accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217
79307                     var otherKind = accessor.kind === 168 /* SetAccessor */ ? 167 /* GetAccessor */ : 168 /* SetAccessor */;
79308                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
79309                     var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
79310                     var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
79311                     var setAccessor = accessor.kind === 168 /* SetAccessor */ ? accessor : otherAccessor;
79312                     var getAccessor = accessor.kind === 167 /* GetAccessor */ ? accessor : otherAccessor;
79313                     return {
79314                         firstAccessor: firstAccessor,
79315                         secondAccessor: secondAccessor,
79316                         setAccessor: setAccessor,
79317                         getAccessor: getAccessor
79318                     };
79319                 },
79320                 getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); },
79321                 isBindingCapturedByNode: function (node, decl) {
79322                     var parseNode = ts.getParseTreeNode(node);
79323                     var parseDecl = ts.getParseTreeNode(decl);
79324                     return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
79325                 },
79326                 getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) {
79327                     var n = ts.getParseTreeNode(node);
79328                     ts.Debug.assert(n && n.kind === 297 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile");
79329                     var sym = getSymbolOfNode(node);
79330                     if (!sym) {
79331                         return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled);
79332                     }
79333                     return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled);
79334                 },
79335                 isImportRequiredByAugmentation: isImportRequiredByAugmentation,
79336             };
79337             function isImportRequiredByAugmentation(node) {
79338                 var file = ts.getSourceFileOfNode(node);
79339                 if (!file.symbol)
79340                     return false;
79341                 var importTarget = getExternalModuleFileFromDeclaration(node);
79342                 if (!importTarget)
79343                     return false;
79344                 if (importTarget === file)
79345                     return false;
79346                 var exports = getExportsOfModule(file.symbol);
79347                 for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) {
79348                     var s = _a[_i];
79349                     if (s.mergeId) {
79350                         var merged = getMergedSymbol(s);
79351                         for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) {
79352                             var d = _c[_b];
79353                             var declFile = ts.getSourceFileOfNode(d);
79354                             if (declFile === importTarget) {
79355                                 return true;
79356                             }
79357                         }
79358                     }
79359                 }
79360                 return false;
79361             }
79362             function isInHeritageClause(node) {
79363                 return node.parent && node.parent.kind === 223 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 286 /* HeritageClause */;
79364             }
79365             // defined here to avoid outer scope pollution
79366             function getTypeReferenceDirectivesForEntityName(node) {
79367                 // program does not have any files with type reference directives - bail out
79368                 if (!fileToDirective) {
79369                     return undefined;
79370                 }
79371                 // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause
79372                 // qualified names can only be used as types\namespaces
79373                 // identifiers are treated as values only if they appear in type queries
79374                 var meaning = 788968 /* Type */ | 1920 /* Namespace */;
79375                 if ((node.kind === 78 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 201 /* PropertyAccessExpression */ && !isInHeritageClause(node))) {
79376                     meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
79377                 }
79378                 var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
79379                 return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined;
79380             }
79381             // defined here to avoid outer scope pollution
79382             function getTypeReferenceDirectivesForSymbol(symbol, meaning) {
79383                 // program does not have any files with type reference directives - bail out
79384                 if (!fileToDirective) {
79385                     return undefined;
79386                 }
79387                 if (!isSymbolFromTypeDeclarationFile(symbol)) {
79388                     return undefined;
79389                 }
79390                 // check what declarations in the symbol can contribute to the target meaning
79391                 var typeReferenceDirectives;
79392                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
79393                     var decl = _a[_i];
79394                     // check meaning of the local symbol to see if declaration needs to be analyzed further
79395                     if (decl.symbol && decl.symbol.flags & meaning) {
79396                         var file = ts.getSourceFileOfNode(decl);
79397                         var typeReferenceDirective = fileToDirective.get(file.path);
79398                         if (typeReferenceDirective) {
79399                             (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
79400                         }
79401                         else {
79402                             // found at least one entry that does not originate from type reference directive
79403                             return undefined;
79404                         }
79405                     }
79406                 }
79407                 return typeReferenceDirectives;
79408             }
79409             function isSymbolFromTypeDeclarationFile(symbol) {
79410                 // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern)
79411                 if (!symbol.declarations) {
79412                     return false;
79413                 }
79414                 // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope
79415                 // external modules cannot define or contribute to type declaration files
79416                 var current = symbol;
79417                 while (true) {
79418                     var parent = getParentOfSymbol(current);
79419                     if (parent) {
79420                         current = parent;
79421                     }
79422                     else {
79423                         break;
79424                     }
79425                 }
79426                 if (current.valueDeclaration && current.valueDeclaration.kind === 297 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
79427                     return false;
79428                 }
79429                 // check that at least one declaration of top level symbol originates from type declaration file
79430                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
79431                     var decl = _a[_i];
79432                     var file = ts.getSourceFileOfNode(decl);
79433                     if (fileToDirective.has(file.path)) {
79434                         return true;
79435                     }
79436                 }
79437                 return false;
79438             }
79439             function addReferencedFilesToTypeDirective(file, key) {
79440                 if (fileToDirective.has(file.path))
79441                     return;
79442                 fileToDirective.set(file.path, key);
79443                 for (var _i = 0, _a = file.referencedFiles; _i < _a.length; _i++) {
79444                     var fileName = _a[_i].fileName;
79445                     var resolvedFile = ts.resolveTripleslashReference(fileName, file.fileName);
79446                     var referencedFile = host.getSourceFile(resolvedFile);
79447                     if (referencedFile) {
79448                         addReferencedFilesToTypeDirective(referencedFile, key);
79449                     }
79450                 }
79451             }
79452         }
79453         function getExternalModuleFileFromDeclaration(declaration) {
79454             var specifier = declaration.kind === 256 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration);
79455             var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217
79456             if (!moduleSymbol) {
79457                 return undefined;
79458             }
79459             return ts.getDeclarationOfKind(moduleSymbol, 297 /* SourceFile */);
79460         }
79461         function initializeTypeChecker() {
79462             // Bind all source files and propagate errors
79463             for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
79464                 var file = _a[_i];
79465                 ts.bindSourceFile(file, compilerOptions);
79466             }
79467             amalgamatedDuplicates = new ts.Map();
79468             // Initialize global symbol table
79469             var augmentations;
79470             for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
79471                 var file = _c[_b];
79472                 if (file.redirectInfo) {
79473                     continue;
79474                 }
79475                 if (!ts.isExternalOrCommonJsModule(file)) {
79476                     // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`.
79477                     // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files.
79478                     var fileGlobalThisSymbol = file.locals.get("globalThis");
79479                     if (fileGlobalThisSymbol) {
79480                         for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) {
79481                             var declaration = _e[_d];
79482                             diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis"));
79483                         }
79484                     }
79485                     mergeSymbolTable(globals, file.locals);
79486                 }
79487                 if (file.jsGlobalAugmentations) {
79488                     mergeSymbolTable(globals, file.jsGlobalAugmentations);
79489                 }
79490                 if (file.patternAmbientModules && file.patternAmbientModules.length) {
79491                     patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
79492                 }
79493                 if (file.moduleAugmentations.length) {
79494                     (augmentations || (augmentations = [])).push(file.moduleAugmentations);
79495                 }
79496                 if (file.symbol && file.symbol.globalExports) {
79497                     // Merge in UMD exports with first-in-wins semantics (see #9771)
79498                     var source = file.symbol.globalExports;
79499                     source.forEach(function (sourceSymbol, id) {
79500                         if (!globals.has(id)) {
79501                             globals.set(id, sourceSymbol);
79502                         }
79503                     });
79504                 }
79505             }
79506             // We do global augmentations separately from module augmentations (and before creating global types) because they
79507             //  1. Affect global types. We won't have the correct global types until global augmentations are merged. Also,
79508             //  2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require
79509             //       checking for an export or property on the module (if export=) which, in turn, can fall back to the
79510             //       apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we
79511             //       did module augmentations prior to finalizing the global types.
79512             if (augmentations) {
79513                 // merge _global_ module augmentations.
79514                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
79515                 for (var _f = 0, augmentations_1 = augmentations; _f < augmentations_1.length; _f++) {
79516                     var list = augmentations_1[_f];
79517                     for (var _g = 0, list_1 = list; _g < list_1.length; _g++) {
79518                         var augmentation = list_1[_g];
79519                         if (!ts.isGlobalScopeAugmentation(augmentation.parent))
79520                             continue;
79521                         mergeModuleAugmentation(augmentation);
79522                     }
79523                 }
79524             }
79525             // Setup global builtins
79526             addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0);
79527             getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
79528             getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true);
79529             getSymbolLinks(unknownSymbol).type = errorType;
79530             getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol);
79531             // Initialize special types
79532             globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true);
79533             globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true);
79534             globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true);
79535             globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
79536             globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
79537             globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true);
79538             globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
79539             globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
79540             globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
79541             anyArrayType = createArrayType(anyType);
79542             autoArrayType = createArrayType(autoType);
79543             if (autoArrayType === emptyObjectType) {
79544                 // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
79545                 autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
79546             }
79547             globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
79548             anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
79549             globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
79550             if (augmentations) {
79551                 // merge _nonglobal_ module augmentations.
79552                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
79553                 for (var _h = 0, augmentations_2 = augmentations; _h < augmentations_2.length; _h++) {
79554                     var list = augmentations_2[_h];
79555                     for (var _j = 0, list_2 = list; _j < list_2.length; _j++) {
79556                         var augmentation = list_2[_j];
79557                         if (ts.isGlobalScopeAugmentation(augmentation.parent))
79558                             continue;
79559                         mergeModuleAugmentation(augmentation);
79560                     }
79561                 }
79562             }
79563             amalgamatedDuplicates.forEach(function (_a) {
79564                 var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols;
79565                 // If not many things conflict, issue individual errors
79566                 if (conflictingSymbols.size < 8) {
79567                     conflictingSymbols.forEach(function (_a, symbolName) {
79568                         var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations;
79569                         var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0;
79570                         for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) {
79571                             var node = firstFileLocations_1[_i];
79572                             addDuplicateDeclarationError(node, message, symbolName, secondFileLocations);
79573                         }
79574                         for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) {
79575                             var node = secondFileLocations_1[_b];
79576                             addDuplicateDeclarationError(node, message, symbolName, firstFileLocations);
79577                         }
79578                     });
79579                 }
79580                 else {
79581                     // Otherwise issue top-level error since the files appear very identical in terms of what they contain
79582                     var list = ts.arrayFrom(conflictingSymbols.keys()).join(", ");
79583                     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)));
79584                     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)));
79585                 }
79586             });
79587             amalgamatedDuplicates = undefined;
79588         }
79589         function checkExternalEmitHelpers(location, helpers) {
79590             if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
79591                 var sourceFile = ts.getSourceFileOfNode(location);
79592                 if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 8388608 /* Ambient */)) {
79593                     var helpersModule = resolveHelpersModule(sourceFile, location);
79594                     if (helpersModule !== unknownSymbol) {
79595                         var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
79596                         for (var helper = 1 /* FirstEmitHelper */; helper <= 2097152 /* LastEmitHelper */; helper <<= 1) {
79597                             if (uncheckedHelpers & helper) {
79598                                 var name = getHelperName(helper);
79599                                 var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 111551 /* Value */);
79600                                 if (!symbol) {
79601                                     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);
79602                                 }
79603                             }
79604                         }
79605                     }
79606                     requestedExternalEmitHelpers |= helpers;
79607                 }
79608             }
79609         }
79610         function getHelperName(helper) {
79611             switch (helper) {
79612                 case 1 /* Extends */: return "__extends";
79613                 case 2 /* Assign */: return "__assign";
79614                 case 4 /* Rest */: return "__rest";
79615                 case 8 /* Decorate */: return "__decorate";
79616                 case 16 /* Metadata */: return "__metadata";
79617                 case 32 /* Param */: return "__param";
79618                 case 64 /* Awaiter */: return "__awaiter";
79619                 case 128 /* Generator */: return "__generator";
79620                 case 256 /* Values */: return "__values";
79621                 case 512 /* Read */: return "__read";
79622                 case 1024 /* SpreadArray */: return "__spreadArray";
79623                 case 2048 /* Await */: return "__await";
79624                 case 4096 /* AsyncGenerator */: return "__asyncGenerator";
79625                 case 8192 /* AsyncDelegator */: return "__asyncDelegator";
79626                 case 16384 /* AsyncValues */: return "__asyncValues";
79627                 case 32768 /* ExportStar */: return "__exportStar";
79628                 case 65536 /* ImportStar */: return "__importStar";
79629                 case 131072 /* ImportDefault */: return "__importDefault";
79630                 case 262144 /* MakeTemplateObject */: return "__makeTemplateObject";
79631                 case 524288 /* ClassPrivateFieldGet */: return "__classPrivateFieldGet";
79632                 case 1048576 /* ClassPrivateFieldSet */: return "__classPrivateFieldSet";
79633                 case 2097152 /* CreateBinding */: return "__createBinding";
79634                 default: return ts.Debug.fail("Unrecognized helper");
79635             }
79636         }
79637         function resolveHelpersModule(node, errorNode) {
79638             if (!externalHelpersModule) {
79639                 externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
79640             }
79641             return externalHelpersModule;
79642         }
79643         // GRAMMAR CHECKING
79644         function checkGrammarDecoratorsAndModifiers(node) {
79645             return checkGrammarDecorators(node) || checkGrammarModifiers(node);
79646         }
79647         function checkGrammarDecorators(node) {
79648             if (!node.decorators) {
79649                 return false;
79650             }
79651             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
79652                 if (node.kind === 165 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
79653                     return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
79654                 }
79655                 else {
79656                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here);
79657                 }
79658             }
79659             else if (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */) {
79660                 var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
79661                 if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) {
79662                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
79663                 }
79664             }
79665             return false;
79666         }
79667         function checkGrammarModifiers(node) {
79668             var quickResult = reportObviousModifierErrors(node);
79669             if (quickResult !== undefined) {
79670                 return quickResult;
79671             }
79672             var lastStatic, lastDeclare, lastAsync, lastReadonly;
79673             var flags = 0 /* None */;
79674             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
79675                 var modifier = _a[_i];
79676                 if (modifier.kind !== 142 /* ReadonlyKeyword */) {
79677                     if (node.kind === 162 /* PropertySignature */ || node.kind === 164 /* MethodSignature */) {
79678                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind));
79679                     }
79680                     if (node.kind === 171 /* IndexSignature */) {
79681                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind));
79682                     }
79683                 }
79684                 switch (modifier.kind) {
79685                     case 84 /* ConstKeyword */:
79686                         if (node.kind !== 255 /* EnumDeclaration */) {
79687                             return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(84 /* ConstKeyword */));
79688                         }
79689                         break;
79690                     case 122 /* PublicKeyword */:
79691                     case 121 /* ProtectedKeyword */:
79692                     case 120 /* PrivateKeyword */:
79693                         var text = visibilityToString(ts.modifierToFlag(modifier.kind));
79694                         if (flags & 28 /* AccessibilityModifier */) {
79695                             return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen);
79696                         }
79697                         else if (flags & 32 /* Static */) {
79698                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
79699                         }
79700                         else if (flags & 64 /* Readonly */) {
79701                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
79702                         }
79703                         else if (flags & 256 /* Async */) {
79704                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
79705                         }
79706                         else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) {
79707                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
79708                         }
79709                         else if (flags & 128 /* Abstract */) {
79710                             if (modifier.kind === 120 /* PrivateKeyword */) {
79711                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
79712                             }
79713                             else {
79714                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
79715                             }
79716                         }
79717                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
79718                             return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
79719                         }
79720                         flags |= ts.modifierToFlag(modifier.kind);
79721                         break;
79722                     case 123 /* StaticKeyword */:
79723                         if (flags & 32 /* Static */) {
79724                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static");
79725                         }
79726                         else if (flags & 64 /* Readonly */) {
79727                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
79728                         }
79729                         else if (flags & 256 /* Async */) {
79730                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
79731                         }
79732                         else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) {
79733                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
79734                         }
79735                         else if (node.kind === 160 /* Parameter */) {
79736                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
79737                         }
79738                         else if (flags & 128 /* Abstract */) {
79739                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
79740                         }
79741                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
79742                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static");
79743                         }
79744                         flags |= 32 /* Static */;
79745                         lastStatic = modifier;
79746                         break;
79747                     case 142 /* ReadonlyKeyword */:
79748                         if (flags & 64 /* Readonly */) {
79749                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly");
79750                         }
79751                         else if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */ && node.kind !== 171 /* IndexSignature */ && node.kind !== 160 /* Parameter */) {
79752                             // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property.
79753                             return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
79754                         }
79755                         flags |= 64 /* Readonly */;
79756                         lastReadonly = modifier;
79757                         break;
79758                     case 92 /* ExportKeyword */:
79759                         if (flags & 1 /* Export */) {
79760                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export");
79761                         }
79762                         else if (flags & 2 /* Ambient */) {
79763                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
79764                         }
79765                         else if (flags & 128 /* Abstract */) {
79766                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
79767                         }
79768                         else if (flags & 256 /* Async */) {
79769                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
79770                         }
79771                         else if (ts.isClassLike(node.parent)) {
79772                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export");
79773                         }
79774                         else if (node.kind === 160 /* Parameter */) {
79775                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
79776                         }
79777                         flags |= 1 /* Export */;
79778                         break;
79779                     case 87 /* DefaultKeyword */:
79780                         var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent;
79781                         if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
79782                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
79783                         }
79784                         flags |= 512 /* Default */;
79785                         break;
79786                     case 133 /* DeclareKeyword */:
79787                         if (flags & 2 /* Ambient */) {
79788                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare");
79789                         }
79790                         else if (flags & 256 /* Async */) {
79791                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
79792                         }
79793                         else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) {
79794                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare");
79795                         }
79796                         else if (node.kind === 160 /* Parameter */) {
79797                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
79798                         }
79799                         else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 257 /* ModuleBlock */) {
79800                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
79801                         }
79802                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
79803                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare");
79804                         }
79805                         flags |= 2 /* Ambient */;
79806                         lastDeclare = modifier;
79807                         break;
79808                     case 125 /* AbstractKeyword */:
79809                         if (flags & 128 /* Abstract */) {
79810                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
79811                         }
79812                         if (node.kind !== 252 /* ClassDeclaration */ &&
79813                             node.kind !== 175 /* ConstructorType */) {
79814                             if (node.kind !== 165 /* MethodDeclaration */ &&
79815                                 node.kind !== 163 /* PropertyDeclaration */ &&
79816                                 node.kind !== 167 /* GetAccessor */ &&
79817                                 node.kind !== 168 /* SetAccessor */) {
79818                                 return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
79819                             }
79820                             if (!(node.parent.kind === 252 /* ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* Abstract */))) {
79821                                 return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class);
79822                             }
79823                             if (flags & 32 /* Static */) {
79824                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
79825                             }
79826                             if (flags & 8 /* Private */) {
79827                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
79828                             }
79829                             if (flags & 256 /* Async */ && lastAsync) {
79830                                 return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
79831                             }
79832                         }
79833                         if (ts.isNamedDeclaration(node) && node.name.kind === 79 /* PrivateIdentifier */) {
79834                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract");
79835                         }
79836                         flags |= 128 /* Abstract */;
79837                         break;
79838                     case 129 /* AsyncKeyword */:
79839                         if (flags & 256 /* Async */) {
79840                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async");
79841                         }
79842                         else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) {
79843                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
79844                         }
79845                         else if (node.kind === 160 /* Parameter */) {
79846                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
79847                         }
79848                         if (flags & 128 /* Abstract */) {
79849                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
79850                         }
79851                         flags |= 256 /* Async */;
79852                         lastAsync = modifier;
79853                         break;
79854                 }
79855             }
79856             if (node.kind === 166 /* Constructor */) {
79857                 if (flags & 32 /* Static */) {
79858                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
79859                 }
79860                 if (flags & 128 /* Abstract */) {
79861                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217
79862                 }
79863                 else if (flags & 256 /* Async */) {
79864                     return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
79865                 }
79866                 else if (flags & 64 /* Readonly */) {
79867                     return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly");
79868                 }
79869                 return false;
79870             }
79871             else if ((node.kind === 261 /* ImportDeclaration */ || node.kind === 260 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
79872                 return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
79873             }
79874             else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
79875                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
79876             }
79877             else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
79878                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
79879             }
79880             if (flags & 256 /* Async */) {
79881                 return checkGrammarAsyncModifier(node, lastAsync);
79882             }
79883             return false;
79884         }
79885         /**
79886          * true | false: Early return this value from checkGrammarModifiers.
79887          * undefined: Need to do full checking on the modifiers.
79888          */
79889         function reportObviousModifierErrors(node) {
79890             return !node.modifiers
79891                 ? false
79892                 : shouldReportBadModifier(node)
79893                     ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here)
79894                     : undefined;
79895         }
79896         function shouldReportBadModifier(node) {
79897             switch (node.kind) {
79898                 case 167 /* GetAccessor */:
79899                 case 168 /* SetAccessor */:
79900                 case 166 /* Constructor */:
79901                 case 163 /* PropertyDeclaration */:
79902                 case 162 /* PropertySignature */:
79903                 case 165 /* MethodDeclaration */:
79904                 case 164 /* MethodSignature */:
79905                 case 171 /* IndexSignature */:
79906                 case 256 /* ModuleDeclaration */:
79907                 case 261 /* ImportDeclaration */:
79908                 case 260 /* ImportEqualsDeclaration */:
79909                 case 267 /* ExportDeclaration */:
79910                 case 266 /* ExportAssignment */:
79911                 case 208 /* FunctionExpression */:
79912                 case 209 /* ArrowFunction */:
79913                 case 160 /* Parameter */:
79914                     return false;
79915                 default:
79916                     if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) {
79917                         return false;
79918                     }
79919                     switch (node.kind) {
79920                         case 251 /* FunctionDeclaration */:
79921                             return nodeHasAnyModifiersExcept(node, 129 /* AsyncKeyword */);
79922                         case 252 /* ClassDeclaration */:
79923                         case 175 /* ConstructorType */:
79924                             return nodeHasAnyModifiersExcept(node, 125 /* AbstractKeyword */);
79925                         case 253 /* InterfaceDeclaration */:
79926                         case 232 /* VariableStatement */:
79927                         case 254 /* TypeAliasDeclaration */:
79928                             return true;
79929                         case 255 /* EnumDeclaration */:
79930                             return nodeHasAnyModifiersExcept(node, 84 /* ConstKeyword */);
79931                         default:
79932                             ts.Debug.fail();
79933                     }
79934             }
79935         }
79936         function nodeHasAnyModifiersExcept(node, allowedModifier) {
79937             return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier;
79938         }
79939         function checkGrammarAsyncModifier(node, asyncModifier) {
79940             switch (node.kind) {
79941                 case 165 /* MethodDeclaration */:
79942                 case 251 /* FunctionDeclaration */:
79943                 case 208 /* FunctionExpression */:
79944                 case 209 /* ArrowFunction */:
79945                     return false;
79946             }
79947             return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async");
79948         }
79949         function checkGrammarForDisallowedTrailingComma(list, diag) {
79950             if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; }
79951             if (list && list.hasTrailingComma) {
79952                 return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag);
79953             }
79954             return false;
79955         }
79956         function checkGrammarTypeParameterList(typeParameters, file) {
79957             if (typeParameters && typeParameters.length === 0) {
79958                 var start = typeParameters.pos - "<".length;
79959                 var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length;
79960                 return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty);
79961             }
79962             return false;
79963         }
79964         function checkGrammarParameterList(parameters) {
79965             var seenOptionalParameter = false;
79966             var parameterCount = parameters.length;
79967             for (var i = 0; i < parameterCount; i++) {
79968                 var parameter = parameters[i];
79969                 if (parameter.dotDotDotToken) {
79970                     if (i !== (parameterCount - 1)) {
79971                         return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
79972                     }
79973                     if (!(parameter.flags & 8388608 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070
79974                         checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
79975                     }
79976                     if (parameter.questionToken) {
79977                         return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional);
79978                     }
79979                     if (parameter.initializer) {
79980                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer);
79981                     }
79982                 }
79983                 else if (isOptionalParameter(parameter)) {
79984                     seenOptionalParameter = true;
79985                     if (parameter.questionToken && parameter.initializer) {
79986                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
79987                     }
79988                 }
79989                 else if (seenOptionalParameter && !parameter.initializer) {
79990                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
79991                 }
79992             }
79993         }
79994         function getNonSimpleParameters(parameters) {
79995             return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); });
79996         }
79997         function checkGrammarForUseStrictSimpleParameterList(node) {
79998             if (languageVersion >= 3 /* ES2016 */) {
79999                 var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements);
80000                 if (useStrictDirective_1) {
80001                     var nonSimpleParameters = getNonSimpleParameters(node.parameters);
80002                     if (ts.length(nonSimpleParameters)) {
80003                         ts.forEach(nonSimpleParameters, function (parameter) {
80004                             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));
80005                         });
80006                         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)); });
80007                         ts.addRelatedInfo.apply(void 0, __spreadArray([error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)], diagnostics_2));
80008                         return true;
80009                     }
80010                 }
80011             }
80012             return false;
80013         }
80014         function checkGrammarFunctionLikeDeclaration(node) {
80015             // Prevent cascading error by short-circuit
80016             var file = ts.getSourceFileOfNode(node);
80017             return checkGrammarDecoratorsAndModifiers(node) ||
80018                 checkGrammarTypeParameterList(node.typeParameters, file) ||
80019                 checkGrammarParameterList(node.parameters) ||
80020                 checkGrammarArrowFunction(node, file) ||
80021                 (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node));
80022         }
80023         function checkGrammarClassLikeDeclaration(node) {
80024             var file = ts.getSourceFileOfNode(node);
80025             return checkGrammarClassDeclarationHeritageClauses(node) ||
80026                 checkGrammarTypeParameterList(node.typeParameters, file);
80027         }
80028         function checkGrammarArrowFunction(node, file) {
80029             if (!ts.isArrowFunction(node)) {
80030                 return false;
80031             }
80032             var equalsGreaterThanToken = node.equalsGreaterThanToken;
80033             var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
80034             var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
80035             return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow);
80036         }
80037         function checkGrammarIndexSignatureParameters(node) {
80038             var parameter = node.parameters[0];
80039             if (node.parameters.length !== 1) {
80040                 if (parameter) {
80041                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
80042                 }
80043                 else {
80044                     return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
80045                 }
80046             }
80047             checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma);
80048             if (parameter.dotDotDotToken) {
80049                 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
80050             }
80051             if (ts.hasEffectiveModifiers(parameter)) {
80052                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
80053             }
80054             if (parameter.questionToken) {
80055                 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
80056             }
80057             if (parameter.initializer) {
80058                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
80059             }
80060             if (!parameter.type) {
80061                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
80062             }
80063             if (parameter.type.kind !== 147 /* StringKeyword */ && parameter.type.kind !== 144 /* NumberKeyword */) {
80064                 var type = getTypeFromTypeNode(parameter.type);
80065                 if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) {
80066                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType));
80067                 }
80068                 if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) {
80069                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead);
80070                 }
80071                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number);
80072             }
80073             if (!node.type) {
80074                 return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation);
80075             }
80076             return false;
80077         }
80078         function checkGrammarIndexSignature(node) {
80079             // Prevent cascading error by short-circuit
80080             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node);
80081         }
80082         function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
80083             if (typeArguments && typeArguments.length === 0) {
80084                 var sourceFile = ts.getSourceFileOfNode(node);
80085                 var start = typeArguments.pos - "<".length;
80086                 var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
80087                 return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty);
80088             }
80089             return false;
80090         }
80091         function checkGrammarTypeArguments(node, typeArguments) {
80092             return checkGrammarForDisallowedTrailingComma(typeArguments) ||
80093                 checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
80094         }
80095         function checkGrammarTaggedTemplateChain(node) {
80096             if (node.questionDotToken || node.flags & 32 /* OptionalChain */) {
80097                 return grammarErrorOnNode(node.template, ts.Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain);
80098             }
80099             return false;
80100         }
80101         function checkGrammarForOmittedArgument(args) {
80102             if (args) {
80103                 for (var _i = 0, args_4 = args; _i < args_4.length; _i++) {
80104                     var arg = args_4[_i];
80105                     if (arg.kind === 222 /* OmittedExpression */) {
80106                         return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
80107                     }
80108                 }
80109             }
80110             return false;
80111         }
80112         function checkGrammarArguments(args) {
80113             return checkGrammarForOmittedArgument(args);
80114         }
80115         function checkGrammarHeritageClause(node) {
80116             var types = node.types;
80117             if (checkGrammarForDisallowedTrailingComma(types)) {
80118                 return true;
80119             }
80120             if (types && types.length === 0) {
80121                 var listType = ts.tokenToString(node.token);
80122                 return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType);
80123             }
80124             return ts.some(types, checkGrammarExpressionWithTypeArguments);
80125         }
80126         function checkGrammarExpressionWithTypeArguments(node) {
80127             return checkGrammarTypeArguments(node, node.typeArguments);
80128         }
80129         function checkGrammarClassDeclarationHeritageClauses(node) {
80130             var seenExtendsClause = false;
80131             var seenImplementsClause = false;
80132             if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) {
80133                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
80134                     var heritageClause = _a[_i];
80135                     if (heritageClause.token === 93 /* ExtendsKeyword */) {
80136                         if (seenExtendsClause) {
80137                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
80138                         }
80139                         if (seenImplementsClause) {
80140                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause);
80141                         }
80142                         if (heritageClause.types.length > 1) {
80143                             return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class);
80144                         }
80145                         seenExtendsClause = true;
80146                     }
80147                     else {
80148                         ts.Debug.assert(heritageClause.token === 116 /* ImplementsKeyword */);
80149                         if (seenImplementsClause) {
80150                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen);
80151                         }
80152                         seenImplementsClause = true;
80153                     }
80154                     // Grammar checking heritageClause inside class declaration
80155                     checkGrammarHeritageClause(heritageClause);
80156                 }
80157             }
80158         }
80159         function checkGrammarInterfaceDeclaration(node) {
80160             var seenExtendsClause = false;
80161             if (node.heritageClauses) {
80162                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
80163                     var heritageClause = _a[_i];
80164                     if (heritageClause.token === 93 /* ExtendsKeyword */) {
80165                         if (seenExtendsClause) {
80166                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
80167                         }
80168                         seenExtendsClause = true;
80169                     }
80170                     else {
80171                         ts.Debug.assert(heritageClause.token === 116 /* ImplementsKeyword */);
80172                         return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause);
80173                     }
80174                     // Grammar checking heritageClause inside class declaration
80175                     checkGrammarHeritageClause(heritageClause);
80176                 }
80177             }
80178             return false;
80179         }
80180         function checkGrammarComputedPropertyName(node) {
80181             // If node is not a computedPropertyName, just skip the grammar checking
80182             if (node.kind !== 158 /* ComputedPropertyName */) {
80183                 return false;
80184             }
80185             var computedPropertyName = node;
80186             if (computedPropertyName.expression.kind === 216 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) {
80187                 return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
80188             }
80189             return false;
80190         }
80191         function checkGrammarForGenerator(node) {
80192             if (node.asteriskToken) {
80193                 ts.Debug.assert(node.kind === 251 /* FunctionDeclaration */ ||
80194                     node.kind === 208 /* FunctionExpression */ ||
80195                     node.kind === 165 /* MethodDeclaration */);
80196                 if (node.flags & 8388608 /* Ambient */) {
80197                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
80198                 }
80199                 if (!node.body) {
80200                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
80201                 }
80202             }
80203         }
80204         function checkGrammarForInvalidQuestionMark(questionToken, message) {
80205             return !!questionToken && grammarErrorOnNode(questionToken, message);
80206         }
80207         function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
80208             return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
80209         }
80210         function checkGrammarObjectLiteralExpression(node, inDestructuring) {
80211             var seen = new ts.Map();
80212             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
80213                 var prop = _a[_i];
80214                 if (prop.kind === 290 /* SpreadAssignment */) {
80215                     if (inDestructuring) {
80216                         // a rest property cannot be destructured any further
80217                         var expression = ts.skipParentheses(prop.expression);
80218                         if (ts.isArrayLiteralExpression(expression) || ts.isObjectLiteralExpression(expression)) {
80219                             return grammarErrorOnNode(prop.expression, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
80220                         }
80221                     }
80222                     continue;
80223                 }
80224                 var name = prop.name;
80225                 if (name.kind === 158 /* ComputedPropertyName */) {
80226                     // If the name is not a ComputedPropertyName, the grammar checking will skip it
80227                     checkGrammarComputedPropertyName(name);
80228                 }
80229                 if (prop.kind === 289 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
80230                     // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern
80231                     // outside of destructuring it is a syntax error
80232                     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);
80233                 }
80234                 if (name.kind === 79 /* PrivateIdentifier */) {
80235                     return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
80236                 }
80237                 // Modifiers are never allowed on properties except for 'async' on a method declaration
80238                 if (prop.modifiers) {
80239                     // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
80240                     for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955
80241                         var mod = _c[_b];
80242                         if (mod.kind !== 129 /* AsyncKeyword */ || prop.kind !== 165 /* MethodDeclaration */) {
80243                             grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod));
80244                         }
80245                     }
80246                 }
80247                 // ECMA-262 11.1.5 Object Initializer
80248                 // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
80249                 // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
80250                 // IsDataDescriptor(propId.descriptor) is true.
80251                 //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
80252                 //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
80253                 //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
80254                 // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
80255                 var currentKind = void 0;
80256                 switch (prop.kind) {
80257                     case 289 /* ShorthandPropertyAssignment */:
80258                         checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
80259                     // falls through
80260                     case 288 /* PropertyAssignment */:
80261                         // Grammar checking for computedPropertyName and shorthandPropertyAssignment
80262                         checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
80263                         if (name.kind === 8 /* NumericLiteral */) {
80264                             checkGrammarNumericLiteral(name);
80265                         }
80266                         currentKind = 4 /* PropertyAssignment */;
80267                         break;
80268                     case 165 /* MethodDeclaration */:
80269                         currentKind = 8 /* Method */;
80270                         break;
80271                     case 167 /* GetAccessor */:
80272                         currentKind = 1 /* GetAccessor */;
80273                         break;
80274                     case 168 /* SetAccessor */:
80275                         currentKind = 2 /* SetAccessor */;
80276                         break;
80277                     default:
80278                         throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
80279                 }
80280                 if (!inDestructuring) {
80281                     var effectiveName = ts.getPropertyNameForPropertyNameNode(name);
80282                     if (effectiveName === undefined) {
80283                         continue;
80284                     }
80285                     var existingKind = seen.get(effectiveName);
80286                     if (!existingKind) {
80287                         seen.set(effectiveName, currentKind);
80288                     }
80289                     else {
80290                         if ((currentKind & 12 /* PropertyAssignmentOrMethod */) && (existingKind & 12 /* PropertyAssignmentOrMethod */)) {
80291                             grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name));
80292                         }
80293                         else if ((currentKind & 3 /* GetOrSetAccessor */) && (existingKind & 3 /* GetOrSetAccessor */)) {
80294                             if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) {
80295                                 seen.set(effectiveName, currentKind | existingKind);
80296                             }
80297                             else {
80298                                 return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
80299                             }
80300                         }
80301                         else {
80302                             return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
80303                         }
80304                     }
80305                 }
80306             }
80307         }
80308         function checkGrammarJsxElement(node) {
80309             checkGrammarTypeArguments(node, node.typeArguments);
80310             var seen = new ts.Map();
80311             for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
80312                 var attr = _a[_i];
80313                 if (attr.kind === 282 /* JsxSpreadAttribute */) {
80314                     continue;
80315                 }
80316                 var name = attr.name, initializer = attr.initializer;
80317                 if (!seen.get(name.escapedText)) {
80318                     seen.set(name.escapedText, true);
80319                 }
80320                 else {
80321                     return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
80322                 }
80323                 if (initializer && initializer.kind === 283 /* JsxExpression */ && !initializer.expression) {
80324                     return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
80325                 }
80326             }
80327         }
80328         function checkGrammarJsxExpression(node) {
80329             if (node.expression && ts.isCommaSequence(node.expression)) {
80330                 return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array);
80331             }
80332         }
80333         function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
80334             if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
80335                 return true;
80336             }
80337             if (forInOrOfStatement.kind === 239 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
80338                 if (!(forInOrOfStatement.flags & 32768 /* AwaitContext */)) {
80339                     var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement);
80340                     if (ts.isInTopLevelContext(forInOrOfStatement)) {
80341                         if (!hasParseDiagnostics(sourceFile)) {
80342                             if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
80343                                 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));
80344                             }
80345                             if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) {
80346                                 diagnostics.add(ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.Top_level_for_await_loops_are_only_allowed_when_the_module_option_is_set_to_esnext_or_system_and_the_target_option_is_set_to_es2017_or_higher));
80347                             }
80348                         }
80349                     }
80350                     else {
80351                         // use of 'for-await-of' in non-async function
80352                         if (!hasParseDiagnostics(sourceFile)) {
80353                             var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules);
80354                             var func = ts.getContainingFunction(forInOrOfStatement);
80355                             if (func && func.kind !== 166 /* Constructor */) {
80356                                 ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function.");
80357                                 var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
80358                                 ts.addRelatedInfo(diagnostic, relatedInfo);
80359                             }
80360                             diagnostics.add(diagnostic);
80361                             return true;
80362                         }
80363                     }
80364                     return false;
80365                 }
80366             }
80367             if (forInOrOfStatement.initializer.kind === 250 /* VariableDeclarationList */) {
80368                 var variableList = forInOrOfStatement.initializer;
80369                 if (!checkGrammarVariableDeclarationList(variableList)) {
80370                     var declarations = variableList.declarations;
80371                     // declarations.length can be zero if there is an error in variable declaration in for-of or for-in
80372                     // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details
80373                     // For example:
80374                     //      var let = 10;
80375                     //      for (let of [1,2,3]) {} // this is invalid ES6 syntax
80376                     //      for (let in [1,2,3]) {} // this is invalid ES6 syntax
80377                     // We will then want to skip on grammar checking on variableList declaration
80378                     if (!declarations.length) {
80379                         return false;
80380                     }
80381                     if (declarations.length > 1) {
80382                         var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */
80383                             ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
80384                             : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
80385                         return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
80386                     }
80387                     var firstDeclaration = declarations[0];
80388                     if (firstDeclaration.initializer) {
80389                         var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */
80390                             ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
80391                             : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
80392                         return grammarErrorOnNode(firstDeclaration.name, diagnostic);
80393                     }
80394                     if (firstDeclaration.type) {
80395                         var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */
80396                             ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation
80397                             : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
80398                         return grammarErrorOnNode(firstDeclaration, diagnostic);
80399                     }
80400                 }
80401             }
80402             return false;
80403         }
80404         function checkGrammarAccessor(accessor) {
80405             if (!(accessor.flags & 8388608 /* Ambient */)) {
80406                 if (languageVersion < 1 /* ES5 */) {
80407                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
80408                 }
80409                 if (accessor.body === undefined && !ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) {
80410                     return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
80411                 }
80412             }
80413             if (accessor.body && ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) {
80414                 return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
80415             }
80416             if (accessor.typeParameters) {
80417                 return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters);
80418             }
80419             if (!doesAccessorHaveCorrectParameterCount(accessor)) {
80420                 return grammarErrorOnNode(accessor.name, accessor.kind === 167 /* GetAccessor */ ?
80421                     ts.Diagnostics.A_get_accessor_cannot_have_parameters :
80422                     ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter);
80423             }
80424             if (accessor.kind === 168 /* SetAccessor */) {
80425                 if (accessor.type) {
80426                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
80427                 }
80428                 var parameter = ts.Debug.checkDefined(ts.getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
80429                 if (parameter.dotDotDotToken) {
80430                     return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter);
80431                 }
80432                 if (parameter.questionToken) {
80433                     return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
80434                 }
80435                 if (parameter.initializer) {
80436                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
80437                 }
80438             }
80439             return false;
80440         }
80441         /** Does the accessor have the right number of parameters?
80442          * A get accessor has no parameters or a single `this` parameter.
80443          * A set accessor has one parameter or a `this` parameter and one more parameter.
80444          */
80445         function doesAccessorHaveCorrectParameterCount(accessor) {
80446             return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 0 : 1);
80447         }
80448         function getAccessorThisParameter(accessor) {
80449             if (accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 1 : 2)) {
80450                 return ts.getThisParameter(accessor);
80451             }
80452         }
80453         function checkGrammarTypeOperatorNode(node) {
80454             if (node.operator === 151 /* UniqueKeyword */) {
80455                 if (node.type.kind !== 148 /* SymbolKeyword */) {
80456                     return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(148 /* SymbolKeyword */));
80457                 }
80458                 var parent = ts.walkUpParenthesizedTypes(node.parent);
80459                 if (ts.isInJSFile(parent) && ts.isJSDocTypeExpression(parent)) {
80460                     parent = parent.parent;
80461                     if (ts.isJSDocTypeTag(parent)) {
80462                         // walk up past JSDoc comment node
80463                         parent = parent.parent.parent;
80464                     }
80465                 }
80466                 switch (parent.kind) {
80467                     case 249 /* VariableDeclaration */:
80468                         var decl = parent;
80469                         if (decl.name.kind !== 78 /* Identifier */) {
80470                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
80471                         }
80472                         if (!ts.isVariableDeclarationInVariableStatement(decl)) {
80473                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
80474                         }
80475                         if (!(decl.parent.flags & 2 /* Const */)) {
80476                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
80477                         }
80478                         break;
80479                     case 163 /* PropertyDeclaration */:
80480                         if (!ts.hasSyntacticModifier(parent, 32 /* Static */) ||
80481                             !ts.hasEffectiveModifier(parent, 64 /* Readonly */)) {
80482                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
80483                         }
80484                         break;
80485                     case 162 /* PropertySignature */:
80486                         if (!ts.hasSyntacticModifier(parent, 64 /* Readonly */)) {
80487                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
80488                         }
80489                         break;
80490                     default:
80491                         return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
80492                 }
80493             }
80494             else if (node.operator === 142 /* ReadonlyKeyword */) {
80495                 if (node.type.kind !== 178 /* ArrayType */ && node.type.kind !== 179 /* TupleType */) {
80496                     return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(148 /* SymbolKeyword */));
80497                 }
80498             }
80499         }
80500         function checkGrammarForInvalidDynamicName(node, message) {
80501             if (isNonBindableDynamicName(node)) {
80502                 return grammarErrorOnNode(node, message);
80503             }
80504         }
80505         function checkGrammarMethod(node) {
80506             if (checkGrammarFunctionLikeDeclaration(node)) {
80507                 return true;
80508             }
80509             if (node.kind === 165 /* MethodDeclaration */) {
80510                 if (node.parent.kind === 200 /* ObjectLiteralExpression */) {
80511                     // We only disallow modifier on a method declaration if it is a property of object-literal-expression
80512                     if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 129 /* AsyncKeyword */)) {
80513                         return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here);
80514                     }
80515                     else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
80516                         return true;
80517                     }
80518                     else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
80519                         return true;
80520                     }
80521                     else if (node.body === undefined) {
80522                         return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
80523                     }
80524                 }
80525                 if (checkGrammarForGenerator(node)) {
80526                     return true;
80527                 }
80528             }
80529             if (ts.isClassLike(node.parent)) {
80530                 // Technically, computed properties in ambient contexts is disallowed
80531                 // for property declarations and accessors too, not just methods.
80532                 // However, property declarations disallow computed names in general,
80533                 // and accessors are not allowed in ambient contexts in general,
80534                 // so this error only really matters for methods.
80535                 if (node.flags & 8388608 /* Ambient */) {
80536                     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);
80537                 }
80538                 else if (node.kind === 165 /* MethodDeclaration */ && !node.body) {
80539                     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);
80540                 }
80541             }
80542             else if (node.parent.kind === 253 /* InterfaceDeclaration */) {
80543                 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);
80544             }
80545             else if (node.parent.kind === 177 /* TypeLiteral */) {
80546                 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);
80547             }
80548         }
80549         function checkGrammarBreakOrContinueStatement(node) {
80550             var current = node;
80551             while (current) {
80552                 if (ts.isFunctionLike(current)) {
80553                     return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary);
80554                 }
80555                 switch (current.kind) {
80556                     case 245 /* LabeledStatement */:
80557                         if (node.label && current.label.escapedText === node.label.escapedText) {
80558                             // found matching label - verify that label usage is correct
80559                             // continue can only target labels that are on iteration statements
80560                             var isMisplacedContinueLabel = node.kind === 240 /* ContinueStatement */
80561                                 && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true);
80562                             if (isMisplacedContinueLabel) {
80563                                 return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
80564                             }
80565                             return false;
80566                         }
80567                         break;
80568                     case 244 /* SwitchStatement */:
80569                         if (node.kind === 241 /* BreakStatement */ && !node.label) {
80570                             // unlabeled break within switch statement - ok
80571                             return false;
80572                         }
80573                         break;
80574                     default:
80575                         if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) {
80576                             // unlabeled break or continue within iteration statement - ok
80577                             return false;
80578                         }
80579                         break;
80580                 }
80581                 current = current.parent;
80582             }
80583             if (node.label) {
80584                 var message = node.kind === 241 /* BreakStatement */
80585                     ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement
80586                     : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
80587                 return grammarErrorOnNode(node, message);
80588             }
80589             else {
80590                 var message = node.kind === 241 /* BreakStatement */
80591                     ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement
80592                     : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
80593                 return grammarErrorOnNode(node, message);
80594             }
80595         }
80596         function checkGrammarBindingElement(node) {
80597             if (node.dotDotDotToken) {
80598                 var elements = node.parent.elements;
80599                 if (node !== ts.last(elements)) {
80600                     return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
80601                 }
80602                 checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
80603                 if (node.propertyName) {
80604                     return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name);
80605                 }
80606             }
80607             if (node.dotDotDotToken && node.initializer) {
80608                 // Error on equals token which immediately precedes the initializer
80609                 return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
80610             }
80611         }
80612         function isStringOrNumberLiteralExpression(expr) {
80613             return ts.isStringOrNumericLiteralLike(expr) ||
80614                 expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
80615                     expr.operand.kind === 8 /* NumericLiteral */;
80616         }
80617         function isBigIntLiteralExpression(expr) {
80618             return expr.kind === 9 /* BigIntLiteral */ ||
80619                 expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
80620                     expr.operand.kind === 9 /* BigIntLiteral */;
80621         }
80622         function isSimpleLiteralEnumReference(expr) {
80623             if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) &&
80624                 ts.isEntityNameExpression(expr.expression)) {
80625                 return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */);
80626             }
80627         }
80628         function checkAmbientInitializer(node) {
80629             var initializer = node.initializer;
80630             if (initializer) {
80631                 var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) ||
80632                     isSimpleLiteralEnumReference(initializer) ||
80633                     initializer.kind === 109 /* TrueKeyword */ || initializer.kind === 94 /* FalseKeyword */ ||
80634                     isBigIntLiteralExpression(initializer));
80635                 var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node);
80636                 if (isConstOrReadonly && !node.type) {
80637                     if (isInvalidInitializer) {
80638                         return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
80639                     }
80640                 }
80641                 else {
80642                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
80643                 }
80644                 if (!isConstOrReadonly || isInvalidInitializer) {
80645                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
80646                 }
80647             }
80648         }
80649         function checkGrammarVariableDeclaration(node) {
80650             if (node.parent.parent.kind !== 238 /* ForInStatement */ && node.parent.parent.kind !== 239 /* ForOfStatement */) {
80651                 if (node.flags & 8388608 /* Ambient */) {
80652                     checkAmbientInitializer(node);
80653                 }
80654                 else if (!node.initializer) {
80655                     if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) {
80656                         return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer);
80657                     }
80658                     if (ts.isVarConst(node)) {
80659                         return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized);
80660                     }
80661                 }
80662             }
80663             if (node.exclamationToken && (node.parent.parent.kind !== 232 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) {
80664                 var message = node.initializer
80665                     ? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions
80666                     : !node.type
80667                         ? ts.Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations
80668                         : ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context;
80669                 return grammarErrorOnNode(node.exclamationToken, message);
80670             }
80671             var moduleKind = ts.getEmitModuleKind(compilerOptions);
80672             if (moduleKind < ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System &&
80673                 !(node.parent.parent.flags & 8388608 /* Ambient */) && ts.hasSyntacticModifier(node.parent.parent, 1 /* Export */)) {
80674                 checkESModuleMarker(node.name);
80675             }
80676             var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node));
80677             // 1. LexicalDeclaration : LetOrConst BindingList ;
80678             // It is a Syntax Error if the BoundNames of BindingList contains "let".
80679             // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding
80680             // It is a Syntax Error if the BoundNames of ForDeclaration contains "let".
80681             // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code
80682             // and its Identifier is eval or arguments
80683             return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
80684         }
80685         function checkESModuleMarker(name) {
80686             if (name.kind === 78 /* Identifier */) {
80687                 if (ts.idText(name) === "__esModule") {
80688                     return grammarErrorOnNodeSkippedOn("noEmit", name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
80689                 }
80690             }
80691             else {
80692                 var elements = name.elements;
80693                 for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
80694                     var element = elements_1[_i];
80695                     if (!ts.isOmittedExpression(element)) {
80696                         return checkESModuleMarker(element.name);
80697                     }
80698                 }
80699             }
80700             return false;
80701         }
80702         function checkGrammarNameInLetOrConstDeclarations(name) {
80703             if (name.kind === 78 /* Identifier */) {
80704                 if (name.originalKeywordKind === 118 /* LetKeyword */) {
80705                     return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
80706                 }
80707             }
80708             else {
80709                 var elements = name.elements;
80710                 for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
80711                     var element = elements_2[_i];
80712                     if (!ts.isOmittedExpression(element)) {
80713                         checkGrammarNameInLetOrConstDeclarations(element.name);
80714                     }
80715                 }
80716             }
80717             return false;
80718         }
80719         function checkGrammarVariableDeclarationList(declarationList) {
80720             var declarations = declarationList.declarations;
80721             if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
80722                 return true;
80723             }
80724             if (!declarationList.declarations.length) {
80725                 return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty);
80726             }
80727             return false;
80728         }
80729         function allowLetAndConstDeclarations(parent) {
80730             switch (parent.kind) {
80731                 case 234 /* IfStatement */:
80732                 case 235 /* DoStatement */:
80733                 case 236 /* WhileStatement */:
80734                 case 243 /* WithStatement */:
80735                 case 237 /* ForStatement */:
80736                 case 238 /* ForInStatement */:
80737                 case 239 /* ForOfStatement */:
80738                     return false;
80739                 case 245 /* LabeledStatement */:
80740                     return allowLetAndConstDeclarations(parent.parent);
80741             }
80742             return true;
80743         }
80744         function checkGrammarForDisallowedLetOrConstStatement(node) {
80745             if (!allowLetAndConstDeclarations(node.parent)) {
80746                 if (ts.isLet(node.declarationList)) {
80747                     return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block);
80748                 }
80749                 else if (ts.isVarConst(node.declarationList)) {
80750                     return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block);
80751                 }
80752             }
80753         }
80754         function checkGrammarMetaProperty(node) {
80755             var escapedText = node.name.escapedText;
80756             switch (node.keywordToken) {
80757                 case 102 /* NewKeyword */:
80758                     if (escapedText !== "target") {
80759                         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");
80760                     }
80761                     break;
80762                 case 99 /* ImportKeyword */:
80763                     if (escapedText !== "meta") {
80764                         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");
80765                     }
80766                     break;
80767             }
80768         }
80769         function hasParseDiagnostics(sourceFile) {
80770             return sourceFile.parseDiagnostics.length > 0;
80771         }
80772         function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) {
80773             var sourceFile = ts.getSourceFileOfNode(node);
80774             if (!hasParseDiagnostics(sourceFile)) {
80775                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
80776                 diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2));
80777                 return true;
80778             }
80779             return false;
80780         }
80781         function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) {
80782             var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile);
80783             if (!hasParseDiagnostics(sourceFile)) {
80784                 diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2));
80785                 return true;
80786             }
80787             return false;
80788         }
80789         function grammarErrorOnNodeSkippedOn(key, node, message, arg0, arg1, arg2) {
80790             var sourceFile = ts.getSourceFileOfNode(node);
80791             if (!hasParseDiagnostics(sourceFile)) {
80792                 errorSkippedOn(key, node, message, arg0, arg1, arg2);
80793                 return true;
80794             }
80795             return false;
80796         }
80797         function grammarErrorOnNode(node, message, arg0, arg1, arg2) {
80798             var sourceFile = ts.getSourceFileOfNode(node);
80799             if (!hasParseDiagnostics(sourceFile)) {
80800                 diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2));
80801                 return true;
80802             }
80803             return false;
80804         }
80805         function checkGrammarConstructorTypeParameters(node) {
80806             var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined;
80807             var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters);
80808             if (range) {
80809                 var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos);
80810                 return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
80811             }
80812         }
80813         function checkGrammarConstructorTypeAnnotation(node) {
80814             var type = ts.getEffectiveReturnTypeNode(node);
80815             if (type) {
80816                 return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
80817             }
80818         }
80819         function checkGrammarProperty(node) {
80820             if (ts.isClassLike(node.parent)) {
80821                 if (ts.isStringLiteral(node.name) && node.name.text === "constructor") {
80822                     return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor);
80823                 }
80824                 if (checkGrammarForInvalidDynamicName(node.name, ts.Diagnostics.A_computed_property_name_in_a_class_property_declaration_must_refer_to_an_expression_whose_type_is_a_literal_type_or_a_unique_symbol_type)) {
80825                     return true;
80826                 }
80827                 if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) {
80828                     return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
80829                 }
80830             }
80831             else if (node.parent.kind === 253 /* InterfaceDeclaration */) {
80832                 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)) {
80833                     return true;
80834                 }
80835                 if (node.initializer) {
80836                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer);
80837                 }
80838             }
80839             else if (node.parent.kind === 177 /* TypeLiteral */) {
80840                 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)) {
80841                     return true;
80842                 }
80843                 if (node.initializer) {
80844                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer);
80845                 }
80846             }
80847             if (node.flags & 8388608 /* Ambient */) {
80848                 checkAmbientInitializer(node);
80849             }
80850             if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer ||
80851                 node.flags & 8388608 /* Ambient */ || ts.hasSyntacticModifier(node, 32 /* Static */ | 128 /* Abstract */))) {
80852                 var message = node.initializer
80853                     ? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions
80854                     : !node.type
80855                         ? ts.Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations
80856                         : ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context;
80857                 return grammarErrorOnNode(node.exclamationToken, message);
80858             }
80859         }
80860         function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
80861             // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace
80862             // interfaces and imports categories:
80863             //
80864             //  DeclarationElement:
80865             //     ExportAssignment
80866             //     export_opt   InterfaceDeclaration
80867             //     export_opt   TypeAliasDeclaration
80868             //     export_opt   ImportDeclaration
80869             //     export_opt   ExternalImportDeclaration
80870             //     export_opt   AmbientDeclaration
80871             //
80872             // TODO: The spec needs to be amended to reflect this grammar.
80873             if (node.kind === 253 /* InterfaceDeclaration */ ||
80874                 node.kind === 254 /* TypeAliasDeclaration */ ||
80875                 node.kind === 261 /* ImportDeclaration */ ||
80876                 node.kind === 260 /* ImportEqualsDeclaration */ ||
80877                 node.kind === 267 /* ExportDeclaration */ ||
80878                 node.kind === 266 /* ExportAssignment */ ||
80879                 node.kind === 259 /* NamespaceExportDeclaration */ ||
80880                 ts.hasSyntacticModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) {
80881                 return false;
80882             }
80883             return grammarErrorOnFirstToken(node, ts.Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier);
80884         }
80885         function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
80886             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
80887                 var decl = _a[_i];
80888                 if (ts.isDeclaration(decl) || decl.kind === 232 /* VariableStatement */) {
80889                     if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
80890                         return true;
80891                     }
80892                 }
80893             }
80894             return false;
80895         }
80896         function checkGrammarSourceFile(node) {
80897             return !!(node.flags & 8388608 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
80898         }
80899         function checkGrammarStatementInAmbientContext(node) {
80900             if (node.flags & 8388608 /* Ambient */) {
80901                 // Find containing block which is either Block, ModuleBlock, SourceFile
80902                 var links = getNodeLinks(node);
80903                 if (!links.hasReportedStatementInAmbientContext && (ts.isFunctionLike(node.parent) || ts.isAccessor(node.parent))) {
80904                     return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
80905                 }
80906                 // We are either parented by another statement, or some sort of block.
80907                 // If we're in a block, we only want to really report an error once
80908                 // to prevent noisiness.  So use a bit on the block to indicate if
80909                 // this has already been reported, and don't report if it has.
80910                 //
80911                 if (node.parent.kind === 230 /* Block */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) {
80912                     var links_2 = getNodeLinks(node.parent);
80913                     // Check if the containing block ever report this error
80914                     if (!links_2.hasReportedStatementInAmbientContext) {
80915                         return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
80916                     }
80917                 }
80918                 else {
80919                     // We must be parented by a statement.  If so, there's no need
80920                     // to report the error as our parent will have already done it.
80921                     // Debug.assert(isStatement(node.parent));
80922                 }
80923             }
80924             return false;
80925         }
80926         function checkGrammarNumericLiteral(node) {
80927             // Grammar checking
80928             if (node.numericLiteralFlags & 32 /* Octal */) {
80929                 var diagnosticMessage = void 0;
80930                 if (languageVersion >= 1 /* ES5 */) {
80931                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0;
80932                 }
80933                 else if (ts.isChildOfNodeWithKind(node, 191 /* LiteralType */)) {
80934                     diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0;
80935                 }
80936                 else if (ts.isChildOfNodeWithKind(node, 291 /* EnumMember */)) {
80937                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0;
80938                 }
80939                 if (diagnosticMessage) {
80940                     var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 40 /* MinusToken */;
80941                     var literal = (withMinus ? "-" : "") + "0o" + node.text;
80942                     return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal);
80943                 }
80944             }
80945             // Realism (size) checking
80946             checkNumericLiteralValueSize(node);
80947             return false;
80948         }
80949         function checkNumericLiteralValueSize(node) {
80950             // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint
80951             // Literals with 15 or fewer characters aren't long enough to reach past 2^53 - 1
80952             // Fractional numbers (e.g. 9000000000000000.001) are inherently imprecise anyway
80953             if (node.numericLiteralFlags & 16 /* Scientific */ || node.text.length <= 15 || node.text.indexOf(".") !== -1) {
80954                 return;
80955             }
80956             // We can't rely on the runtime to accurately store and compare extremely large numeric values
80957             // Even for internal use, we use getTextOfNode: https://github.com/microsoft/TypeScript/issues/33298
80958             // Thus, if the runtime claims a too-large number is lower than Number.MAX_SAFE_INTEGER,
80959             // it's likely addition operations on it will fail too
80960             var apparentValue = +ts.getTextOfNode(node);
80961             if (apparentValue <= Math.pow(2, 53) - 1 && apparentValue + 1 > apparentValue) {
80962                 return;
80963             }
80964             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));
80965         }
80966         function checkGrammarBigIntLiteral(node) {
80967             var literalType = ts.isLiteralTypeNode(node.parent) ||
80968                 ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
80969             if (!literalType) {
80970                 if (languageVersion < 7 /* ES2020 */) {
80971                     if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ES2020)) {
80972                         return true;
80973                     }
80974                 }
80975             }
80976             return false;
80977         }
80978         function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) {
80979             var sourceFile = ts.getSourceFileOfNode(node);
80980             if (!hasParseDiagnostics(sourceFile)) {
80981                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
80982                 diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2));
80983                 return true;
80984             }
80985             return false;
80986         }
80987         function getAmbientModules() {
80988             if (!ambientModulesCache) {
80989                 ambientModulesCache = [];
80990                 globals.forEach(function (global, sym) {
80991                     // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module.
80992                     if (ambientModuleSymbolRegex.test(sym)) {
80993                         ambientModulesCache.push(global);
80994                     }
80995                 });
80996             }
80997             return ambientModulesCache;
80998         }
80999         function checkGrammarImportClause(node) {
81000             if (node.isTypeOnly && node.name && node.namedBindings) {
81001                 return grammarErrorOnNode(node, ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both);
81002             }
81003             return false;
81004         }
81005         function checkGrammarImportCallExpression(node) {
81006             if (moduleKind === ts.ModuleKind.ES2015) {
81007                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd);
81008             }
81009             if (node.typeArguments) {
81010                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
81011             }
81012             var nodeArguments = node.arguments;
81013             if (nodeArguments.length !== 1) {
81014                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument);
81015             }
81016             checkGrammarForDisallowedTrailingComma(nodeArguments);
81017             // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
81018             // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
81019             if (ts.isSpreadElement(nodeArguments[0])) {
81020                 return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element);
81021             }
81022             return false;
81023         }
81024         function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
81025             var sourceObjectFlags = ts.getObjectFlags(source);
81026             if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) {
81027                 return ts.find(unionTarget.types, function (target) {
81028                     if (target.flags & 524288 /* Object */) {
81029                         var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target);
81030                         if (overlapObjFlags & 4 /* Reference */) {
81031                             return source.target === target.target;
81032                         }
81033                         if (overlapObjFlags & 16 /* Anonymous */) {
81034                             return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
81035                         }
81036                     }
81037                     return false;
81038                 });
81039             }
81040         }
81041         function findBestTypeForObjectLiteral(source, unionTarget) {
81042             if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) {
81043                 return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); });
81044             }
81045         }
81046         function findBestTypeForInvokable(source, unionTarget) {
81047             var signatureKind = 0 /* Call */;
81048             var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 ||
81049                 (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
81050             if (hasSignatures) {
81051                 return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
81052             }
81053         }
81054         function findMostOverlappyType(source, unionTarget) {
81055             var bestMatch;
81056             var matchingCount = 0;
81057             for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
81058                 var target = _a[_i];
81059                 var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
81060                 if (overlap.flags & 4194304 /* Index */) {
81061                     // perfect overlap of keys
81062                     bestMatch = target;
81063                     matchingCount = Infinity;
81064                 }
81065                 else if (overlap.flags & 1048576 /* Union */) {
81066                     // We only want to account for literal types otherwise.
81067                     // If we have a union of index types, it seems likely that we
81068                     // needed to elaborate between two generic mapped types anyway.
81069                     var len = ts.length(ts.filter(overlap.types, isUnitType));
81070                     if (len >= matchingCount) {
81071                         bestMatch = target;
81072                         matchingCount = len;
81073                     }
81074                 }
81075                 else if (isUnitType(overlap) && 1 >= matchingCount) {
81076                     bestMatch = target;
81077                     matchingCount = 1;
81078                 }
81079             }
81080             return bestMatch;
81081         }
81082         function filterPrimitivesIfContainsNonPrimitive(type) {
81083             if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */)) {
81084                 var result = filterType(type, function (t) { return !(t.flags & 131068 /* Primitive */); });
81085                 if (!(result.flags & 131072 /* Never */)) {
81086                     return result;
81087                 }
81088             }
81089             return type;
81090         }
81091         // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
81092         function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) {
81093             if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) {
81094                 var sourceProperties = getPropertiesOfType(source);
81095                 if (sourceProperties) {
81096                     var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
81097                     if (sourcePropertiesFiltered) {
81098                         return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial);
81099                     }
81100                 }
81101             }
81102             return undefined;
81103         }
81104     }
81105     ts.createTypeChecker = createTypeChecker;
81106     function isNotAccessor(declaration) {
81107         // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks
81108         return !ts.isAccessor(declaration);
81109     }
81110     function isNotOverload(declaration) {
81111         return (declaration.kind !== 251 /* FunctionDeclaration */ && declaration.kind !== 165 /* MethodDeclaration */) ||
81112             !!declaration.body;
81113     }
81114     /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */
81115     function isDeclarationNameOrImportPropertyName(name) {
81116         switch (name.parent.kind) {
81117             case 265 /* ImportSpecifier */:
81118             case 270 /* ExportSpecifier */:
81119                 return ts.isIdentifier(name);
81120             default:
81121                 return ts.isDeclarationName(name);
81122         }
81123     }
81124     function isSomeImportDeclaration(decl) {
81125         switch (decl.kind) {
81126             case 262 /* ImportClause */: // For default import
81127             case 260 /* ImportEqualsDeclaration */:
81128             case 263 /* NamespaceImport */:
81129             case 265 /* ImportSpecifier */: // For rename import `x as y`
81130                 return true;
81131             case 78 /* Identifier */:
81132                 // For regular import, `decl` is an Identifier under the ImportSpecifier.
81133                 return decl.parent.kind === 265 /* ImportSpecifier */;
81134             default:
81135                 return false;
81136         }
81137     }
81138     var JsxNames;
81139     (function (JsxNames) {
81140         JsxNames.JSX = "JSX";
81141         JsxNames.IntrinsicElements = "IntrinsicElements";
81142         JsxNames.ElementClass = "ElementClass";
81143         JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support
81144         JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
81145         JsxNames.Element = "Element";
81146         JsxNames.IntrinsicAttributes = "IntrinsicAttributes";
81147         JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes";
81148         JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes";
81149     })(JsxNames || (JsxNames = {}));
81150     function getIterationTypesKeyFromIterationTypeKind(typeKind) {
81151         switch (typeKind) {
81152             case 0 /* Yield */: return "yieldType";
81153             case 1 /* Return */: return "returnType";
81154             case 2 /* Next */: return "nextType";
81155         }
81156     }
81157     function signatureHasRestParameter(s) {
81158         return !!(s.flags & 1 /* HasRestParameter */);
81159     }
81160     ts.signatureHasRestParameter = signatureHasRestParameter;
81161     function signatureHasLiteralTypes(s) {
81162         return !!(s.flags & 2 /* HasLiteralTypes */);
81163     }
81164     ts.signatureHasLiteralTypes = signatureHasLiteralTypes;
81165 })(ts || (ts = {}));
81166 var ts;
81167 (function (ts) {
81168     var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration);
81169     function visitNode(node, visitor, test, lift) {
81170         if (node === undefined || visitor === undefined) {
81171             return node;
81172         }
81173         var visited = visitor(node);
81174         if (visited === node) {
81175             return node;
81176         }
81177         var visitedNode;
81178         if (visited === undefined) {
81179             return undefined;
81180         }
81181         else if (ts.isArray(visited)) {
81182             visitedNode = (lift || extractSingleNode)(visited);
81183         }
81184         else {
81185             visitedNode = visited;
81186         }
81187         ts.Debug.assertNode(visitedNode, test);
81188         return visitedNode;
81189     }
81190     ts.visitNode = visitNode;
81191     /**
81192      * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
81193      *
81194      * @param nodes The NodeArray to visit.
81195      * @param visitor The callback used to visit a Node.
81196      * @param test A node test to execute for each node.
81197      * @param start An optional value indicating the starting offset at which to start visiting.
81198      * @param count An optional value indicating the maximum number of nodes to visit.
81199      */
81200     function visitNodes(nodes, visitor, test, start, count) {
81201         if (nodes === undefined || visitor === undefined) {
81202             return nodes;
81203         }
81204         var updated;
81205         // Ensure start and count have valid values
81206         var length = nodes.length;
81207         if (start === undefined || start < 0) {
81208             start = 0;
81209         }
81210         if (count === undefined || count > length - start) {
81211             count = length - start;
81212         }
81213         var hasTrailingComma;
81214         var pos = -1;
81215         var end = -1;
81216         if (start > 0 || count < length) {
81217             // If we are not visiting all of the original nodes, we must always create a new array.
81218             // Since this is a fragment of a node array, we do not copy over the previous location
81219             // and will only copy over `hasTrailingComma` if we are including the last element.
81220             updated = [];
81221             hasTrailingComma = nodes.hasTrailingComma && start + count === length;
81222         }
81223         // Visit each original node.
81224         for (var i = 0; i < count; i++) {
81225             var node = nodes[i + start];
81226             var visited = node !== undefined ? visitor(node) : undefined;
81227             if (updated !== undefined || visited === undefined || visited !== node) {
81228                 if (updated === undefined) {
81229                     // Ensure we have a copy of `nodes`, up to the current index.
81230                     updated = nodes.slice(0, i);
81231                     hasTrailingComma = nodes.hasTrailingComma;
81232                     pos = nodes.pos;
81233                     end = nodes.end;
81234                 }
81235                 if (visited) {
81236                     if (ts.isArray(visited)) {
81237                         for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
81238                             var visitedNode = visited_1[_i];
81239                             void ts.Debug.assertNode(visitedNode, test);
81240                             updated.push(visitedNode);
81241                         }
81242                     }
81243                     else {
81244                         void ts.Debug.assertNode(visited, test);
81245                         updated.push(visited);
81246                     }
81247                 }
81248             }
81249         }
81250         if (updated) {
81251             // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory.
81252             var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma);
81253             ts.setTextRangePosEnd(updatedArray, pos, end);
81254             return updatedArray;
81255         }
81256         return nodes;
81257     }
81258     ts.visitNodes = visitNodes;
81259     /**
81260      * Starts a new lexical environment and visits a statement list, ending the lexical environment
81261      * and merging hoisted declarations upon completion.
81262      */
81263     function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict, nodesVisitor) {
81264         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
81265         context.startLexicalEnvironment();
81266         statements = nodesVisitor(statements, visitor, ts.isStatement, start);
81267         if (ensureUseStrict)
81268             statements = context.factory.ensureUseStrict(statements);
81269         return ts.factory.mergeLexicalEnvironment(statements, context.endLexicalEnvironment());
81270     }
81271     ts.visitLexicalEnvironment = visitLexicalEnvironment;
81272     function visitParameterList(nodes, visitor, context, nodesVisitor) {
81273         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
81274         var updated;
81275         context.startLexicalEnvironment();
81276         if (nodes) {
81277             context.setLexicalEnvironmentFlags(1 /* InParameters */, true);
81278             updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration);
81279             // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an
81280             // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression
81281             // that we might transform that introduces a temporary variable would fail as the temporary variable
81282             // exists in a different lexical scope. To address this, we move any binding patterns and initializers
81283             // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list
81284             // when the emit target is greater than ES2015.
81285             if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ &&
81286                 ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) {
81287                 updated = addDefaultValueAssignmentsIfNeeded(updated, context);
81288             }
81289             context.setLexicalEnvironmentFlags(1 /* InParameters */, false);
81290         }
81291         context.suspendLexicalEnvironment();
81292         return updated;
81293     }
81294     ts.visitParameterList = visitParameterList;
81295     function addDefaultValueAssignmentsIfNeeded(parameters, context) {
81296         var result;
81297         for (var i = 0; i < parameters.length; i++) {
81298             var parameter = parameters[i];
81299             var updated = addDefaultValueAssignmentIfNeeded(parameter, context);
81300             if (result || updated !== parameter) {
81301                 if (!result)
81302                     result = parameters.slice(0, i);
81303                 result[i] = updated;
81304             }
81305         }
81306         if (result) {
81307             return ts.setTextRange(context.factory.createNodeArray(result, parameters.hasTrailingComma), parameters);
81308         }
81309         return parameters;
81310     }
81311     function addDefaultValueAssignmentIfNeeded(parameter, context) {
81312         // A rest parameter cannot have a binding pattern or an initializer,
81313         // so let's just ignore it.
81314         return parameter.dotDotDotToken ? parameter :
81315             ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) :
81316                 parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) :
81317                     parameter;
81318     }
81319     function addDefaultValueAssignmentForBindingPattern(parameter, context) {
81320         var factory = context.factory;
81321         context.addInitializationStatement(factory.createVariableStatement(
81322         /*modifiers*/ undefined, factory.createVariableDeclarationList([
81323             factory.createVariableDeclaration(parameter.name, 
81324             /*exclamationToken*/ undefined, parameter.type, parameter.initializer ?
81325                 factory.createConditionalExpression(factory.createStrictEquality(factory.getGeneratedNameForNode(parameter), factory.createVoidZero()), 
81326                 /*questionToken*/ undefined, parameter.initializer, 
81327                 /*colonToken*/ undefined, factory.getGeneratedNameForNode(parameter)) :
81328                 factory.getGeneratedNameForNode(parameter)),
81329         ])));
81330         return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, 
81331         /*initializer*/ undefined);
81332     }
81333     function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) {
81334         var factory = context.factory;
81335         context.addInitializationStatement(factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([
81336             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 */))
81337         ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)));
81338         return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, 
81339         /*initializer*/ undefined);
81340     }
81341     function visitFunctionBody(node, visitor, context, nodeVisitor) {
81342         if (nodeVisitor === void 0) { nodeVisitor = visitNode; }
81343         context.resumeLexicalEnvironment();
81344         var updated = nodeVisitor(node, visitor, ts.isConciseBody);
81345         var declarations = context.endLexicalEnvironment();
81346         if (ts.some(declarations)) {
81347             if (!updated) {
81348                 return context.factory.createBlock(declarations);
81349             }
81350             var block = context.factory.converters.convertToFunctionBlock(updated);
81351             var statements = ts.factory.mergeLexicalEnvironment(block.statements, declarations);
81352             return context.factory.updateBlock(block, statements);
81353         }
81354         return updated;
81355     }
81356     ts.visitFunctionBody = visitFunctionBody;
81357     function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor, nodeVisitor) {
81358         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
81359         if (nodeVisitor === void 0) { nodeVisitor = visitNode; }
81360         if (node === undefined) {
81361             return undefined;
81362         }
81363         var kind = node.kind;
81364         // No need to visit nodes with no children.
81365         if ((kind > 0 /* FirstToken */ && kind <= 156 /* LastToken */) || kind === 187 /* ThisType */) {
81366             return node;
81367         }
81368         var factory = context.factory;
81369         switch (kind) {
81370             // Names
81371             case 78 /* Identifier */:
81372                 return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration));
81373             case 157 /* QualifiedName */:
81374                 return factory.updateQualifiedName(node, nodeVisitor(node.left, visitor, ts.isEntityName), nodeVisitor(node.right, visitor, ts.isIdentifier));
81375             case 158 /* ComputedPropertyName */:
81376                 return factory.updateComputedPropertyName(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81377             // Signature elements
81378             case 159 /* TypeParameter */:
81379                 return factory.updateTypeParameterDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode));
81380             case 160 /* Parameter */:
81381                 return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression));
81382             case 161 /* Decorator */:
81383                 return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81384             // Type elements
81385             case 162 /* PropertySignature */:
81386                 return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode));
81387             case 163 /* PropertyDeclaration */:
81388                 return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), 
81389                 // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too
81390                 nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression));
81391             case 164 /* MethodSignature */:
81392                 return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
81393             case 165 /* MethodDeclaration */:
81394                 return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor));
81395             case 166 /* Constructor */:
81396                 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));
81397             case 167 /* GetAccessor */:
81398                 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));
81399             case 168 /* SetAccessor */:
81400                 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));
81401             case 169 /* CallSignature */:
81402                 return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
81403             case 170 /* ConstructSignature */:
81404                 return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
81405             case 171 /* IndexSignature */:
81406                 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));
81407             // Types
81408             case 172 /* TypePredicate */:
81409                 return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor), nodeVisitor(node.parameterName, visitor), nodeVisitor(node.type, visitor, ts.isTypeNode));
81410             case 173 /* TypeReference */:
81411                 return factory.updateTypeReferenceNode(node, nodeVisitor(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
81412             case 174 /* FunctionType */:
81413                 return factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
81414             case 175 /* ConstructorType */:
81415                 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));
81416             case 176 /* TypeQuery */:
81417                 return factory.updateTypeQueryNode(node, nodeVisitor(node.exprName, visitor, ts.isEntityName));
81418             case 177 /* TypeLiteral */:
81419                 return factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement));
81420             case 178 /* ArrayType */:
81421                 return factory.updateArrayTypeNode(node, nodeVisitor(node.elementType, visitor, ts.isTypeNode));
81422             case 179 /* TupleType */:
81423                 return factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, ts.isTypeNode));
81424             case 180 /* OptionalType */:
81425                 return factory.updateOptionalTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
81426             case 181 /* RestType */:
81427                 return factory.updateRestTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
81428             case 182 /* UnionType */:
81429                 return factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
81430             case 183 /* IntersectionType */:
81431                 return factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
81432             case 184 /* ConditionalType */:
81433                 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));
81434             case 185 /* InferType */:
81435                 return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration));
81436             case 195 /* ImportType */:
81437                 return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf);
81438             case 192 /* NamedTupleMember */:
81439                 return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode));
81440             case 186 /* ParenthesizedType */:
81441                 return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
81442             case 188 /* TypeOperator */:
81443                 return factory.updateTypeOperatorNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
81444             case 189 /* IndexedAccessType */:
81445                 return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode));
81446             case 190 /* MappedType */:
81447                 return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode));
81448             case 191 /* LiteralType */:
81449                 return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression));
81450             case 193 /* TemplateLiteralType */:
81451                 return factory.updateTemplateLiteralType(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateLiteralTypeSpan));
81452             case 194 /* TemplateLiteralTypeSpan */:
81453                 return factory.updateTemplateLiteralTypeSpan(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
81454             // Binding patterns
81455             case 196 /* ObjectBindingPattern */:
81456                 return factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement));
81457             case 197 /* ArrayBindingPattern */:
81458                 return factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement));
81459             case 198 /* BindingElement */:
81460                 return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression));
81461             // Expression
81462             case 199 /* ArrayLiteralExpression */:
81463                 return factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression));
81464             case 200 /* ObjectLiteralExpression */:
81465                 return factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike));
81466             case 201 /* PropertyAccessExpression */:
81467                 if (node.flags & 32 /* OptionalChain */) {
81468                     return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier));
81469                 }
81470                 return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isIdentifierOrPrivateIdentifier));
81471             case 202 /* ElementAccessExpression */:
81472                 if (node.flags & 32 /* OptionalChain */) {
81473                     return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression));
81474                 }
81475                 return factory.updateElementAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.argumentExpression, visitor, ts.isExpression));
81476             case 203 /* CallExpression */:
81477                 if (node.flags & 32 /* OptionalChain */) {
81478                     return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
81479                 }
81480                 return factory.updateCallExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
81481             case 204 /* NewExpression */:
81482                 return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
81483             case 205 /* TaggedTemplateExpression */:
81484                 return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), nodeVisitor(node.template, visitor, ts.isTemplateLiteral));
81485             case 206 /* TypeAssertionExpression */:
81486                 return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression));
81487             case 207 /* ParenthesizedExpression */:
81488                 return factory.updateParenthesizedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81489             case 208 /* FunctionExpression */:
81490                 return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor));
81491             case 209 /* ArrowFunction */:
81492                 return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isToken), visitFunctionBody(node.body, visitor, context, nodeVisitor));
81493             case 210 /* DeleteExpression */:
81494                 return factory.updateDeleteExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81495             case 211 /* TypeOfExpression */:
81496                 return factory.updateTypeOfExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81497             case 212 /* VoidExpression */:
81498                 return factory.updateVoidExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81499             case 213 /* AwaitExpression */:
81500                 return factory.updateAwaitExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81501             case 214 /* PrefixUnaryExpression */:
81502                 return factory.updatePrefixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression));
81503             case 215 /* PostfixUnaryExpression */:
81504                 return factory.updatePostfixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression));
81505             case 216 /* BinaryExpression */:
81506                 return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isToken), nodeVisitor(node.right, visitor, ts.isExpression));
81507             case 217 /* ConditionalExpression */:
81508                 return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression));
81509             case 218 /* TemplateExpression */:
81510                 return factory.updateTemplateExpression(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan));
81511             case 219 /* YieldExpression */:
81512                 return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.expression, visitor, ts.isExpression));
81513             case 220 /* SpreadElement */:
81514                 return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81515             case 221 /* ClassExpression */:
81516                 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));
81517             case 223 /* ExpressionWithTypeArguments */:
81518                 return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
81519             case 224 /* AsExpression */:
81520                 return factory.updateAsExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.type, visitor, ts.isTypeNode));
81521             case 225 /* NonNullExpression */:
81522                 if (node.flags & 32 /* OptionalChain */) {
81523                     return factory.updateNonNullChain(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81524                 }
81525                 return factory.updateNonNullExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81526             case 226 /* MetaProperty */:
81527                 return factory.updateMetaProperty(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
81528             // Misc
81529             case 228 /* TemplateSpan */:
81530                 return factory.updateTemplateSpan(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
81531             // Element
81532             case 230 /* Block */:
81533                 return factory.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
81534             case 232 /* VariableStatement */:
81535                 return factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.declarationList, visitor, ts.isVariableDeclarationList));
81536             case 233 /* ExpressionStatement */:
81537                 return factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81538             case 234 /* IfStatement */:
81539                 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));
81540             case 235 /* DoStatement */:
81541                 return factory.updateDoStatement(node, nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.expression, visitor, ts.isExpression));
81542             case 236 /* WhileStatement */:
81543                 return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
81544             case 237 /* ForStatement */:
81545                 return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
81546             case 238 /* ForInStatement */:
81547                 return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
81548             case 239 /* ForOfStatement */:
81549                 return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isToken), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
81550             case 240 /* ContinueStatement */:
81551                 return factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier));
81552             case 241 /* BreakStatement */:
81553                 return factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier));
81554             case 242 /* ReturnStatement */:
81555                 return factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81556             case 243 /* WithStatement */:
81557                 return factory.updateWithStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
81558             case 244 /* SwitchStatement */:
81559                 return factory.updateSwitchStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.caseBlock, visitor, ts.isCaseBlock));
81560             case 245 /* LabeledStatement */:
81561                 return factory.updateLabeledStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
81562             case 246 /* ThrowStatement */:
81563                 return factory.updateThrowStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81564             case 247 /* TryStatement */:
81565                 return factory.updateTryStatement(node, nodeVisitor(node.tryBlock, visitor, ts.isBlock), nodeVisitor(node.catchClause, visitor, ts.isCatchClause), nodeVisitor(node.finallyBlock, visitor, ts.isBlock));
81566             case 249 /* VariableDeclaration */:
81567                 return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression));
81568             case 250 /* VariableDeclarationList */:
81569                 return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration));
81570             case 251 /* FunctionDeclaration */:
81571                 return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor));
81572             case 252 /* ClassDeclaration */:
81573                 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));
81574             case 253 /* InterfaceDeclaration */:
81575                 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));
81576             case 254 /* TypeAliasDeclaration */:
81577                 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));
81578             case 255 /* EnumDeclaration */:
81579                 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));
81580             case 256 /* ModuleDeclaration */:
81581                 return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.body, visitor, ts.isModuleBody));
81582             case 257 /* ModuleBlock */:
81583                 return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
81584             case 258 /* CaseBlock */:
81585                 return factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause));
81586             case 259 /* NamespaceExportDeclaration */:
81587                 return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
81588             case 260 /* ImportEqualsDeclaration */:
81589                 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));
81590             case 261 /* ImportDeclaration */:
81591                 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));
81592             case 262 /* ImportClause */:
81593                 return factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings));
81594             case 263 /* NamespaceImport */:
81595                 return factory.updateNamespaceImport(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
81596             case 269 /* NamespaceExport */:
81597                 return factory.updateNamespaceExport(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
81598             case 264 /* NamedImports */:
81599                 return factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier));
81600             case 265 /* ImportSpecifier */:
81601                 return factory.updateImportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier));
81602             case 266 /* ExportAssignment */:
81603                 return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression));
81604             case 267 /* ExportDeclaration */:
81605                 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));
81606             case 268 /* NamedExports */:
81607                 return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier));
81608             case 270 /* ExportSpecifier */:
81609                 return factory.updateExportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier));
81610             // Module references
81611             case 272 /* ExternalModuleReference */:
81612                 return factory.updateExternalModuleReference(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81613             // JSX
81614             case 273 /* JsxElement */:
81615                 return factory.updateJsxElement(node, nodeVisitor(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingElement, visitor, ts.isJsxClosingElement));
81616             case 274 /* JsxSelfClosingElement */:
81617                 return factory.updateJsxSelfClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes));
81618             case 275 /* JsxOpeningElement */:
81619                 return factory.updateJsxOpeningElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes));
81620             case 276 /* JsxClosingElement */:
81621                 return factory.updateJsxClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression));
81622             case 277 /* JsxFragment */:
81623                 return factory.updateJsxFragment(node, nodeVisitor(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingFragment, visitor, ts.isJsxClosingFragment));
81624             case 280 /* JsxAttribute */:
81625                 return factory.updateJsxAttribute(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
81626             case 281 /* JsxAttributes */:
81627                 return factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike));
81628             case 282 /* JsxSpreadAttribute */:
81629                 return factory.updateJsxSpreadAttribute(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81630             case 283 /* JsxExpression */:
81631                 return factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81632             // Clauses
81633             case 284 /* CaseClause */:
81634                 return factory.updateCaseClause(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement));
81635             case 285 /* DefaultClause */:
81636                 return factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement));
81637             case 286 /* HeritageClause */:
81638                 return factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments));
81639             case 287 /* CatchClause */:
81640                 return factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, ts.isVariableDeclaration), nodeVisitor(node.block, visitor, ts.isBlock));
81641             // Property assignments
81642             case 288 /* PropertyAssignment */:
81643                 return factory.updatePropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression));
81644             case 289 /* ShorthandPropertyAssignment */:
81645                 return factory.updateShorthandPropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.objectAssignmentInitializer, visitor, ts.isExpression));
81646             case 290 /* SpreadAssignment */:
81647                 return factory.updateSpreadAssignment(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81648             // Enum
81649             case 291 /* EnumMember */:
81650                 return factory.updateEnumMember(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression));
81651             // Top-level nodes
81652             case 297 /* SourceFile */:
81653                 return factory.updateSourceFile(node, visitLexicalEnvironment(node.statements, visitor, context));
81654             // Transformation nodes
81655             case 336 /* PartiallyEmittedExpression */:
81656                 return factory.updatePartiallyEmittedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
81657             case 337 /* CommaListExpression */:
81658                 return factory.updateCommaListExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression));
81659             default:
81660                 // No need to visit nodes with no children.
81661                 return node;
81662         }
81663     }
81664     ts.visitEachChild = visitEachChild;
81665     /**
81666      * Extracts the single node from a NodeArray.
81667      *
81668      * @param nodes The NodeArray.
81669      */
81670     function extractSingleNode(nodes) {
81671         ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
81672         return ts.singleOrUndefined(nodes);
81673     }
81674 })(ts || (ts = {}));
81675 /* @internal */
81676 var ts;
81677 (function (ts) {
81678     function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) {
81679         var _a = generatorOptions.extendedDiagnostics
81680             ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap")
81681             : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit;
81682         // Current source map file and its index in the sources list
81683         var rawSources = [];
81684         var sources = [];
81685         var sourceToSourceIndexMap = new ts.Map();
81686         var sourcesContent;
81687         var names = [];
81688         var nameToNameIndexMap;
81689         var mappings = "";
81690         // Last recorded and encoded mappings
81691         var lastGeneratedLine = 0;
81692         var lastGeneratedCharacter = 0;
81693         var lastSourceIndex = 0;
81694         var lastSourceLine = 0;
81695         var lastSourceCharacter = 0;
81696         var lastNameIndex = 0;
81697         var hasLast = false;
81698         var pendingGeneratedLine = 0;
81699         var pendingGeneratedCharacter = 0;
81700         var pendingSourceIndex = 0;
81701         var pendingSourceLine = 0;
81702         var pendingSourceCharacter = 0;
81703         var pendingNameIndex = 0;
81704         var hasPending = false;
81705         var hasPendingSource = false;
81706         var hasPendingName = false;
81707         return {
81708             getSources: function () { return rawSources; },
81709             addSource: addSource,
81710             setSourceContent: setSourceContent,
81711             addName: addName,
81712             addMapping: addMapping,
81713             appendSourceMap: appendSourceMap,
81714             toJSON: toJSON,
81715             toString: function () { return JSON.stringify(toJSON()); }
81716         };
81717         function addSource(fileName) {
81718             enter();
81719             var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
81720             /*isAbsolutePathAnUrl*/ true);
81721             var sourceIndex = sourceToSourceIndexMap.get(source);
81722             if (sourceIndex === undefined) {
81723                 sourceIndex = sources.length;
81724                 sources.push(source);
81725                 rawSources.push(fileName);
81726                 sourceToSourceIndexMap.set(source, sourceIndex);
81727             }
81728             exit();
81729             return sourceIndex;
81730         }
81731         /* eslint-disable boolean-trivia, no-null/no-null */
81732         function setSourceContent(sourceIndex, content) {
81733             enter();
81734             if (content !== null) {
81735                 if (!sourcesContent)
81736                     sourcesContent = [];
81737                 while (sourcesContent.length < sourceIndex) {
81738                     sourcesContent.push(null);
81739                 }
81740                 sourcesContent[sourceIndex] = content;
81741             }
81742             exit();
81743         }
81744         /* eslint-enable boolean-trivia, no-null/no-null */
81745         function addName(name) {
81746             enter();
81747             if (!nameToNameIndexMap)
81748                 nameToNameIndexMap = new ts.Map();
81749             var nameIndex = nameToNameIndexMap.get(name);
81750             if (nameIndex === undefined) {
81751                 nameIndex = names.length;
81752                 names.push(name);
81753                 nameToNameIndexMap.set(name, nameIndex);
81754             }
81755             exit();
81756             return nameIndex;
81757         }
81758         function isNewGeneratedPosition(generatedLine, generatedCharacter) {
81759             return !hasPending
81760                 || pendingGeneratedLine !== generatedLine
81761                 || pendingGeneratedCharacter !== generatedCharacter;
81762         }
81763         function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) {
81764             return sourceIndex !== undefined
81765                 && sourceLine !== undefined
81766                 && sourceCharacter !== undefined
81767                 && pendingSourceIndex === sourceIndex
81768                 && (pendingSourceLine > sourceLine
81769                     || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter);
81770         }
81771         function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) {
81772             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
81773             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
81774             ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative");
81775             ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative");
81776             ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative");
81777             enter();
81778             // If this location wasn't recorded or the location in source is going backwards, record the mapping
81779             if (isNewGeneratedPosition(generatedLine, generatedCharacter) ||
81780                 isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) {
81781                 commitPendingMapping();
81782                 pendingGeneratedLine = generatedLine;
81783                 pendingGeneratedCharacter = generatedCharacter;
81784                 hasPendingSource = false;
81785                 hasPendingName = false;
81786                 hasPending = true;
81787             }
81788             if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) {
81789                 pendingSourceIndex = sourceIndex;
81790                 pendingSourceLine = sourceLine;
81791                 pendingSourceCharacter = sourceCharacter;
81792                 hasPendingSource = true;
81793                 if (nameIndex !== undefined) {
81794                     pendingNameIndex = nameIndex;
81795                     hasPendingName = true;
81796                 }
81797             }
81798             exit();
81799         }
81800         function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
81801             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
81802             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
81803             enter();
81804             // First, decode the old component sourcemap
81805             var sourceIndexToNewSourceIndexMap = [];
81806             var nameIndexToNewNameIndexMap;
81807             var mappingIterator = decodeMappings(map.mappings);
81808             for (var iterResult = mappingIterator.next(); !iterResult.done; iterResult = mappingIterator.next()) {
81809                 var raw = iterResult.value;
81810                 if (end && (raw.generatedLine > end.line ||
81811                     (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
81812                     break;
81813                 }
81814                 if (start && (raw.generatedLine < start.line ||
81815                     (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
81816                     continue;
81817                 }
81818                 // Then reencode all the updated mappings into the overall map
81819                 var newSourceIndex = void 0;
81820                 var newSourceLine = void 0;
81821                 var newSourceCharacter = void 0;
81822                 var newNameIndex = void 0;
81823                 if (raw.sourceIndex !== undefined) {
81824                     newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex];
81825                     if (newSourceIndex === undefined) {
81826                         // Apply offsets to each position and fixup source entries
81827                         var rawPath = map.sources[raw.sourceIndex];
81828                         var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath;
81829                         var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath);
81830                         sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath);
81831                         if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") {
81832                             setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]);
81833                         }
81834                     }
81835                     newSourceLine = raw.sourceLine;
81836                     newSourceCharacter = raw.sourceCharacter;
81837                     if (map.names && raw.nameIndex !== undefined) {
81838                         if (!nameIndexToNewNameIndexMap)
81839                             nameIndexToNewNameIndexMap = [];
81840                         newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex];
81841                         if (newNameIndex === undefined) {
81842                             nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]);
81843                         }
81844                     }
81845                 }
81846                 var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
81847                 var newGeneratedLine = rawGeneratedLine + generatedLine;
81848                 var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
81849                 var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
81850                 addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
81851             }
81852             exit();
81853         }
81854         function shouldCommitMapping() {
81855             return !hasLast
81856                 || lastGeneratedLine !== pendingGeneratedLine
81857                 || lastGeneratedCharacter !== pendingGeneratedCharacter
81858                 || lastSourceIndex !== pendingSourceIndex
81859                 || lastSourceLine !== pendingSourceLine
81860                 || lastSourceCharacter !== pendingSourceCharacter
81861                 || lastNameIndex !== pendingNameIndex;
81862         }
81863         function commitPendingMapping() {
81864             if (!hasPending || !shouldCommitMapping()) {
81865                 return;
81866             }
81867             enter();
81868             // Line/Comma delimiters
81869             if (lastGeneratedLine < pendingGeneratedLine) {
81870                 // Emit line delimiters
81871                 do {
81872                     mappings += ";";
81873                     lastGeneratedLine++;
81874                     lastGeneratedCharacter = 0;
81875                 } while (lastGeneratedLine < pendingGeneratedLine);
81876             }
81877             else {
81878                 ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack");
81879                 // Emit comma to separate the entry
81880                 if (hasLast) {
81881                     mappings += ",";
81882                 }
81883             }
81884             // 1. Relative generated character
81885             mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter);
81886             lastGeneratedCharacter = pendingGeneratedCharacter;
81887             if (hasPendingSource) {
81888                 // 2. Relative sourceIndex
81889                 mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex);
81890                 lastSourceIndex = pendingSourceIndex;
81891                 // 3. Relative source line
81892                 mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine);
81893                 lastSourceLine = pendingSourceLine;
81894                 // 4. Relative source character
81895                 mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter);
81896                 lastSourceCharacter = pendingSourceCharacter;
81897                 if (hasPendingName) {
81898                     // 5. Relative nameIndex
81899                     mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex);
81900                     lastNameIndex = pendingNameIndex;
81901                 }
81902             }
81903             hasLast = true;
81904             exit();
81905         }
81906         function toJSON() {
81907             commitPendingMapping();
81908             return {
81909                 version: 3,
81910                 file: file,
81911                 sourceRoot: sourceRoot,
81912                 sources: sources,
81913                 names: names,
81914                 mappings: mappings,
81915                 sourcesContent: sourcesContent,
81916             };
81917         }
81918     }
81919     ts.createSourceMapGenerator = createSourceMapGenerator;
81920     // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M])
81921     var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/;
81922     var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
81923     function getLineInfo(text, lineStarts) {
81924         return {
81925             getLineCount: function () { return lineStarts.length; },
81926             getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); }
81927         };
81928     }
81929     ts.getLineInfo = getLineInfo;
81930     /**
81931      * Tries to find the sourceMappingURL comment at the end of a file.
81932      */
81933     function tryGetSourceMappingURL(lineInfo) {
81934         for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) {
81935             var line = lineInfo.getLineText(index);
81936             var comment = sourceMapCommentRegExp.exec(line);
81937             if (comment) {
81938                 return comment[1];
81939             }
81940             // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file
81941             else if (!line.match(whitespaceOrMapCommentRegExp)) {
81942                 break;
81943             }
81944         }
81945     }
81946     ts.tryGetSourceMappingURL = tryGetSourceMappingURL;
81947     /* eslint-disable no-null/no-null */
81948     function isStringOrNull(x) {
81949         return typeof x === "string" || x === null;
81950     }
81951     function isRawSourceMap(x) {
81952         return x !== null
81953             && typeof x === "object"
81954             && x.version === 3
81955             && typeof x.file === "string"
81956             && typeof x.mappings === "string"
81957             && ts.isArray(x.sources) && ts.every(x.sources, ts.isString)
81958             && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string")
81959             && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull))
81960             && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString));
81961     }
81962     ts.isRawSourceMap = isRawSourceMap;
81963     /* eslint-enable no-null/no-null */
81964     function tryParseRawSourceMap(text) {
81965         try {
81966             var parsed = JSON.parse(text);
81967             if (isRawSourceMap(parsed)) {
81968                 return parsed;
81969             }
81970         }
81971         catch (_a) {
81972             // empty
81973         }
81974         return undefined;
81975     }
81976     ts.tryParseRawSourceMap = tryParseRawSourceMap;
81977     function decodeMappings(mappings) {
81978         var done = false;
81979         var pos = 0;
81980         var generatedLine = 0;
81981         var generatedCharacter = 0;
81982         var sourceIndex = 0;
81983         var sourceLine = 0;
81984         var sourceCharacter = 0;
81985         var nameIndex = 0;
81986         var error;
81987         return {
81988             get pos() { return pos; },
81989             get error() { return error; },
81990             get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); },
81991             next: function () {
81992                 while (!done && pos < mappings.length) {
81993                     var ch = mappings.charCodeAt(pos);
81994                     if (ch === 59 /* semicolon */) {
81995                         // new line
81996                         generatedLine++;
81997                         generatedCharacter = 0;
81998                         pos++;
81999                         continue;
82000                     }
82001                     if (ch === 44 /* comma */) {
82002                         // Next entry is on same line - no action needed
82003                         pos++;
82004                         continue;
82005                     }
82006                     var hasSource = false;
82007                     var hasName = false;
82008                     generatedCharacter += base64VLQFormatDecode();
82009                     if (hasReportedError())
82010                         return stopIterating();
82011                     if (generatedCharacter < 0)
82012                         return setErrorAndStopIterating("Invalid generatedCharacter found");
82013                     if (!isSourceMappingSegmentEnd()) {
82014                         hasSource = true;
82015                         sourceIndex += base64VLQFormatDecode();
82016                         if (hasReportedError())
82017                             return stopIterating();
82018                         if (sourceIndex < 0)
82019                             return setErrorAndStopIterating("Invalid sourceIndex found");
82020                         if (isSourceMappingSegmentEnd())
82021                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex");
82022                         sourceLine += base64VLQFormatDecode();
82023                         if (hasReportedError())
82024                             return stopIterating();
82025                         if (sourceLine < 0)
82026                             return setErrorAndStopIterating("Invalid sourceLine found");
82027                         if (isSourceMappingSegmentEnd())
82028                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine");
82029                         sourceCharacter += base64VLQFormatDecode();
82030                         if (hasReportedError())
82031                             return stopIterating();
82032                         if (sourceCharacter < 0)
82033                             return setErrorAndStopIterating("Invalid sourceCharacter found");
82034                         if (!isSourceMappingSegmentEnd()) {
82035                             hasName = true;
82036                             nameIndex += base64VLQFormatDecode();
82037                             if (hasReportedError())
82038                                 return stopIterating();
82039                             if (nameIndex < 0)
82040                                 return setErrorAndStopIterating("Invalid nameIndex found");
82041                             if (!isSourceMappingSegmentEnd())
82042                                 return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex");
82043                         }
82044                     }
82045                     return { value: captureMapping(hasSource, hasName), done: done };
82046                 }
82047                 return stopIterating();
82048             }
82049         };
82050         function captureMapping(hasSource, hasName) {
82051             return {
82052                 generatedLine: generatedLine,
82053                 generatedCharacter: generatedCharacter,
82054                 sourceIndex: hasSource ? sourceIndex : undefined,
82055                 sourceLine: hasSource ? sourceLine : undefined,
82056                 sourceCharacter: hasSource ? sourceCharacter : undefined,
82057                 nameIndex: hasName ? nameIndex : undefined
82058             };
82059         }
82060         function stopIterating() {
82061             done = true;
82062             return { value: undefined, done: true };
82063         }
82064         function setError(message) {
82065             if (error === undefined) {
82066                 error = message;
82067             }
82068         }
82069         function setErrorAndStopIterating(message) {
82070             setError(message);
82071             return stopIterating();
82072         }
82073         function hasReportedError() {
82074             return error !== undefined;
82075         }
82076         function isSourceMappingSegmentEnd() {
82077             return (pos === mappings.length ||
82078                 mappings.charCodeAt(pos) === 44 /* comma */ ||
82079                 mappings.charCodeAt(pos) === 59 /* semicolon */);
82080         }
82081         function base64VLQFormatDecode() {
82082             var moreDigits = true;
82083             var shiftCount = 0;
82084             var value = 0;
82085             for (; moreDigits; pos++) {
82086                 if (pos >= mappings.length)
82087                     return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1;
82088                 // 6 digit number
82089                 var currentByte = base64FormatDecode(mappings.charCodeAt(pos));
82090                 if (currentByte === -1)
82091                     return setError("Invalid character in VLQ"), -1;
82092                 // If msb is set, we still have more bits to continue
82093                 moreDigits = (currentByte & 32) !== 0;
82094                 // least significant 5 bits are the next msbs in the final value.
82095                 value = value | ((currentByte & 31) << shiftCount);
82096                 shiftCount += 5;
82097             }
82098             // Least significant bit if 1 represents negative and rest of the msb is actual absolute value
82099             if ((value & 1) === 0) {
82100                 // + number
82101                 value = value >> 1;
82102             }
82103             else {
82104                 // - number
82105                 value = value >> 1;
82106                 value = -value;
82107             }
82108             return value;
82109         }
82110     }
82111     ts.decodeMappings = decodeMappings;
82112     function sameMapping(left, right) {
82113         return left === right
82114             || left.generatedLine === right.generatedLine
82115                 && left.generatedCharacter === right.generatedCharacter
82116                 && left.sourceIndex === right.sourceIndex
82117                 && left.sourceLine === right.sourceLine
82118                 && left.sourceCharacter === right.sourceCharacter
82119                 && left.nameIndex === right.nameIndex;
82120     }
82121     ts.sameMapping = sameMapping;
82122     function isSourceMapping(mapping) {
82123         return mapping.sourceIndex !== undefined
82124             && mapping.sourceLine !== undefined
82125             && mapping.sourceCharacter !== undefined;
82126     }
82127     ts.isSourceMapping = isSourceMapping;
82128     function base64FormatEncode(value) {
82129         return value >= 0 && value < 26 ? 65 /* A */ + value :
82130             value >= 26 && value < 52 ? 97 /* a */ + value - 26 :
82131                 value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 :
82132                     value === 62 ? 43 /* plus */ :
82133                         value === 63 ? 47 /* slash */ :
82134                             ts.Debug.fail(value + ": not a base64 value");
82135     }
82136     function base64FormatDecode(ch) {
82137         return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ :
82138             ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 :
82139                 ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 :
82140                     ch === 43 /* plus */ ? 62 :
82141                         ch === 47 /* slash */ ? 63 :
82142                             -1;
82143     }
82144     function base64VLQFormatEncode(inValue) {
82145         // Add a new least significant bit that has the sign of the value.
82146         // if negative number the least significant bit that gets added to the number has value 1
82147         // else least significant bit value that gets added is 0
82148         // eg. -1 changes to binary : 01 [1] => 3
82149         //     +1 changes to binary : 01 [0] => 2
82150         if (inValue < 0) {
82151             inValue = ((-inValue) << 1) + 1;
82152         }
82153         else {
82154             inValue = inValue << 1;
82155         }
82156         // Encode 5 bits at a time starting from least significant bits
82157         var encodedStr = "";
82158         do {
82159             var currentDigit = inValue & 31; // 11111
82160             inValue = inValue >> 5;
82161             if (inValue > 0) {
82162                 // There are still more digits to decode, set the msb (6th bit)
82163                 currentDigit = currentDigit | 32;
82164             }
82165             encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit));
82166         } while (inValue > 0);
82167         return encodedStr;
82168     }
82169     function isSourceMappedPosition(value) {
82170         return value.sourceIndex !== undefined
82171             && value.sourcePosition !== undefined;
82172     }
82173     function sameMappedPosition(left, right) {
82174         return left.generatedPosition === right.generatedPosition
82175             && left.sourceIndex === right.sourceIndex
82176             && left.sourcePosition === right.sourcePosition;
82177     }
82178     function compareSourcePositions(left, right) {
82179         // Compares sourcePosition without comparing sourceIndex
82180         // since the mappings are grouped by sourceIndex
82181         ts.Debug.assert(left.sourceIndex === right.sourceIndex);
82182         return ts.compareValues(left.sourcePosition, right.sourcePosition);
82183     }
82184     function compareGeneratedPositions(left, right) {
82185         return ts.compareValues(left.generatedPosition, right.generatedPosition);
82186     }
82187     function getSourcePositionOfMapping(value) {
82188         return value.sourcePosition;
82189     }
82190     function getGeneratedPositionOfMapping(value) {
82191         return value.generatedPosition;
82192     }
82193     function createDocumentPositionMapper(host, map, mapPath) {
82194         var mapDirectory = ts.getDirectoryPath(mapPath);
82195         var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory;
82196         var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory);
82197         var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath);
82198         var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); });
82199         var sourceToSourceIndexMap = new ts.Map(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; }));
82200         var decodedMappings;
82201         var generatedMappings;
82202         var sourceMappings;
82203         return {
82204             getSourcePosition: getSourcePosition,
82205             getGeneratedPosition: getGeneratedPosition
82206         };
82207         function processMapping(mapping) {
82208             var generatedPosition = generatedFile !== undefined
82209                 ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true)
82210                 : -1;
82211             var source;
82212             var sourcePosition;
82213             if (isSourceMapping(mapping)) {
82214                 var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]);
82215                 source = map.sources[mapping.sourceIndex];
82216                 sourcePosition = sourceFile !== undefined
82217                     ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true)
82218                     : -1;
82219             }
82220             return {
82221                 generatedPosition: generatedPosition,
82222                 source: source,
82223                 sourceIndex: mapping.sourceIndex,
82224                 sourcePosition: sourcePosition,
82225                 nameIndex: mapping.nameIndex
82226             };
82227         }
82228         function getDecodedMappings() {
82229             if (decodedMappings === undefined) {
82230                 var decoder = decodeMappings(map.mappings);
82231                 var mappings = ts.arrayFrom(decoder, processMapping);
82232                 if (decoder.error !== undefined) {
82233                     if (host.log) {
82234                         host.log("Encountered error while decoding sourcemap: " + decoder.error);
82235                     }
82236                     decodedMappings = ts.emptyArray;
82237                 }
82238                 else {
82239                     decodedMappings = mappings;
82240                 }
82241             }
82242             return decodedMappings;
82243         }
82244         function getSourceMappings(sourceIndex) {
82245             if (sourceMappings === undefined) {
82246                 var lists = [];
82247                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
82248                     var mapping = _a[_i];
82249                     if (!isSourceMappedPosition(mapping))
82250                         continue;
82251                     var list = lists[mapping.sourceIndex];
82252                     if (!list)
82253                         lists[mapping.sourceIndex] = list = [];
82254                     list.push(mapping);
82255                 }
82256                 sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); });
82257             }
82258             return sourceMappings[sourceIndex];
82259         }
82260         function getGeneratedMappings() {
82261             if (generatedMappings === undefined) {
82262                 var list = [];
82263                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
82264                     var mapping = _a[_i];
82265                     list.push(mapping);
82266                 }
82267                 generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition);
82268             }
82269             return generatedMappings;
82270         }
82271         function getGeneratedPosition(loc) {
82272             var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName));
82273             if (sourceIndex === undefined)
82274                 return loc;
82275             var sourceMappings = getSourceMappings(sourceIndex);
82276             if (!ts.some(sourceMappings))
82277                 return loc;
82278             var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues);
82279             if (targetIndex < 0) {
82280                 // if no exact match, closest is 2's complement of result
82281                 targetIndex = ~targetIndex;
82282             }
82283             var mapping = sourceMappings[targetIndex];
82284             if (mapping === undefined || mapping.sourceIndex !== sourceIndex) {
82285                 return loc;
82286             }
82287             return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos
82288         }
82289         function getSourcePosition(loc) {
82290             var generatedMappings = getGeneratedMappings();
82291             if (!ts.some(generatedMappings))
82292                 return loc;
82293             var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues);
82294             if (targetIndex < 0) {
82295                 // if no exact match, closest is 2's complement of result
82296                 targetIndex = ~targetIndex;
82297             }
82298             var mapping = generatedMappings[targetIndex];
82299             if (mapping === undefined || !isSourceMappedPosition(mapping)) {
82300                 return loc;
82301             }
82302             return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos
82303         }
82304     }
82305     ts.createDocumentPositionMapper = createDocumentPositionMapper;
82306     ts.identitySourceMapConsumer = {
82307         getSourcePosition: ts.identity,
82308         getGeneratedPosition: ts.identity
82309     };
82310 })(ts || (ts = {}));
82311 /* @internal */
82312 var ts;
82313 (function (ts) {
82314     function getOriginalNodeId(node) {
82315         node = ts.getOriginalNode(node);
82316         return node ? ts.getNodeId(node) : 0;
82317     }
82318     ts.getOriginalNodeId = getOriginalNodeId;
82319     function containsDefaultReference(node) {
82320         if (!node)
82321             return false;
82322         if (!ts.isNamedImports(node))
82323             return false;
82324         return ts.some(node.elements, isNamedDefaultReference);
82325     }
82326     function isNamedDefaultReference(e) {
82327         return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */;
82328     }
82329     function chainBundle(context, transformSourceFile) {
82330         return transformSourceFileOrBundle;
82331         function transformSourceFileOrBundle(node) {
82332             return node.kind === 297 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
82333         }
82334         function transformBundle(node) {
82335             return context.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
82336         }
82337     }
82338     ts.chainBundle = chainBundle;
82339     function getExportNeedsImportStarHelper(node) {
82340         return !!ts.getNamespaceDeclarationNode(node);
82341     }
82342     ts.getExportNeedsImportStarHelper = getExportNeedsImportStarHelper;
82343     function getImportNeedsImportStarHelper(node) {
82344         if (!!ts.getNamespaceDeclarationNode(node)) {
82345             return true;
82346         }
82347         var bindings = node.importClause && node.importClause.namedBindings;
82348         if (!bindings) {
82349             return false;
82350         }
82351         if (!ts.isNamedImports(bindings))
82352             return false;
82353         var defaultRefCount = 0;
82354         for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
82355             var binding = _a[_i];
82356             if (isNamedDefaultReference(binding)) {
82357                 defaultRefCount++;
82358             }
82359         }
82360         // 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
82361         return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
82362     }
82363     ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
82364     function getImportNeedsImportDefaultHelper(node) {
82365         // 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)
82366         return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217
82367     }
82368     ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
82369     function collectExternalModuleInfo(context, sourceFile, resolver, compilerOptions) {
82370         var externalImports = [];
82371         var exportSpecifiers = ts.createMultiMap();
82372         var exportedBindings = [];
82373         var uniqueExports = new ts.Map();
82374         var exportedNames;
82375         var hasExportDefault = false;
82376         var exportEquals;
82377         var hasExportStarsToExportValues = false;
82378         var hasImportStar = false;
82379         var hasImportDefault = false;
82380         for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
82381             var node = _a[_i];
82382             switch (node.kind) {
82383                 case 261 /* ImportDeclaration */:
82384                     // import "mod"
82385                     // import x from "mod"
82386                     // import * as x from "mod"
82387                     // import { x, y } from "mod"
82388                     externalImports.push(node);
82389                     if (!hasImportStar && getImportNeedsImportStarHelper(node)) {
82390                         hasImportStar = true;
82391                     }
82392                     if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) {
82393                         hasImportDefault = true;
82394                     }
82395                     break;
82396                 case 260 /* ImportEqualsDeclaration */:
82397                     if (node.moduleReference.kind === 272 /* ExternalModuleReference */) {
82398                         // import x = require("mod")
82399                         externalImports.push(node);
82400                     }
82401                     break;
82402                 case 267 /* ExportDeclaration */:
82403                     if (node.moduleSpecifier) {
82404                         if (!node.exportClause) {
82405                             // export * from "mod"
82406                             externalImports.push(node);
82407                             hasExportStarsToExportValues = true;
82408                         }
82409                         else {
82410                             // export * as ns from "mod"
82411                             // export { x, y } from "mod"
82412                             externalImports.push(node);
82413                             if (ts.isNamedExports(node.exportClause)) {
82414                                 addExportedNamesForExportDeclaration(node);
82415                             }
82416                             else {
82417                                 var name = node.exportClause.name;
82418                                 if (!uniqueExports.get(ts.idText(name))) {
82419                                     multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
82420                                     uniqueExports.set(ts.idText(name), true);
82421                                     exportedNames = ts.append(exportedNames, name);
82422                                 }
82423                                 // we use the same helpers for `export * as ns` as we do for `import * as ns`
82424                                 hasImportStar = true;
82425                             }
82426                         }
82427                     }
82428                     else {
82429                         // export { x, y }
82430                         addExportedNamesForExportDeclaration(node);
82431                     }
82432                     break;
82433                 case 266 /* ExportAssignment */:
82434                     if (node.isExportEquals && !exportEquals) {
82435                         // export = x
82436                         exportEquals = node;
82437                     }
82438                     break;
82439                 case 232 /* VariableStatement */:
82440                     if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
82441                         for (var _b = 0, _c = node.declarationList.declarations; _b < _c.length; _b++) {
82442                             var decl = _c[_b];
82443                             exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
82444                         }
82445                     }
82446                     break;
82447                 case 251 /* FunctionDeclaration */:
82448                     if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
82449                         if (ts.hasSyntacticModifier(node, 512 /* Default */)) {
82450                             // export default function() { }
82451                             if (!hasExportDefault) {
82452                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node));
82453                                 hasExportDefault = true;
82454                             }
82455                         }
82456                         else {
82457                             // export function x() { }
82458                             var name = node.name;
82459                             if (!uniqueExports.get(ts.idText(name))) {
82460                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
82461                                 uniqueExports.set(ts.idText(name), true);
82462                                 exportedNames = ts.append(exportedNames, name);
82463                             }
82464                         }
82465                     }
82466                     break;
82467                 case 252 /* ClassDeclaration */:
82468                     if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
82469                         if (ts.hasSyntacticModifier(node, 512 /* Default */)) {
82470                             // export default class { }
82471                             if (!hasExportDefault) {
82472                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node));
82473                                 hasExportDefault = true;
82474                             }
82475                         }
82476                         else {
82477                             // export class x { }
82478                             var name = node.name;
82479                             if (name && !uniqueExports.get(ts.idText(name))) {
82480                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
82481                                 uniqueExports.set(ts.idText(name), true);
82482                                 exportedNames = ts.append(exportedNames, name);
82483                             }
82484                         }
82485                     }
82486                     break;
82487             }
82488         }
82489         var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(context.factory, context.getEmitHelperFactory(), sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault);
82490         if (externalHelpersImportDeclaration) {
82491             externalImports.unshift(externalHelpersImportDeclaration);
82492         }
82493         return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration };
82494         function addExportedNamesForExportDeclaration(node) {
82495             for (var _i = 0, _a = ts.cast(node.exportClause, ts.isNamedExports).elements; _i < _a.length; _i++) {
82496                 var specifier = _a[_i];
82497                 if (!uniqueExports.get(ts.idText(specifier.name))) {
82498                     var name = specifier.propertyName || specifier.name;
82499                     if (!node.moduleSpecifier) {
82500                         exportSpecifiers.add(ts.idText(name), specifier);
82501                     }
82502                     var decl = resolver.getReferencedImportDeclaration(name)
82503                         || resolver.getReferencedValueDeclaration(name);
82504                     if (decl) {
82505                         multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
82506                     }
82507                     uniqueExports.set(ts.idText(specifier.name), true);
82508                     exportedNames = ts.append(exportedNames, specifier.name);
82509                 }
82510             }
82511         }
82512     }
82513     ts.collectExternalModuleInfo = collectExternalModuleInfo;
82514     function collectExportedVariableInfo(decl, uniqueExports, exportedNames) {
82515         if (ts.isBindingPattern(decl.name)) {
82516             for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
82517                 var element = _a[_i];
82518                 if (!ts.isOmittedExpression(element)) {
82519                     exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames);
82520                 }
82521             }
82522         }
82523         else if (!ts.isGeneratedIdentifier(decl.name)) {
82524             var text = ts.idText(decl.name);
82525             if (!uniqueExports.get(text)) {
82526                 uniqueExports.set(text, true);
82527                 exportedNames = ts.append(exportedNames, decl.name);
82528             }
82529         }
82530         return exportedNames;
82531     }
82532     /** Use a sparse array as a multi-map. */
82533     function multiMapSparseArrayAdd(map, key, value) {
82534         var values = map[key];
82535         if (values) {
82536             values.push(value);
82537         }
82538         else {
82539             map[key] = values = [value];
82540         }
82541         return values;
82542     }
82543     /**
82544      * Used in the module transformer to check if an expression is reasonably without sideeffect,
82545      *  and thus better to copy into multiple places rather than to cache in a temporary variable
82546      *  - this is mostly subjective beyond the requirement that the expression not be sideeffecting
82547      */
82548     function isSimpleCopiableExpression(expression) {
82549         return ts.isStringLiteralLike(expression) ||
82550             expression.kind === 8 /* NumericLiteral */ ||
82551             ts.isKeyword(expression.kind) ||
82552             ts.isIdentifier(expression);
82553     }
82554     ts.isSimpleCopiableExpression = isSimpleCopiableExpression;
82555     /**
82556      * A simple inlinable expression is an expression which can be copied into multiple locations
82557      * without risk of repeating any sideeffects and whose value could not possibly change between
82558      * any such locations
82559      */
82560     function isSimpleInlineableExpression(expression) {
82561         return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) ||
82562             ts.isWellKnownSymbolSyntactically(expression);
82563     }
82564     ts.isSimpleInlineableExpression = isSimpleInlineableExpression;
82565     function isCompoundAssignment(kind) {
82566         return kind >= 63 /* FirstCompoundAssignment */
82567             && kind <= 77 /* LastCompoundAssignment */;
82568     }
82569     ts.isCompoundAssignment = isCompoundAssignment;
82570     function getNonAssignmentOperatorForCompoundAssignment(kind) {
82571         switch (kind) {
82572             case 63 /* PlusEqualsToken */: return 39 /* PlusToken */;
82573             case 64 /* MinusEqualsToken */: return 40 /* MinusToken */;
82574             case 65 /* AsteriskEqualsToken */: return 41 /* AsteriskToken */;
82575             case 66 /* AsteriskAsteriskEqualsToken */: return 42 /* AsteriskAsteriskToken */;
82576             case 67 /* SlashEqualsToken */: return 43 /* SlashToken */;
82577             case 68 /* PercentEqualsToken */: return 44 /* PercentToken */;
82578             case 69 /* LessThanLessThanEqualsToken */: return 47 /* LessThanLessThanToken */;
82579             case 70 /* GreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanToken */;
82580             case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 49 /* GreaterThanGreaterThanGreaterThanToken */;
82581             case 72 /* AmpersandEqualsToken */: return 50 /* AmpersandToken */;
82582             case 73 /* BarEqualsToken */: return 51 /* BarToken */;
82583             case 77 /* CaretEqualsToken */: return 52 /* CaretToken */;
82584             case 74 /* BarBarEqualsToken */: return 56 /* BarBarToken */;
82585             case 75 /* AmpersandAmpersandEqualsToken */: return 55 /* AmpersandAmpersandToken */;
82586             case 76 /* QuestionQuestionEqualsToken */: return 60 /* QuestionQuestionToken */;
82587         }
82588     }
82589     ts.getNonAssignmentOperatorForCompoundAssignment = getNonAssignmentOperatorForCompoundAssignment;
82590     /**
82591      * Adds super call and preceding prologue directives into the list of statements.
82592      *
82593      * @param ctor The constructor node.
82594      * @param result The list of statements.
82595      * @param visitor The visitor to apply to each node added to the result array.
82596      * @returns index of the statement that follows super call
82597      */
82598     function addPrologueDirectivesAndInitialSuperCall(factory, ctor, result, visitor) {
82599         if (ctor.body) {
82600             var statements = ctor.body.statements;
82601             // add prologue directives to the list (if any)
82602             var index = factory.copyPrologue(statements, result, /*ensureUseStrict*/ false, visitor);
82603             if (index === statements.length) {
82604                 // list contains nothing but prologue directives (or empty) - exit
82605                 return index;
82606             }
82607             var superIndex = ts.findIndex(statements, function (s) { return ts.isExpressionStatement(s) && ts.isSuperCall(s.expression); }, index);
82608             if (superIndex > -1) {
82609                 for (var i = index; i <= superIndex; i++) {
82610                     result.push(ts.visitNode(statements[i], visitor, ts.isStatement));
82611                 }
82612                 return superIndex + 1;
82613             }
82614             return index;
82615         }
82616         return 0;
82617     }
82618     ts.addPrologueDirectivesAndInitialSuperCall = addPrologueDirectivesAndInitialSuperCall;
82619     function getProperties(node, requireInitializer, isStatic) {
82620         return ts.filter(node.members, function (m) { return isInitializedOrStaticProperty(m, requireInitializer, isStatic); });
82621     }
82622     ts.getProperties = getProperties;
82623     /**
82624      * Is a class element either a static or an instance property declaration with an initializer?
82625      *
82626      * @param member The class element node.
82627      * @param isStatic A value indicating whether the member should be a static or instance member.
82628      */
82629     function isInitializedOrStaticProperty(member, requireInitializer, isStatic) {
82630         return ts.isPropertyDeclaration(member)
82631             && (!!member.initializer || !requireInitializer)
82632             && ts.hasStaticModifier(member) === isStatic;
82633     }
82634     /**
82635      * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer.
82636      *
82637      * @param member The class element node.
82638      * @param isStatic A value indicating whether the member should be a static or instance member.
82639      */
82640     function isInitializedProperty(member) {
82641         return member.kind === 163 /* PropertyDeclaration */
82642             && member.initializer !== undefined;
82643     }
82644     ts.isInitializedProperty = isInitializedProperty;
82645 })(ts || (ts = {}));
82646 /*@internal*/
82647 var ts;
82648 (function (ts) {
82649     var FlattenLevel;
82650     (function (FlattenLevel) {
82651         FlattenLevel[FlattenLevel["All"] = 0] = "All";
82652         FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest";
82653     })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {}));
82654     /**
82655      * Flattens a DestructuringAssignment or a VariableDeclaration to an expression.
82656      *
82657      * @param node The node to flatten.
82658      * @param visitor An optional visitor used to visit initializers.
82659      * @param context The transformation context.
82660      * @param level Indicates the extent to which flattening should occur.
82661      * @param needsValue An optional value indicating whether the value from the right-hand-side of
82662      * the destructuring assignment is needed as part of a larger expression.
82663      * @param createAssignmentCallback An optional callback used to create the assignment expression.
82664      */
82665     function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
82666         var location = node;
82667         var value;
82668         if (ts.isDestructuringAssignment(node)) {
82669             value = node.right;
82670             while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) {
82671                 if (ts.isDestructuringAssignment(value)) {
82672                     location = node = value;
82673                     value = node.right;
82674                 }
82675                 else {
82676                     return ts.visitNode(value, visitor, ts.isExpression);
82677                 }
82678             }
82679         }
82680         var expressions;
82681         var flattenContext = {
82682             context: context,
82683             level: level,
82684             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
82685             hoistTempVariables: true,
82686             emitExpression: emitExpression,
82687             emitBindingOrAssignment: emitBindingOrAssignment,
82688             createArrayBindingOrAssignmentPattern: function (elements) { return makeArrayAssignmentPattern(context.factory, elements); },
82689             createObjectBindingOrAssignmentPattern: function (elements) { return makeObjectAssignmentPattern(context.factory, elements); },
82690             createArrayBindingOrAssignmentElement: makeAssignmentElement,
82691             visitor: visitor
82692         };
82693         if (value) {
82694             value = ts.visitNode(value, visitor, ts.isExpression);
82695             if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) ||
82696                 bindingOrAssignmentElementContainsNonLiteralComputedName(node)) {
82697                 // If the right-hand value of the assignment is also an assignment target then
82698                 // we need to cache the right-hand value.
82699                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location);
82700             }
82701             else if (needsValue) {
82702                 // If the right-hand value of the destructuring assignment needs to be preserved (as
82703                 // is the case when the destructuring assignment is part of a larger expression),
82704                 // then we need to cache the right-hand value.
82705                 //
82706                 // The source map location for the assignment should point to the entire binary
82707                 // expression.
82708                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
82709             }
82710             else if (ts.nodeIsSynthesized(node)) {
82711                 // Generally, the source map location for a destructuring assignment is the root
82712                 // expression.
82713                 //
82714                 // However, if the root expression is synthesized (as in the case
82715                 // of the initializer when transforming a ForOfStatement), then the source map
82716                 // location should point to the right-hand value of the expression.
82717                 location = value;
82718             }
82719         }
82720         flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node));
82721         if (value && needsValue) {
82722             if (!ts.some(expressions)) {
82723                 return value;
82724             }
82725             expressions.push(value);
82726         }
82727         return context.factory.inlineExpressions(expressions) || context.factory.createOmittedExpression();
82728         function emitExpression(expression) {
82729             expressions = ts.append(expressions, expression);
82730         }
82731         function emitBindingOrAssignment(target, value, location, original) {
82732             ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
82733             var expression = createAssignmentCallback
82734                 ? createAssignmentCallback(target, value, location)
82735                 : ts.setTextRange(context.factory.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
82736             expression.original = original;
82737             emitExpression(expression);
82738         }
82739     }
82740     ts.flattenDestructuringAssignment = flattenDestructuringAssignment;
82741     function bindingOrAssignmentElementAssignsToName(element, escapedName) {
82742         var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
82743         if (ts.isBindingOrAssignmentPattern(target)) {
82744             return bindingOrAssignmentPatternAssignsToName(target, escapedName);
82745         }
82746         else if (ts.isIdentifier(target)) {
82747             return target.escapedText === escapedName;
82748         }
82749         return false;
82750     }
82751     function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) {
82752         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
82753         for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
82754             var element = elements_3[_i];
82755             if (bindingOrAssignmentElementAssignsToName(element, escapedName)) {
82756                 return true;
82757             }
82758         }
82759         return false;
82760     }
82761     function bindingOrAssignmentElementContainsNonLiteralComputedName(element) {
82762         var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
82763         if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) {
82764             return true;
82765         }
82766         var target = ts.getTargetOfBindingOrAssignmentElement(element);
82767         return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target);
82768     }
82769     function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) {
82770         return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName);
82771     }
82772     /**
82773      * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations.
82774      *
82775      * @param node The node to flatten.
82776      * @param visitor An optional visitor used to visit initializers.
82777      * @param context The transformation context.
82778      * @param boundValue The value bound to the declaration.
82779      * @param skipInitializer A value indicating whether to ignore the initializer of `node`.
82780      * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line.
82781      * @param level Indicates the extent to which flattening should occur.
82782      */
82783     function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) {
82784         if (hoistTempVariables === void 0) { hoistTempVariables = false; }
82785         var pendingExpressions;
82786         var pendingDeclarations = [];
82787         var declarations = [];
82788         var flattenContext = {
82789             context: context,
82790             level: level,
82791             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
82792             hoistTempVariables: hoistTempVariables,
82793             emitExpression: emitExpression,
82794             emitBindingOrAssignment: emitBindingOrAssignment,
82795             createArrayBindingOrAssignmentPattern: function (elements) { return makeArrayBindingPattern(context.factory, elements); },
82796             createObjectBindingOrAssignmentPattern: function (elements) { return makeObjectBindingPattern(context.factory, elements); },
82797             createArrayBindingOrAssignmentElement: function (name) { return makeBindingElement(context.factory, name); },
82798             visitor: visitor
82799         };
82800         if (ts.isVariableDeclaration(node)) {
82801             var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
82802             if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) ||
82803                 bindingOrAssignmentElementContainsNonLiteralComputedName(node))) {
82804                 // If the right-hand value of the assignment is also an assignment target then
82805                 // we need to cache the right-hand value.
82806                 initializer = ensureIdentifier(flattenContext, ts.visitNode(initializer, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, initializer);
82807                 node = context.factory.updateVariableDeclaration(node, node.name, /*exclamationToken*/ undefined, /*type*/ undefined, initializer);
82808             }
82809         }
82810         flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
82811         if (pendingExpressions) {
82812             var temp = context.factory.createTempVariable(/*recordTempVariable*/ undefined);
82813             if (hoistTempVariables) {
82814                 var value = context.factory.inlineExpressions(pendingExpressions);
82815                 pendingExpressions = undefined;
82816                 emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
82817             }
82818             else {
82819                 context.hoistVariableDeclaration(temp);
82820                 var pendingDeclaration = ts.last(pendingDeclarations);
82821                 pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, context.factory.createAssignment(temp, pendingDeclaration.value));
82822                 ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
82823                 pendingDeclaration.value = temp;
82824             }
82825         }
82826         for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
82827             var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original;
82828             var variable = context.factory.createVariableDeclaration(name, 
82829             /*exclamationToken*/ undefined, 
82830             /*type*/ undefined, pendingExpressions_1 ? context.factory.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
82831             variable.original = original;
82832             ts.setTextRange(variable, location);
82833             declarations.push(variable);
82834         }
82835         return declarations;
82836         function emitExpression(value) {
82837             pendingExpressions = ts.append(pendingExpressions, value);
82838         }
82839         function emitBindingOrAssignment(target, value, location, original) {
82840             ts.Debug.assertNode(target, ts.isBindingName);
82841             if (pendingExpressions) {
82842                 value = context.factory.inlineExpressions(ts.append(pendingExpressions, value));
82843                 pendingExpressions = undefined;
82844             }
82845             pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original });
82846         }
82847     }
82848     ts.flattenDestructuringBinding = flattenDestructuringBinding;
82849     /**
82850      * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments.
82851      *
82852      * @param flattenContext Options used to control flattening.
82853      * @param element The element to flatten.
82854      * @param value The current RHS value to assign to the element.
82855      * @param location The location to use for source maps and comments.
82856      * @param skipInitializer An optional value indicating whether to include the initializer
82857      * for the element.
82858      */
82859     function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) {
82860         var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
82861         if (!skipInitializer) {
82862             var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression);
82863             if (initializer) {
82864                 // Combine value and initializer
82865                 if (value) {
82866                     value = createDefaultValueCheck(flattenContext, value, initializer, location);
82867                     // If 'value' is not a simple expression, it could contain side-effecting code that should evaluate before an object or array binding pattern.
82868                     if (!ts.isSimpleInlineableExpression(initializer) && ts.isBindingOrAssignmentPattern(bindingTarget)) {
82869                         value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
82870                     }
82871                 }
82872                 else {
82873                     value = initializer;
82874                 }
82875             }
82876             else if (!value) {
82877                 // Use 'void 0' in absence of value and initializer
82878                 value = flattenContext.context.factory.createVoidZero();
82879             }
82880         }
82881         if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) {
82882             flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
82883         }
82884         else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) {
82885             flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
82886         }
82887         else {
82888             flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217
82889         }
82890     }
82891     /**
82892      * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments.
82893      *
82894      * @param flattenContext Options used to control flattening.
82895      * @param parent The parent element of the pattern.
82896      * @param pattern The ObjectBindingOrAssignmentPattern to flatten.
82897      * @param value The current RHS value to assign to the element.
82898      * @param location The location to use for source maps and comments.
82899      */
82900     function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
82901         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
82902         var numElements = elements.length;
82903         if (numElements !== 1) {
82904             // For anything other than a single-element destructuring we need to generate a temporary
82905             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
82906             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
82907             // so in that case, we'll intentionally create that temporary.
82908             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
82909             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
82910         }
82911         var bindingElements;
82912         var computedTempVariables;
82913         for (var i = 0; i < numElements; i++) {
82914             var element = elements[i];
82915             if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
82916                 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
82917                 if (flattenContext.level >= 1 /* ObjectRest */
82918                     && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
82919                     && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
82920                     && !ts.isComputedPropertyName(propertyName)) {
82921                     bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor));
82922                 }
82923                 else {
82924                     if (bindingElements) {
82925                         flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
82926                         bindingElements = undefined;
82927                     }
82928                     var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
82929                     if (ts.isComputedPropertyName(propertyName)) {
82930                         computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression);
82931                     }
82932                     flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
82933                 }
82934             }
82935             else if (i === numElements - 1) {
82936                 if (bindingElements) {
82937                     flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
82938                     bindingElements = undefined;
82939                 }
82940                 var rhsValue = flattenContext.context.getEmitHelperFactory().createRestHelper(value, elements, computedTempVariables, pattern);
82941                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
82942             }
82943         }
82944         if (bindingElements) {
82945             flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
82946         }
82947     }
82948     /**
82949      * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments.
82950      *
82951      * @param flattenContext Options used to control flattening.
82952      * @param parent The parent element of the pattern.
82953      * @param pattern The ArrayBindingOrAssignmentPattern to flatten.
82954      * @param value The current RHS value to assign to the element.
82955      * @param location The location to use for source maps and comments.
82956      */
82957     function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
82958         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
82959         var numElements = elements.length;
82960         if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
82961             // Read the elements of the iterable into an array
82962             value = ensureIdentifier(flattenContext, ts.setTextRange(flattenContext.context.getEmitHelperFactory().createReadHelper(value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1])
82963                 ? undefined
82964                 : numElements), location), 
82965             /*reuseIdentifierExpressions*/ false, location);
82966         }
82967         else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)
82968             || ts.every(elements, ts.isOmittedExpression)) {
82969             // For anything other than a single-element destructuring we need to generate a temporary
82970             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
82971             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
82972             // so in that case, we'll intentionally create that temporary.
82973             // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]",
82974             // then we will create temporary variable.
82975             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
82976             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
82977         }
82978         var bindingElements;
82979         var restContainingElements;
82980         for (var i = 0; i < numElements; i++) {
82981             var element = elements[i];
82982             if (flattenContext.level >= 1 /* ObjectRest */) {
82983                 // If an array pattern contains an ObjectRest, we must cache the result so that we
82984                 // can perform the ObjectRest destructuring in a different declaration
82985                 if (element.transformFlags & 16384 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) {
82986                     flattenContext.hasTransformedPriorElement = true;
82987                     var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined);
82988                     if (flattenContext.hoistTempVariables) {
82989                         flattenContext.context.hoistVariableDeclaration(temp);
82990                     }
82991                     restContainingElements = ts.append(restContainingElements, [temp, element]);
82992                     bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
82993                 }
82994                 else {
82995                     bindingElements = ts.append(bindingElements, element);
82996                 }
82997             }
82998             else if (ts.isOmittedExpression(element)) {
82999                 continue;
83000             }
83001             else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
83002                 var rhsValue = flattenContext.context.factory.createElementAccessExpression(value, i);
83003                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
83004             }
83005             else if (i === numElements - 1) {
83006                 var rhsValue = flattenContext.context.factory.createArraySliceCall(value, i);
83007                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
83008             }
83009         }
83010         if (bindingElements) {
83011             flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
83012         }
83013         if (restContainingElements) {
83014             for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) {
83015                 var _a = restContainingElements_1[_i], id = _a[0], element = _a[1];
83016                 flattenBindingOrAssignmentElement(flattenContext, element, id, element);
83017             }
83018         }
83019     }
83020     function isSimpleBindingOrAssignmentElement(element) {
83021         var target = ts.getTargetOfBindingOrAssignmentElement(element);
83022         if (!target || ts.isOmittedExpression(target))
83023             return true;
83024         var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
83025         if (propertyName && !ts.isPropertyNameLiteral(propertyName))
83026             return false;
83027         var initializer = ts.getInitializerOfBindingOrAssignmentElement(element);
83028         if (initializer && !ts.isSimpleInlineableExpression(initializer))
83029             return false;
83030         if (ts.isBindingOrAssignmentPattern(target))
83031             return ts.every(ts.getElementsOfBindingOrAssignmentPattern(target), isSimpleBindingOrAssignmentElement);
83032         return ts.isIdentifier(target);
83033     }
83034     /**
83035      * Creates an expression used to provide a default value if a value is `undefined` at runtime.
83036      *
83037      * @param flattenContext Options used to control flattening.
83038      * @param value The RHS value to test.
83039      * @param defaultValue The default value to use if `value` is `undefined` at runtime.
83040      * @param location The location to use for source maps and comments.
83041      */
83042     function createDefaultValueCheck(flattenContext, value, defaultValue, location) {
83043         value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
83044         return flattenContext.context.factory.createConditionalExpression(flattenContext.context.factory.createTypeCheck(value, "undefined"), /*questionToken*/ undefined, defaultValue, /*colonToken*/ undefined, value);
83045     }
83046     /**
83047      * Creates either a PropertyAccessExpression or an ElementAccessExpression for the
83048      * right-hand side of a transformed destructuring assignment.
83049      *
83050      * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation
83051      *
83052      * @param flattenContext Options used to control flattening.
83053      * @param value The RHS value that is the source of the property.
83054      * @param propertyName The destructuring property name.
83055      */
83056     function createDestructuringPropertyAccess(flattenContext, value, propertyName) {
83057         if (ts.isComputedPropertyName(propertyName)) {
83058             var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName);
83059             return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression);
83060         }
83061         else if (ts.isStringOrNumericLiteralLike(propertyName)) {
83062             var argumentExpression = ts.factory.cloneNode(propertyName);
83063             return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression);
83064         }
83065         else {
83066             var name = flattenContext.context.factory.createIdentifier(ts.idText(propertyName));
83067             return flattenContext.context.factory.createPropertyAccessExpression(value, name);
83068         }
83069     }
83070     /**
83071      * Ensures that there exists a declared identifier whose value holds the given expression.
83072      * This function is useful to ensure that the expression's value can be read from in subsequent expressions.
83073      * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
83074      *
83075      * @param flattenContext Options used to control flattening.
83076      * @param value the expression whose value needs to be bound.
83077      * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
83078      * false if it is necessary to always emit an identifier.
83079      * @param location The location to use for source maps and comments.
83080      */
83081     function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) {
83082         if (ts.isIdentifier(value) && reuseIdentifierExpressions) {
83083             return value;
83084         }
83085         else {
83086             var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined);
83087             if (flattenContext.hoistTempVariables) {
83088                 flattenContext.context.hoistVariableDeclaration(temp);
83089                 flattenContext.emitExpression(ts.setTextRange(flattenContext.context.factory.createAssignment(temp, value), location));
83090             }
83091             else {
83092                 flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
83093             }
83094             return temp;
83095         }
83096     }
83097     function makeArrayBindingPattern(factory, elements) {
83098         ts.Debug.assertEachNode(elements, ts.isArrayBindingElement);
83099         return factory.createArrayBindingPattern(elements);
83100     }
83101     function makeArrayAssignmentPattern(factory, elements) {
83102         return factory.createArrayLiteralExpression(ts.map(elements, factory.converters.convertToArrayAssignmentElement));
83103     }
83104     function makeObjectBindingPattern(factory, elements) {
83105         ts.Debug.assertEachNode(elements, ts.isBindingElement);
83106         return factory.createObjectBindingPattern(elements);
83107     }
83108     function makeObjectAssignmentPattern(factory, elements) {
83109         return factory.createObjectLiteralExpression(ts.map(elements, factory.converters.convertToObjectAssignmentElement));
83110     }
83111     function makeBindingElement(factory, name) {
83112         return factory.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name);
83113     }
83114     function makeAssignmentElement(name) {
83115         return name;
83116     }
83117 })(ts || (ts = {}));
83118 /*@internal*/
83119 var ts;
83120 (function (ts) {
83121     var ProcessLevel;
83122     (function (ProcessLevel) {
83123         ProcessLevel[ProcessLevel["LiftRestriction"] = 0] = "LiftRestriction";
83124         ProcessLevel[ProcessLevel["All"] = 1] = "All";
83125     })(ProcessLevel = ts.ProcessLevel || (ts.ProcessLevel = {}));
83126     function processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, level) {
83127         // Visit the tag expression
83128         var tag = ts.visitNode(node.tag, visitor, ts.isExpression);
83129         // Build up the template arguments and the raw and cooked strings for the template.
83130         // We start out with 'undefined' for the first argument and revisit later
83131         // to avoid walking over the template string twice and shifting all our arguments over after the fact.
83132         var templateArguments = [undefined];
83133         var cookedStrings = [];
83134         var rawStrings = [];
83135         var template = node.template;
83136         if (level === ProcessLevel.LiftRestriction && !ts.hasInvalidEscape(template)) {
83137             return ts.visitEachChild(node, visitor, context);
83138         }
83139         if (ts.isNoSubstitutionTemplateLiteral(template)) {
83140             cookedStrings.push(createTemplateCooked(template));
83141             rawStrings.push(getRawLiteral(template, currentSourceFile));
83142         }
83143         else {
83144             cookedStrings.push(createTemplateCooked(template.head));
83145             rawStrings.push(getRawLiteral(template.head, currentSourceFile));
83146             for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) {
83147                 var templateSpan = _a[_i];
83148                 cookedStrings.push(createTemplateCooked(templateSpan.literal));
83149                 rawStrings.push(getRawLiteral(templateSpan.literal, currentSourceFile));
83150                 templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression));
83151             }
83152         }
83153         var helperCall = context.getEmitHelperFactory().createTemplateObjectHelper(ts.factory.createArrayLiteralExpression(cookedStrings), ts.factory.createArrayLiteralExpression(rawStrings));
83154         // Create a variable to cache the template object if we're in a module.
83155         // Do not do this in the global scope, as any variable we currently generate could conflict with
83156         // variables from outside of the current compilation. In the future, we can revisit this behavior.
83157         if (ts.isExternalModule(currentSourceFile)) {
83158             var tempVar = ts.factory.createUniqueName("templateObject");
83159             recordTaggedTemplateString(tempVar);
83160             templateArguments[0] = ts.factory.createLogicalOr(tempVar, ts.factory.createAssignment(tempVar, helperCall));
83161         }
83162         else {
83163             templateArguments[0] = helperCall;
83164         }
83165         return ts.factory.createCallExpression(tag, /*typeArguments*/ undefined, templateArguments);
83166     }
83167     ts.processTaggedTemplateExpression = processTaggedTemplateExpression;
83168     function createTemplateCooked(template) {
83169         return template.templateFlags ? ts.factory.createVoidZero() : ts.factory.createStringLiteral(template.text);
83170     }
83171     /**
83172      * Creates an ES5 compatible literal from an ES6 template literal.
83173      *
83174      * @param node The ES6 template literal.
83175      */
83176     function getRawLiteral(node, currentSourceFile) {
83177         // Find original source text, since we need to emit the raw strings of the tagged template.
83178         // The raw strings contain the (escaped) strings of what the user wrote.
83179         // Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
83180         var text = node.rawText;
83181         if (text === undefined) {
83182             text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
83183             // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
83184             // thus we need to remove those characters.
83185             // First template piece starts with "`", others with "}"
83186             // Last template piece ends with "`", others with "${"
83187             var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */;
83188             text = text.substring(1, text.length - (isLast ? 1 : 2));
83189         }
83190         // Newline normalization:
83191         // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
83192         // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
83193         text = text.replace(/\r\n?/g, "\n");
83194         return ts.setTextRange(ts.factory.createStringLiteral(text), node);
83195     }
83196 })(ts || (ts = {}));
83197 /*@internal*/
83198 var ts;
83199 (function (ts) {
83200     /**
83201      * Indicates whether to emit type metadata in the new format.
83202      */
83203     var USE_NEW_TYPE_METADATA_FORMAT = false;
83204     var TypeScriptSubstitutionFlags;
83205     (function (TypeScriptSubstitutionFlags) {
83206         /** Enables substitutions for decorated classes. */
83207         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
83208         /** Enables substitutions for namespace exports. */
83209         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports";
83210         /* Enables substitutions for unqualified enum members */
83211         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers";
83212     })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {}));
83213     var ClassFacts;
83214     (function (ClassFacts) {
83215         ClassFacts[ClassFacts["None"] = 0] = "None";
83216         ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties";
83217         ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators";
83218         ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators";
83219         ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace";
83220         ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport";
83221         ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport";
83222         ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass";
83223         ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression";
83224         ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators";
83225         ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName";
83226         ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression";
83227         ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported";
83228     })(ClassFacts || (ClassFacts = {}));
83229     function transformTypeScript(context) {
83230         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
83231         var resolver = context.getEmitResolver();
83232         var compilerOptions = context.getCompilerOptions();
83233         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
83234         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
83235         var moduleKind = ts.getEmitModuleKind(compilerOptions);
83236         // Save the previous transformation hooks.
83237         var previousOnEmitNode = context.onEmitNode;
83238         var previousOnSubstituteNode = context.onSubstituteNode;
83239         // Set new transformation hooks.
83240         context.onEmitNode = onEmitNode;
83241         context.onSubstituteNode = onSubstituteNode;
83242         // Enable substitution for property/element access to emit const enum values.
83243         context.enableSubstitution(201 /* PropertyAccessExpression */);
83244         context.enableSubstitution(202 /* ElementAccessExpression */);
83245         // These variables contain state that changes as we descend into the tree.
83246         var currentSourceFile;
83247         var currentNamespace;
83248         var currentNamespaceContainerName;
83249         var currentLexicalScope;
83250         var currentNameScope;
83251         var currentScopeFirstDeclarationsOfName;
83252         var currentClassHasParameterProperties;
83253         /**
83254          * Keeps track of whether expression substitution has been enabled for specific edge cases.
83255          * They are persisted between each SourceFile transformation and should not be reset.
83256          */
83257         var enabledSubstitutions;
83258         /**
83259          * A map that keeps track of aliases created for classes with decorators to avoid issues
83260          * with the double-binding behavior of classes.
83261          */
83262         var classAliases;
83263         /**
83264          * Keeps track of whether we are within any containing namespaces when performing
83265          * just-in-time substitution while printing an expression identifier.
83266          */
83267         var applicableSubstitutions;
83268         return transformSourceFileOrBundle;
83269         function transformSourceFileOrBundle(node) {
83270             if (node.kind === 298 /* Bundle */) {
83271                 return transformBundle(node);
83272             }
83273             return transformSourceFile(node);
83274         }
83275         function transformBundle(node) {
83276             return factory.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
83277                 if (prepend.kind === 300 /* InputFiles */) {
83278                     return ts.createUnparsedSourceFile(prepend, "js");
83279                 }
83280                 return prepend;
83281             }));
83282         }
83283         /**
83284          * Transform TypeScript-specific syntax in a SourceFile.
83285          *
83286          * @param node A SourceFile node.
83287          */
83288         function transformSourceFile(node) {
83289             if (node.isDeclarationFile) {
83290                 return node;
83291             }
83292             currentSourceFile = node;
83293             var visited = saveStateAndInvoke(node, visitSourceFile);
83294             ts.addEmitHelpers(visited, context.readEmitHelpers());
83295             currentSourceFile = undefined;
83296             return visited;
83297         }
83298         /**
83299          * Visits a node, saving and restoring state variables on the stack.
83300          *
83301          * @param node The node to visit.
83302          */
83303         function saveStateAndInvoke(node, f) {
83304             // Save state
83305             var savedCurrentScope = currentLexicalScope;
83306             var savedCurrentNameScope = currentNameScope;
83307             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
83308             var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties;
83309             // Handle state changes before visiting a node.
83310             onBeforeVisitNode(node);
83311             var visited = f(node);
83312             // Restore state
83313             if (currentLexicalScope !== savedCurrentScope) {
83314                 currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
83315             }
83316             currentLexicalScope = savedCurrentScope;
83317             currentNameScope = savedCurrentNameScope;
83318             currentClassHasParameterProperties = savedCurrentClassHasParameterProperties;
83319             return visited;
83320         }
83321         /**
83322          * Performs actions that should always occur immediately before visiting a node.
83323          *
83324          * @param node The node to visit.
83325          */
83326         function onBeforeVisitNode(node) {
83327             switch (node.kind) {
83328                 case 297 /* SourceFile */:
83329                 case 258 /* CaseBlock */:
83330                 case 257 /* ModuleBlock */:
83331                 case 230 /* Block */:
83332                     currentLexicalScope = node;
83333                     currentNameScope = undefined;
83334                     currentScopeFirstDeclarationsOfName = undefined;
83335                     break;
83336                 case 252 /* ClassDeclaration */:
83337                 case 251 /* FunctionDeclaration */:
83338                     if (ts.hasSyntacticModifier(node, 2 /* Ambient */)) {
83339                         break;
83340                     }
83341                     // Record these declarations provided that they have a name.
83342                     if (node.name) {
83343                         recordEmittedDeclarationInScope(node);
83344                     }
83345                     else {
83346                         // These nodes should always have names unless they are default-exports;
83347                         // however, class declaration parsing allows for undefined names, so syntactically invalid
83348                         // programs may also have an undefined name.
83349                         ts.Debug.assert(node.kind === 252 /* ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* Default */));
83350                     }
83351                     if (ts.isClassDeclaration(node)) {
83352                         // XXX: should probably also cover interfaces and type aliases that can have type variables?
83353                         currentNameScope = node;
83354                     }
83355                     break;
83356             }
83357         }
83358         /**
83359          * General-purpose node visitor.
83360          *
83361          * @param node The node to visit.
83362          */
83363         function visitor(node) {
83364             return saveStateAndInvoke(node, visitorWorker);
83365         }
83366         /**
83367          * Visits and possibly transforms any node.
83368          *
83369          * @param node The node to visit.
83370          */
83371         function visitorWorker(node) {
83372             if (node.transformFlags & 1 /* ContainsTypeScript */) {
83373                 return visitTypeScript(node);
83374             }
83375             return node;
83376         }
83377         /**
83378          * Specialized visitor that visits the immediate children of a SourceFile.
83379          *
83380          * @param node The node to visit.
83381          */
83382         function sourceElementVisitor(node) {
83383             return saveStateAndInvoke(node, sourceElementVisitorWorker);
83384         }
83385         /**
83386          * Specialized visitor that visits the immediate children of a SourceFile.
83387          *
83388          * @param node The node to visit.
83389          */
83390         function sourceElementVisitorWorker(node) {
83391             switch (node.kind) {
83392                 case 261 /* ImportDeclaration */:
83393                 case 260 /* ImportEqualsDeclaration */:
83394                 case 266 /* ExportAssignment */:
83395                 case 267 /* ExportDeclaration */:
83396                     return visitElidableStatement(node);
83397                 default:
83398                     return visitorWorker(node);
83399             }
83400         }
83401         function visitElidableStatement(node) {
83402             var parsed = ts.getParseTreeNode(node);
83403             if (parsed !== node) {
83404                 // If the node has been transformed by a `before` transformer, perform no ellision on it
83405                 // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
83406                 // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
83407                 // and will trigger debug failures when debug verbosity is turned up
83408                 if (node.transformFlags & 1 /* ContainsTypeScript */) {
83409                     // This node contains TypeScript, so we should visit its children.
83410                     return ts.visitEachChild(node, visitor, context);
83411                 }
83412                 // Otherwise, we can just return the node
83413                 return node;
83414             }
83415             switch (node.kind) {
83416                 case 261 /* ImportDeclaration */:
83417                     return visitImportDeclaration(node);
83418                 case 260 /* ImportEqualsDeclaration */:
83419                     return visitImportEqualsDeclaration(node);
83420                 case 266 /* ExportAssignment */:
83421                     return visitExportAssignment(node);
83422                 case 267 /* ExportDeclaration */:
83423                     return visitExportDeclaration(node);
83424                 default:
83425                     ts.Debug.fail("Unhandled ellided statement");
83426             }
83427         }
83428         /**
83429          * Specialized visitor that visits the immediate children of a namespace.
83430          *
83431          * @param node The node to visit.
83432          */
83433         function namespaceElementVisitor(node) {
83434             return saveStateAndInvoke(node, namespaceElementVisitorWorker);
83435         }
83436         /**
83437          * Specialized visitor that visits the immediate children of a namespace.
83438          *
83439          * @param node The node to visit.
83440          */
83441         function namespaceElementVisitorWorker(node) {
83442             if (node.kind === 267 /* ExportDeclaration */ ||
83443                 node.kind === 261 /* ImportDeclaration */ ||
83444                 node.kind === 262 /* ImportClause */ ||
83445                 (node.kind === 260 /* ImportEqualsDeclaration */ &&
83446                     node.moduleReference.kind === 272 /* ExternalModuleReference */)) {
83447                 // do not emit ES6 imports and exports since they are illegal inside a namespace
83448                 return undefined;
83449             }
83450             else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasSyntacticModifier(node, 1 /* Export */)) {
83451                 return visitTypeScript(node);
83452             }
83453             return node;
83454         }
83455         /**
83456          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
83457          *
83458          * @param node The node to visit.
83459          */
83460         function classElementVisitor(node) {
83461             return saveStateAndInvoke(node, classElementVisitorWorker);
83462         }
83463         /**
83464          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
83465          *
83466          * @param node The node to visit.
83467          */
83468         function classElementVisitorWorker(node) {
83469             switch (node.kind) {
83470                 case 166 /* Constructor */:
83471                     return visitConstructor(node);
83472                 case 163 /* PropertyDeclaration */:
83473                     // Property declarations are not TypeScript syntax, but they must be visited
83474                     // for the decorator transformation.
83475                     return visitPropertyDeclaration(node);
83476                 case 171 /* IndexSignature */:
83477                 case 167 /* GetAccessor */:
83478                 case 168 /* SetAccessor */:
83479                 case 165 /* MethodDeclaration */:
83480                     // Fallback to the default visit behavior.
83481                     return visitorWorker(node);
83482                 case 229 /* SemicolonClassElement */:
83483                     return node;
83484                 default:
83485                     return ts.Debug.failBadSyntaxKind(node);
83486             }
83487         }
83488         function modifierVisitor(node) {
83489             if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) {
83490                 return undefined;
83491             }
83492             else if (currentNamespace && node.kind === 92 /* ExportKeyword */) {
83493                 return undefined;
83494             }
83495             return node;
83496         }
83497         /**
83498          * Branching visitor, visits a TypeScript syntax node.
83499          *
83500          * @param node The node to visit.
83501          */
83502         function visitTypeScript(node) {
83503             if (ts.isStatement(node) && ts.hasSyntacticModifier(node, 2 /* Ambient */)) {
83504                 // TypeScript ambient declarations are elided, but some comments may be preserved.
83505                 // See the implementation of `getLeadingComments` in comments.ts for more details.
83506                 return factory.createNotEmittedStatement(node);
83507             }
83508             switch (node.kind) {
83509                 case 92 /* ExportKeyword */:
83510                 case 87 /* DefaultKeyword */:
83511                     // ES6 export and default modifiers are elided when inside a namespace.
83512                     return currentNamespace ? undefined : node;
83513                 case 122 /* PublicKeyword */:
83514                 case 120 /* PrivateKeyword */:
83515                 case 121 /* ProtectedKeyword */:
83516                 case 125 /* AbstractKeyword */:
83517                 case 84 /* ConstKeyword */:
83518                 case 133 /* DeclareKeyword */:
83519                 case 142 /* ReadonlyKeyword */:
83520                 // TypeScript accessibility and readonly modifiers are elided
83521                 // falls through
83522                 case 178 /* ArrayType */:
83523                 case 179 /* TupleType */:
83524                 case 180 /* OptionalType */:
83525                 case 181 /* RestType */:
83526                 case 177 /* TypeLiteral */:
83527                 case 172 /* TypePredicate */:
83528                 case 159 /* TypeParameter */:
83529                 case 128 /* AnyKeyword */:
83530                 case 152 /* UnknownKeyword */:
83531                 case 131 /* BooleanKeyword */:
83532                 case 147 /* StringKeyword */:
83533                 case 144 /* NumberKeyword */:
83534                 case 141 /* NeverKeyword */:
83535                 case 113 /* VoidKeyword */:
83536                 case 148 /* SymbolKeyword */:
83537                 case 175 /* ConstructorType */:
83538                 case 174 /* FunctionType */:
83539                 case 176 /* TypeQuery */:
83540                 case 173 /* TypeReference */:
83541                 case 182 /* UnionType */:
83542                 case 183 /* IntersectionType */:
83543                 case 184 /* ConditionalType */:
83544                 case 186 /* ParenthesizedType */:
83545                 case 187 /* ThisType */:
83546                 case 188 /* TypeOperator */:
83547                 case 189 /* IndexedAccessType */:
83548                 case 190 /* MappedType */:
83549                 case 191 /* LiteralType */:
83550                 // TypeScript type nodes are elided.
83551                 // falls through
83552                 case 171 /* IndexSignature */:
83553                 // TypeScript index signatures are elided.
83554                 // falls through
83555                 case 161 /* Decorator */:
83556                 // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
83557                 // falls through
83558                 case 254 /* TypeAliasDeclaration */:
83559                     // TypeScript type-only declarations are elided.
83560                     return undefined;
83561                 case 163 /* PropertyDeclaration */:
83562                     // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
83563                     return visitPropertyDeclaration(node);
83564                 case 259 /* NamespaceExportDeclaration */:
83565                     // TypeScript namespace export declarations are elided.
83566                     return undefined;
83567                 case 166 /* Constructor */:
83568                     return visitConstructor(node);
83569                 case 253 /* InterfaceDeclaration */:
83570                     // TypeScript interfaces are elided, but some comments may be preserved.
83571                     // See the implementation of `getLeadingComments` in comments.ts for more details.
83572                     return factory.createNotEmittedStatement(node);
83573                 case 252 /* ClassDeclaration */:
83574                     // This may be a class declaration with TypeScript syntax extensions.
83575                     //
83576                     // TypeScript class syntax extensions include:
83577                     // - decorators
83578                     // - optional `implements` heritage clause
83579                     // - parameter property assignments in the constructor
83580                     // - index signatures
83581                     // - method overload signatures
83582                     return visitClassDeclaration(node);
83583                 case 221 /* ClassExpression */:
83584                     // This may be a class expression with TypeScript syntax extensions.
83585                     //
83586                     // TypeScript class syntax extensions include:
83587                     // - decorators
83588                     // - optional `implements` heritage clause
83589                     // - parameter property assignments in the constructor
83590                     // - index signatures
83591                     // - method overload signatures
83592                     return visitClassExpression(node);
83593                 case 286 /* HeritageClause */:
83594                     // This may be a heritage clause with TypeScript syntax extensions.
83595                     //
83596                     // TypeScript heritage clause extensions include:
83597                     // - `implements` clause
83598                     return visitHeritageClause(node);
83599                 case 223 /* ExpressionWithTypeArguments */:
83600                     // TypeScript supports type arguments on an expression in an `extends` heritage clause.
83601                     return visitExpressionWithTypeArguments(node);
83602                 case 165 /* MethodDeclaration */:
83603                     // TypeScript method declarations may have decorators, modifiers
83604                     // or type annotations.
83605                     return visitMethodDeclaration(node);
83606                 case 167 /* GetAccessor */:
83607                     // Get Accessors can have TypeScript modifiers, decorators, and type annotations.
83608                     return visitGetAccessor(node);
83609                 case 168 /* SetAccessor */:
83610                     // Set Accessors can have TypeScript modifiers and type annotations.
83611                     return visitSetAccessor(node);
83612                 case 251 /* FunctionDeclaration */:
83613                     // Typescript function declarations can have modifiers, decorators, and type annotations.
83614                     return visitFunctionDeclaration(node);
83615                 case 208 /* FunctionExpression */:
83616                     // TypeScript function expressions can have modifiers and type annotations.
83617                     return visitFunctionExpression(node);
83618                 case 209 /* ArrowFunction */:
83619                     // TypeScript arrow functions can have modifiers and type annotations.
83620                     return visitArrowFunction(node);
83621                 case 160 /* Parameter */:
83622                     // This may be a parameter declaration with TypeScript syntax extensions.
83623                     //
83624                     // TypeScript parameter declaration syntax extensions include:
83625                     // - decorators
83626                     // - accessibility modifiers
83627                     // - the question mark (?) token for optional parameters
83628                     // - type annotations
83629                     // - this parameters
83630                     return visitParameter(node);
83631                 case 207 /* ParenthesizedExpression */:
83632                     // ParenthesizedExpressions are TypeScript if their expression is a
83633                     // TypeAssertion or AsExpression
83634                     return visitParenthesizedExpression(node);
83635                 case 206 /* TypeAssertionExpression */:
83636                 case 224 /* AsExpression */:
83637                     // TypeScript type assertions are removed, but their subtrees are preserved.
83638                     return visitAssertionExpression(node);
83639                 case 203 /* CallExpression */:
83640                     return visitCallExpression(node);
83641                 case 204 /* NewExpression */:
83642                     return visitNewExpression(node);
83643                 case 205 /* TaggedTemplateExpression */:
83644                     return visitTaggedTemplateExpression(node);
83645                 case 225 /* NonNullExpression */:
83646                     // TypeScript non-null expressions are removed, but their subtrees are preserved.
83647                     return visitNonNullExpression(node);
83648                 case 255 /* EnumDeclaration */:
83649                     // TypeScript enum declarations do not exist in ES6 and must be rewritten.
83650                     return visitEnumDeclaration(node);
83651                 case 232 /* VariableStatement */:
83652                     // TypeScript namespace exports for variable statements must be transformed.
83653                     return visitVariableStatement(node);
83654                 case 249 /* VariableDeclaration */:
83655                     return visitVariableDeclaration(node);
83656                 case 256 /* ModuleDeclaration */:
83657                     // TypeScript namespace declarations must be transformed.
83658                     return visitModuleDeclaration(node);
83659                 case 260 /* ImportEqualsDeclaration */:
83660                     // TypeScript namespace or external module import.
83661                     return visitImportEqualsDeclaration(node);
83662                 case 274 /* JsxSelfClosingElement */:
83663                     return visitJsxSelfClosingElement(node);
83664                 case 275 /* JsxOpeningElement */:
83665                     return visitJsxJsxOpeningElement(node);
83666                 default:
83667                     // node contains some other TypeScript syntax
83668                     return ts.visitEachChild(node, visitor, context);
83669             }
83670         }
83671         function visitSourceFile(node) {
83672             var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") &&
83673                 !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) &&
83674                 !ts.isJsonSourceFile(node);
83675             return factory.updateSourceFile(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
83676         }
83677         /**
83678          * Tests whether we should emit a __decorate call for a class declaration.
83679          */
83680         function shouldEmitDecorateCallForClass(node) {
83681             if (node.decorators && node.decorators.length > 0) {
83682                 return true;
83683             }
83684             var constructor = ts.getFirstConstructorWithBody(node);
83685             if (constructor) {
83686                 return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter);
83687             }
83688             return false;
83689         }
83690         /**
83691          * Tests whether we should emit a __decorate call for a parameter declaration.
83692          */
83693         function shouldEmitDecorateCallForParameter(parameter) {
83694             return parameter.decorators !== undefined && parameter.decorators.length > 0;
83695         }
83696         function getClassFacts(node, staticProperties) {
83697             var facts = 0 /* None */;
83698             if (ts.some(staticProperties))
83699                 facts |= 1 /* HasStaticInitializedProperties */;
83700             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
83701             if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */)
83702                 facts |= 64 /* IsDerivedClass */;
83703             if (shouldEmitDecorateCallForClass(node))
83704                 facts |= 2 /* HasConstructorDecorators */;
83705             if (ts.childIsDecorated(node))
83706                 facts |= 4 /* HasMemberDecorators */;
83707             if (isExportOfNamespace(node))
83708                 facts |= 8 /* IsExportOfNamespace */;
83709             else if (isDefaultExternalModuleExport(node))
83710                 facts |= 32 /* IsDefaultExternalExport */;
83711             else if (isNamedExternalModuleExport(node))
83712                 facts |= 16 /* IsNamedExternalExport */;
83713             if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */))
83714                 facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
83715             return facts;
83716         }
83717         function hasTypeScriptClassSyntax(node) {
83718             return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */);
83719         }
83720         function isClassLikeDeclarationWithTypeScriptSyntax(node) {
83721             return ts.some(node.decorators)
83722                 || ts.some(node.typeParameters)
83723                 || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
83724                 || ts.some(node.members, hasTypeScriptClassSyntax);
83725         }
83726         function visitClassDeclaration(node) {
83727             if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasSyntacticModifier(node, 1 /* Export */))) {
83728                 return ts.visitEachChild(node, visitor, context);
83729             }
83730             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
83731             var facts = getClassFacts(node, staticProperties);
83732             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
83733                 context.startLexicalEnvironment();
83734             }
83735             var name = node.name || (facts & 5 /* NeedsName */ ? factory.getGeneratedNameForNode(node) : undefined);
83736             var classStatement = facts & 2 /* HasConstructorDecorators */
83737                 ? createClassDeclarationHeadWithDecorators(node, name)
83738                 : createClassDeclarationHeadWithoutDecorators(node, name, facts);
83739             var statements = [classStatement];
83740             // Write any decorators of the node.
83741             addClassElementDecorationStatements(statements, node, /*isStatic*/ false);
83742             addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
83743             addConstructorDecorationStatement(statements, node);
83744             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
83745                 // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
83746                 // 'es2015' transformer can properly nest static initializers and decorators. The result
83747                 // looks something like:
83748                 //
83749                 //  var C = function () {
83750                 //      class C {
83751                 //      }
83752                 //      C.static_prop = 1;
83753                 //      return C;
83754                 //  }();
83755                 //
83756                 var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */);
83757                 var localName = factory.getInternalName(node);
83758                 // The following partially-emitted expression exists purely to align our sourcemap
83759                 // emit with the original emitter.
83760                 var outer = factory.createPartiallyEmittedExpression(localName);
83761                 ts.setTextRangeEnd(outer, closingBraceLocation.end);
83762                 ts.setEmitFlags(outer, 1536 /* NoComments */);
83763                 var statement = factory.createReturnStatement(outer);
83764                 ts.setTextRangePos(statement, closingBraceLocation.pos);
83765                 ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
83766                 statements.push(statement);
83767                 ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
83768                 var iife = factory.createImmediatelyInvokedArrowFunction(statements);
83769                 ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
83770                 var varStatement = factory.createVariableStatement(
83771                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
83772                     factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), 
83773                     /*exclamationToken*/ undefined, 
83774                     /*type*/ undefined, iife)
83775                 ]));
83776                 ts.setOriginalNode(varStatement, node);
83777                 ts.setCommentRange(varStatement, node);
83778                 ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node));
83779                 ts.startOnNewLine(varStatement);
83780                 statements = [varStatement];
83781             }
83782             // If the class is exported as part of a TypeScript namespace, emit the namespace export.
83783             // Otherwise, if the class was exported at the top level and was decorated, emit an export
83784             // declaration or export default for the class.
83785             if (facts & 8 /* IsExportOfNamespace */) {
83786                 addExportMemberAssignment(statements, node);
83787             }
83788             else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) {
83789                 if (facts & 32 /* IsDefaultExternalExport */) {
83790                     statements.push(factory.createExportDefault(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
83791                 }
83792                 else if (facts & 16 /* IsNamedExternalExport */) {
83793                     statements.push(factory.createExternalModuleExport(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
83794                 }
83795             }
83796             if (statements.length > 1) {
83797                 // Add a DeclarationMarker as a marker for the end of the declaration
83798                 statements.push(factory.createEndOfDeclarationMarker(node));
83799                 ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */);
83800             }
83801             return ts.singleOrMany(statements);
83802         }
83803         /**
83804          * Transforms a non-decorated class declaration and appends the resulting statements.
83805          *
83806          * @param node A ClassDeclaration node.
83807          * @param name The name of the class.
83808          * @param facts Precomputed facts about the class.
83809          */
83810         function createClassDeclarationHeadWithoutDecorators(node, name, facts) {
83811             //  ${modifiers} class ${name} ${heritageClauses} {
83812             //      ${members}
83813             //  }
83814             // we do not emit modifiers on the declaration if we are emitting an IIFE
83815             var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */)
83816                 ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier)
83817                 : undefined;
83818             var classDeclaration = factory.createClassDeclaration(
83819             /*decorators*/ undefined, modifiers, name, 
83820             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
83821             // To better align with the old emitter, we should not emit a trailing source map
83822             // entry if the class has static properties.
83823             var emitFlags = ts.getEmitFlags(node);
83824             if (facts & 1 /* HasStaticInitializedProperties */) {
83825                 emitFlags |= 32 /* NoTrailingSourceMap */;
83826             }
83827             ts.setTextRange(classDeclaration, node);
83828             ts.setOriginalNode(classDeclaration, node);
83829             ts.setEmitFlags(classDeclaration, emitFlags);
83830             return classDeclaration;
83831         }
83832         /**
83833          * Transforms a decorated class declaration and appends the resulting statements. If
83834          * the class requires an alias to avoid issues with double-binding, the alias is returned.
83835          */
83836         function createClassDeclarationHeadWithDecorators(node, name) {
83837             // When we emit an ES6 class that has a class decorator, we must tailor the
83838             // emit to certain specific cases.
83839             //
83840             // In the simplest case, we emit the class declaration as a let declaration, and
83841             // evaluate decorators after the close of the class body:
83842             //
83843             //  [Example 1]
83844             //  ---------------------------------------------------------------------
83845             //  TypeScript                      | Javascript
83846             //  ---------------------------------------------------------------------
83847             //  @dec                            | let C = class C {
83848             //  class C {                       | }
83849             //  }                               | C = __decorate([dec], C);
83850             //  ---------------------------------------------------------------------
83851             //  @dec                            | let C = class C {
83852             //  export class C {                | }
83853             //  }                               | C = __decorate([dec], C);
83854             //                                  | export { C };
83855             //  ---------------------------------------------------------------------
83856             //
83857             // If a class declaration contains a reference to itself *inside* of the class body,
83858             // this introduces two bindings to the class: One outside of the class body, and one
83859             // inside of the class body. If we apply decorators as in [Example 1] above, there
83860             // is the possibility that the decorator `dec` will return a new value for the
83861             // constructor, which would result in the binding inside of the class no longer
83862             // pointing to the same reference as the binding outside of the class.
83863             //
83864             // As a result, we must instead rewrite all references to the class *inside* of the
83865             // class body to instead point to a local temporary alias for the class:
83866             //
83867             //  [Example 2]
83868             //  ---------------------------------------------------------------------
83869             //  TypeScript                      | Javascript
83870             //  ---------------------------------------------------------------------
83871             //  @dec                            | let C = C_1 = class C {
83872             //  class C {                       |   static x() { return C_1.y; }
83873             //    static x() { return C.y; }    | }
83874             //    static y = 1;                 | C.y = 1;
83875             //  }                               | C = C_1 = __decorate([dec], C);
83876             //                                  | var C_1;
83877             //  ---------------------------------------------------------------------
83878             //  @dec                            | let C = class C {
83879             //  export class C {                |   static x() { return C_1.y; }
83880             //    static x() { return C.y; }    | }
83881             //    static y = 1;                 | C.y = 1;
83882             //  }                               | C = C_1 = __decorate([dec], C);
83883             //                                  | export { C };
83884             //                                  | var C_1;
83885             //  ---------------------------------------------------------------------
83886             //
83887             // If a class declaration is the default export of a module, we instead emit
83888             // the export after the decorated declaration:
83889             //
83890             //  [Example 3]
83891             //  ---------------------------------------------------------------------
83892             //  TypeScript                      | Javascript
83893             //  ---------------------------------------------------------------------
83894             //  @dec                            | let default_1 = class {
83895             //  export default class {          | }
83896             //  }                               | default_1 = __decorate([dec], default_1);
83897             //                                  | export default default_1;
83898             //  ---------------------------------------------------------------------
83899             //  @dec                            | let C = class C {
83900             //  export default class C {        | }
83901             //  }                               | C = __decorate([dec], C);
83902             //                                  | export default C;
83903             //  ---------------------------------------------------------------------
83904             //
83905             // If the class declaration is the default export and a reference to itself
83906             // inside of the class body, we must emit both an alias for the class *and*
83907             // move the export after the declaration:
83908             //
83909             //  [Example 4]
83910             //  ---------------------------------------------------------------------
83911             //  TypeScript                      | Javascript
83912             //  ---------------------------------------------------------------------
83913             //  @dec                            | let C = class C {
83914             //  export default class C {        |   static x() { return C_1.y; }
83915             //    static x() { return C.y; }    | }
83916             //    static y = 1;                 | C.y = 1;
83917             //  }                               | C = C_1 = __decorate([dec], C);
83918             //                                  | export default C;
83919             //                                  | var C_1;
83920             //  ---------------------------------------------------------------------
83921             //
83922             var location = ts.moveRangePastDecorators(node);
83923             var classAlias = getClassAliasIfNeeded(node);
83924             var declName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
83925             //  ... = class ${name} ${heritageClauses} {
83926             //      ${members}
83927             //  }
83928             var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
83929             var members = transformClassMembers(node);
83930             var classExpression = factory.createClassExpression(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
83931             ts.setOriginalNode(classExpression, node);
83932             ts.setTextRange(classExpression, location);
83933             //  let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
83934             //                                         or decoratedClassAlias if the class contain self-reference.
83935             var statement = factory.createVariableStatement(
83936             /*modifiers*/ undefined, factory.createVariableDeclarationList([
83937                 factory.createVariableDeclaration(declName, 
83938                 /*exclamationToken*/ undefined, 
83939                 /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression)
83940             ], 1 /* Let */));
83941             ts.setOriginalNode(statement, node);
83942             ts.setTextRange(statement, location);
83943             ts.setCommentRange(statement, node);
83944             return statement;
83945         }
83946         function visitClassExpression(node) {
83947             if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
83948                 return ts.visitEachChild(node, visitor, context);
83949             }
83950             var classExpression = factory.createClassExpression(
83951             /*decorators*/ undefined, 
83952             /*modifiers*/ undefined, node.name, 
83953             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
83954             ts.setOriginalNode(classExpression, node);
83955             ts.setTextRange(classExpression, node);
83956             return classExpression;
83957         }
83958         /**
83959          * Transforms the members of a class.
83960          *
83961          * @param node The current class.
83962          */
83963         function transformClassMembers(node) {
83964             var members = [];
83965             var constructor = ts.getFirstConstructorWithBody(node);
83966             var parametersWithPropertyAssignments = constructor &&
83967                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
83968             if (parametersWithPropertyAssignments) {
83969                 for (var _i = 0, parametersWithPropertyAssignments_1 = parametersWithPropertyAssignments; _i < parametersWithPropertyAssignments_1.length; _i++) {
83970                     var parameter = parametersWithPropertyAssignments_1[_i];
83971                     if (ts.isIdentifier(parameter.name)) {
83972                         members.push(ts.setOriginalNode(factory.createPropertyDeclaration(
83973                         /*decorators*/ undefined, 
83974                         /*modifiers*/ undefined, parameter.name, 
83975                         /*questionOrExclamationToken*/ undefined, 
83976                         /*type*/ undefined, 
83977                         /*initializer*/ undefined), parameter));
83978                     }
83979                 }
83980             }
83981             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
83982             return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members);
83983         }
83984         /**
83985          * Gets either the static or instance members of a class that are decorated, or have
83986          * parameters that are decorated.
83987          *
83988          * @param node The class containing the member.
83989          * @param isStatic A value indicating whether to retrieve static or instance members of
83990          *                 the class.
83991          */
83992         function getDecoratedClassElements(node, isStatic) {
83993             return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); });
83994         }
83995         /**
83996          * Determines whether a class member is a static member of a class that is decorated, or
83997          * has parameters that are decorated.
83998          *
83999          * @param member The class member.
84000          */
84001         function isStaticDecoratedClassElement(member, parent) {
84002             return isDecoratedClassElement(member, /*isStatic*/ true, parent);
84003         }
84004         /**
84005          * Determines whether a class member is an instance member of a class that is decorated,
84006          * or has parameters that are decorated.
84007          *
84008          * @param member The class member.
84009          */
84010         function isInstanceDecoratedClassElement(member, parent) {
84011             return isDecoratedClassElement(member, /*isStatic*/ false, parent);
84012         }
84013         /**
84014          * Determines whether a class member is either a static or an instance member of a class
84015          * that is decorated, or has parameters that are decorated.
84016          *
84017          * @param member The class member.
84018          */
84019         function isDecoratedClassElement(member, isStatic, parent) {
84020             return ts.nodeOrChildIsDecorated(member, parent)
84021                 && isStatic === ts.hasSyntacticModifier(member, 32 /* Static */);
84022         }
84023         /**
84024          * Gets an array of arrays of decorators for the parameters of a function-like node.
84025          * The offset into the result array should correspond to the offset of the parameter.
84026          *
84027          * @param node The function-like node.
84028          */
84029         function getDecoratorsOfParameters(node) {
84030             var decorators;
84031             if (node) {
84032                 var parameters = node.parameters;
84033                 var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
84034                 var firstParameterOffset = firstParameterIsThis ? 1 : 0;
84035                 var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
84036                 for (var i = 0; i < numParameters; i++) {
84037                     var parameter = parameters[i + firstParameterOffset];
84038                     if (decorators || parameter.decorators) {
84039                         if (!decorators) {
84040                             decorators = new Array(numParameters);
84041                         }
84042                         decorators[i] = parameter.decorators;
84043                     }
84044                 }
84045             }
84046             return decorators;
84047         }
84048         /**
84049          * Gets an AllDecorators object containing the decorators for the class and the decorators for the
84050          * parameters of the constructor of the class.
84051          *
84052          * @param node The class node.
84053          */
84054         function getAllDecoratorsOfConstructor(node) {
84055             var decorators = node.decorators;
84056             var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node));
84057             if (!decorators && !parameters) {
84058                 return undefined;
84059             }
84060             return {
84061                 decorators: decorators,
84062                 parameters: parameters
84063             };
84064         }
84065         /**
84066          * Gets an AllDecorators object containing the decorators for the member and its parameters.
84067          *
84068          * @param node The class node that contains the member.
84069          * @param member The class member.
84070          */
84071         function getAllDecoratorsOfClassElement(node, member) {
84072             switch (member.kind) {
84073                 case 167 /* GetAccessor */:
84074                 case 168 /* SetAccessor */:
84075                     return getAllDecoratorsOfAccessors(node, member);
84076                 case 165 /* MethodDeclaration */:
84077                     return getAllDecoratorsOfMethod(member);
84078                 case 163 /* PropertyDeclaration */:
84079                     return getAllDecoratorsOfProperty(member);
84080                 default:
84081                     return undefined;
84082             }
84083         }
84084         /**
84085          * Gets an AllDecorators object containing the decorators for the accessor and its parameters.
84086          *
84087          * @param node The class node that contains the accessor.
84088          * @param accessor The class accessor member.
84089          */
84090         function getAllDecoratorsOfAccessors(node, accessor) {
84091             if (!accessor.body) {
84092                 return undefined;
84093             }
84094             var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor;
84095             var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined;
84096             if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
84097                 return undefined;
84098             }
84099             var decorators = firstAccessorWithDecorators.decorators;
84100             var parameters = getDecoratorsOfParameters(setAccessor);
84101             if (!decorators && !parameters) {
84102                 return undefined;
84103             }
84104             return { decorators: decorators, parameters: parameters };
84105         }
84106         /**
84107          * Gets an AllDecorators object containing the decorators for the method and its parameters.
84108          *
84109          * @param method The class method member.
84110          */
84111         function getAllDecoratorsOfMethod(method) {
84112             if (!method.body) {
84113                 return undefined;
84114             }
84115             var decorators = method.decorators;
84116             var parameters = getDecoratorsOfParameters(method);
84117             if (!decorators && !parameters) {
84118                 return undefined;
84119             }
84120             return { decorators: decorators, parameters: parameters };
84121         }
84122         /**
84123          * Gets an AllDecorators object containing the decorators for the property.
84124          *
84125          * @param property The class property member.
84126          */
84127         function getAllDecoratorsOfProperty(property) {
84128             var decorators = property.decorators;
84129             if (!decorators) {
84130                 return undefined;
84131             }
84132             return { decorators: decorators };
84133         }
84134         /**
84135          * Transforms all of the decorators for a declaration into an array of expressions.
84136          *
84137          * @param node The declaration node.
84138          * @param allDecorators An object containing all of the decorators for the declaration.
84139          */
84140         function transformAllDecoratorsOfDeclaration(node, container, allDecorators) {
84141             if (!allDecorators) {
84142                 return undefined;
84143             }
84144             var decoratorExpressions = [];
84145             ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator));
84146             ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
84147             addTypeMetadata(node, container, decoratorExpressions);
84148             return decoratorExpressions;
84149         }
84150         /**
84151          * Generates statements used to apply decorators to either the static or instance members
84152          * of a class.
84153          *
84154          * @param node The class node.
84155          * @param isStatic A value indicating whether to generate statements for static or
84156          *                 instance members.
84157          */
84158         function addClassElementDecorationStatements(statements, node, isStatic) {
84159             ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement));
84160         }
84161         /**
84162          * Generates expressions used to apply decorators to either the static or instance members
84163          * of a class.
84164          *
84165          * @param node The class node.
84166          * @param isStatic A value indicating whether to generate expressions for static or
84167          *                 instance members.
84168          */
84169         function generateClassElementDecorationExpressions(node, isStatic) {
84170             var members = getDecoratedClassElements(node, isStatic);
84171             var expressions;
84172             for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
84173                 var member = members_6[_i];
84174                 var expression = generateClassElementDecorationExpression(node, member);
84175                 if (expression) {
84176                     if (!expressions) {
84177                         expressions = [expression];
84178                     }
84179                     else {
84180                         expressions.push(expression);
84181                     }
84182                 }
84183             }
84184             return expressions;
84185         }
84186         /**
84187          * Generates an expression used to evaluate class element decorators at runtime.
84188          *
84189          * @param node The class node that contains the member.
84190          * @param member The class member.
84191          */
84192         function generateClassElementDecorationExpression(node, member) {
84193             var allDecorators = getAllDecoratorsOfClassElement(node, member);
84194             var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators);
84195             if (!decoratorExpressions) {
84196                 return undefined;
84197             }
84198             // Emit the call to __decorate. Given the following:
84199             //
84200             //   class C {
84201             //     @dec method(@dec2 x) {}
84202             //     @dec get accessor() {}
84203             //     @dec prop;
84204             //   }
84205             //
84206             // The emit for a method is:
84207             //
84208             //   __decorate([
84209             //       dec,
84210             //       __param(0, dec2),
84211             //       __metadata("design:type", Function),
84212             //       __metadata("design:paramtypes", [Object]),
84213             //       __metadata("design:returntype", void 0)
84214             //   ], C.prototype, "method", null);
84215             //
84216             // The emit for an accessor is:
84217             //
84218             //   __decorate([
84219             //       dec
84220             //   ], C.prototype, "accessor", null);
84221             //
84222             // The emit for a property is:
84223             //
84224             //   __decorate([
84225             //       dec
84226             //   ], C.prototype, "prop");
84227             //
84228             var prefix = getClassMemberPrefix(node, member);
84229             var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
84230             var descriptor = languageVersion > 0 /* ES3 */
84231                 ? member.kind === 163 /* PropertyDeclaration */
84232                     // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it
84233                     // should not invoke `Object.getOwnPropertyDescriptor`.
84234                     ? factory.createVoidZero()
84235                     // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.
84236                     // We have this extra argument here so that we can inject an explicit property descriptor at a later date.
84237                     : factory.createNull()
84238                 : undefined;
84239             var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor);
84240             ts.setTextRange(helper, ts.moveRangePastDecorators(member));
84241             ts.setEmitFlags(helper, 1536 /* NoComments */);
84242             return helper;
84243         }
84244         /**
84245          * Generates a __decorate helper call for a class constructor.
84246          *
84247          * @param node The class node.
84248          */
84249         function addConstructorDecorationStatement(statements, node) {
84250             var expression = generateConstructorDecorationExpression(node);
84251             if (expression) {
84252                 statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node));
84253             }
84254         }
84255         /**
84256          * Generates a __decorate helper call for a class constructor.
84257          *
84258          * @param node The class node.
84259          */
84260         function generateConstructorDecorationExpression(node) {
84261             var allDecorators = getAllDecoratorsOfConstructor(node);
84262             var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
84263             if (!decoratorExpressions) {
84264                 return undefined;
84265             }
84266             var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)];
84267             var localName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
84268             var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName);
84269             var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate);
84270             ts.setEmitFlags(expression, 1536 /* NoComments */);
84271             ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node));
84272             return expression;
84273         }
84274         /**
84275          * Transforms a decorator into an expression.
84276          *
84277          * @param decorator The decorator node.
84278          */
84279         function transformDecorator(decorator) {
84280             return ts.visitNode(decorator.expression, visitor, ts.isExpression);
84281         }
84282         /**
84283          * Transforms the decorators of a parameter.
84284          *
84285          * @param decorators The decorators for the parameter at the provided offset.
84286          * @param parameterOffset The offset of the parameter.
84287          */
84288         function transformDecoratorsOfParameter(decorators, parameterOffset) {
84289             var expressions;
84290             if (decorators) {
84291                 expressions = [];
84292                 for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) {
84293                     var decorator = decorators_1[_i];
84294                     var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset);
84295                     ts.setTextRange(helper, decorator.expression);
84296                     ts.setEmitFlags(helper, 1536 /* NoComments */);
84297                     expressions.push(helper);
84298                 }
84299             }
84300             return expressions;
84301         }
84302         /**
84303          * Adds optional type metadata for a declaration.
84304          *
84305          * @param node The declaration node.
84306          * @param decoratorExpressions The destination array to which to add new decorator expressions.
84307          */
84308         function addTypeMetadata(node, container, decoratorExpressions) {
84309             if (USE_NEW_TYPE_METADATA_FORMAT) {
84310                 addNewTypeMetadata(node, container, decoratorExpressions);
84311             }
84312             else {
84313                 addOldTypeMetadata(node, container, decoratorExpressions);
84314             }
84315         }
84316         function addOldTypeMetadata(node, container, decoratorExpressions) {
84317             if (compilerOptions.emitDecoratorMetadata) {
84318                 if (shouldAddTypeMetadata(node)) {
84319                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:type", serializeTypeOfNode(node)));
84320                 }
84321                 if (shouldAddParamTypesMetadata(node)) {
84322                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:paramtypes", serializeParameterTypesOfNode(node, container)));
84323                 }
84324                 if (shouldAddReturnTypeMetadata(node)) {
84325                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:returntype", serializeReturnTypeOfNode(node)));
84326                 }
84327             }
84328         }
84329         function addNewTypeMetadata(node, container, decoratorExpressions) {
84330             if (compilerOptions.emitDecoratorMetadata) {
84331                 var properties = void 0;
84332                 if (shouldAddTypeMetadata(node)) {
84333                     (properties || (properties = [])).push(factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* EqualsGreaterThanToken */), serializeTypeOfNode(node))));
84334                 }
84335                 if (shouldAddParamTypesMetadata(node)) {
84336                     (properties || (properties = [])).push(factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container))));
84337                 }
84338                 if (shouldAddReturnTypeMetadata(node)) {
84339                     (properties || (properties = [])).push(factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node))));
84340                 }
84341                 if (properties) {
84342                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true)));
84343                 }
84344             }
84345         }
84346         /**
84347          * Determines whether to emit the "design:type" metadata based on the node's kind.
84348          * The caller should have already tested whether the node has decorators and whether the
84349          * emitDecoratorMetadata compiler option is set.
84350          *
84351          * @param node The node to test.
84352          */
84353         function shouldAddTypeMetadata(node) {
84354             var kind = node.kind;
84355             return kind === 165 /* MethodDeclaration */
84356                 || kind === 167 /* GetAccessor */
84357                 || kind === 168 /* SetAccessor */
84358                 || kind === 163 /* PropertyDeclaration */;
84359         }
84360         /**
84361          * Determines whether to emit the "design:returntype" metadata based on the node's kind.
84362          * The caller should have already tested whether the node has decorators and whether the
84363          * emitDecoratorMetadata compiler option is set.
84364          *
84365          * @param node The node to test.
84366          */
84367         function shouldAddReturnTypeMetadata(node) {
84368             return node.kind === 165 /* MethodDeclaration */;
84369         }
84370         /**
84371          * Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
84372          * The caller should have already tested whether the node has decorators and whether the
84373          * emitDecoratorMetadata compiler option is set.
84374          *
84375          * @param node The node to test.
84376          */
84377         function shouldAddParamTypesMetadata(node) {
84378             switch (node.kind) {
84379                 case 252 /* ClassDeclaration */:
84380                 case 221 /* ClassExpression */:
84381                     return ts.getFirstConstructorWithBody(node) !== undefined;
84382                 case 165 /* MethodDeclaration */:
84383                 case 167 /* GetAccessor */:
84384                 case 168 /* SetAccessor */:
84385                     return true;
84386             }
84387             return false;
84388         }
84389         function getAccessorTypeNode(node) {
84390             var accessors = resolver.getAllAccessorDeclarations(node);
84391             return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor)
84392                 || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor);
84393         }
84394         /**
84395          * Serializes the type of a node for use with decorator type metadata.
84396          *
84397          * @param node The node that should have its type serialized.
84398          */
84399         function serializeTypeOfNode(node) {
84400             switch (node.kind) {
84401                 case 163 /* PropertyDeclaration */:
84402                 case 160 /* Parameter */:
84403                     return serializeTypeNode(node.type);
84404                 case 168 /* SetAccessor */:
84405                 case 167 /* GetAccessor */:
84406                     return serializeTypeNode(getAccessorTypeNode(node));
84407                 case 252 /* ClassDeclaration */:
84408                 case 221 /* ClassExpression */:
84409                 case 165 /* MethodDeclaration */:
84410                     return factory.createIdentifier("Function");
84411                 default:
84412                     return factory.createVoidZero();
84413             }
84414         }
84415         /**
84416          * Serializes the types of the parameters of a node for use with decorator type metadata.
84417          *
84418          * @param node The node that should have its parameter types serialized.
84419          */
84420         function serializeParameterTypesOfNode(node, container) {
84421             var valueDeclaration = ts.isClassLike(node)
84422                 ? ts.getFirstConstructorWithBody(node)
84423                 : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)
84424                     ? node
84425                     : undefined;
84426             var expressions = [];
84427             if (valueDeclaration) {
84428                 var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
84429                 var numParameters = parameters.length;
84430                 for (var i = 0; i < numParameters; i++) {
84431                     var parameter = parameters[i];
84432                     if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
84433                         continue;
84434                     }
84435                     if (parameter.dotDotDotToken) {
84436                         expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type)));
84437                     }
84438                     else {
84439                         expressions.push(serializeTypeOfNode(parameter));
84440                     }
84441                 }
84442             }
84443             return factory.createArrayLiteralExpression(expressions);
84444         }
84445         function getParametersOfDecoratedDeclaration(node, container) {
84446             if (container && node.kind === 167 /* GetAccessor */) {
84447                 var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor;
84448                 if (setAccessor) {
84449                     return setAccessor.parameters;
84450                 }
84451             }
84452             return node.parameters;
84453         }
84454         /**
84455          * Serializes the return type of a node for use with decorator type metadata.
84456          *
84457          * @param node The node that should have its return type serialized.
84458          */
84459         function serializeReturnTypeOfNode(node) {
84460             if (ts.isFunctionLike(node) && node.type) {
84461                 return serializeTypeNode(node.type);
84462             }
84463             else if (ts.isAsyncFunction(node)) {
84464                 return factory.createIdentifier("Promise");
84465             }
84466             return factory.createVoidZero();
84467         }
84468         /**
84469          * Serializes a type node for use with decorator type metadata.
84470          *
84471          * Types are serialized in the following fashion:
84472          * - Void types point to "undefined" (e.g. "void 0")
84473          * - Function and Constructor types point to the global "Function" constructor.
84474          * - Interface types with a call or construct signature types point to the global
84475          *   "Function" constructor.
84476          * - Array and Tuple types point to the global "Array" constructor.
84477          * - Type predicates and booleans point to the global "Boolean" constructor.
84478          * - String literal types and strings point to the global "String" constructor.
84479          * - Enum and number types point to the global "Number" constructor.
84480          * - Symbol types point to the global "Symbol" constructor.
84481          * - Type references to classes (or class-like variables) point to the constructor for the class.
84482          * - Anything else points to the global "Object" constructor.
84483          *
84484          * @param node The type node to serialize.
84485          */
84486         function serializeTypeNode(node) {
84487             if (node === undefined) {
84488                 return factory.createIdentifier("Object");
84489             }
84490             switch (node.kind) {
84491                 case 113 /* VoidKeyword */:
84492                 case 150 /* UndefinedKeyword */:
84493                 case 141 /* NeverKeyword */:
84494                     return factory.createVoidZero();
84495                 case 186 /* ParenthesizedType */:
84496                     return serializeTypeNode(node.type);
84497                 case 174 /* FunctionType */:
84498                 case 175 /* ConstructorType */:
84499                     return factory.createIdentifier("Function");
84500                 case 178 /* ArrayType */:
84501                 case 179 /* TupleType */:
84502                     return factory.createIdentifier("Array");
84503                 case 172 /* TypePredicate */:
84504                 case 131 /* BooleanKeyword */:
84505                     return factory.createIdentifier("Boolean");
84506                 case 147 /* StringKeyword */:
84507                     return factory.createIdentifier("String");
84508                 case 145 /* ObjectKeyword */:
84509                     return factory.createIdentifier("Object");
84510                 case 191 /* LiteralType */:
84511                     switch (node.literal.kind) {
84512                         case 10 /* StringLiteral */:
84513                         case 14 /* NoSubstitutionTemplateLiteral */:
84514                             return factory.createIdentifier("String");
84515                         case 214 /* PrefixUnaryExpression */:
84516                         case 8 /* NumericLiteral */:
84517                             return factory.createIdentifier("Number");
84518                         case 9 /* BigIntLiteral */:
84519                             return getGlobalBigIntNameWithFallback();
84520                         case 109 /* TrueKeyword */:
84521                         case 94 /* FalseKeyword */:
84522                             return factory.createIdentifier("Boolean");
84523                         case 103 /* NullKeyword */:
84524                             return factory.createVoidZero();
84525                         default:
84526                             return ts.Debug.failBadSyntaxKind(node.literal);
84527                     }
84528                 case 144 /* NumberKeyword */:
84529                     return factory.createIdentifier("Number");
84530                 case 155 /* BigIntKeyword */:
84531                     return getGlobalBigIntNameWithFallback();
84532                 case 148 /* SymbolKeyword */:
84533                     return languageVersion < 2 /* ES2015 */
84534                         ? getGlobalSymbolNameWithFallback()
84535                         : factory.createIdentifier("Symbol");
84536                 case 173 /* TypeReference */:
84537                     return serializeTypeReferenceNode(node);
84538                 case 183 /* IntersectionType */:
84539                 case 182 /* UnionType */:
84540                     return serializeTypeList(node.types);
84541                 case 184 /* ConditionalType */:
84542                     return serializeTypeList([node.trueType, node.falseType]);
84543                 case 188 /* TypeOperator */:
84544                     if (node.operator === 142 /* ReadonlyKeyword */) {
84545                         return serializeTypeNode(node.type);
84546                     }
84547                     break;
84548                 case 176 /* TypeQuery */:
84549                 case 189 /* IndexedAccessType */:
84550                 case 190 /* MappedType */:
84551                 case 177 /* TypeLiteral */:
84552                 case 128 /* AnyKeyword */:
84553                 case 152 /* UnknownKeyword */:
84554                 case 187 /* ThisType */:
84555                 case 195 /* ImportType */:
84556                     break;
84557                 // handle JSDoc types from an invalid parse
84558                 case 303 /* JSDocAllType */:
84559                 case 304 /* JSDocUnknownType */:
84560                 case 308 /* JSDocFunctionType */:
84561                 case 309 /* JSDocVariadicType */:
84562                 case 310 /* JSDocNamepathType */:
84563                     break;
84564                 case 305 /* JSDocNullableType */:
84565                 case 306 /* JSDocNonNullableType */:
84566                 case 307 /* JSDocOptionalType */:
84567                     return serializeTypeNode(node.type);
84568                 default:
84569                     return ts.Debug.failBadSyntaxKind(node);
84570             }
84571             return factory.createIdentifier("Object");
84572         }
84573         function serializeTypeList(types) {
84574             // Note when updating logic here also update getEntityNameForDecoratorMetadata
84575             // so that aliases can be marked as referenced
84576             var serializedUnion;
84577             for (var _i = 0, types_24 = types; _i < types_24.length; _i++) {
84578                 var typeNode = types_24[_i];
84579                 while (typeNode.kind === 186 /* ParenthesizedType */) {
84580                     typeNode = typeNode.type; // Skip parens if need be
84581                 }
84582                 if (typeNode.kind === 141 /* NeverKeyword */) {
84583                     continue; // Always elide `never` from the union/intersection if possible
84584                 }
84585                 if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) {
84586                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
84587                 }
84588                 var serializedIndividual = serializeTypeNode(typeNode);
84589                 if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") {
84590                     // One of the individual is global object, return immediately
84591                     return serializedIndividual;
84592                 }
84593                 // If there exists union that is not void 0 expression, check if the the common type is identifier.
84594                 // anything more complex and we will just default to Object
84595                 else if (serializedUnion) {
84596                     // Different types
84597                     if (!ts.isIdentifier(serializedUnion) ||
84598                         !ts.isIdentifier(serializedIndividual) ||
84599                         serializedUnion.escapedText !== serializedIndividual.escapedText) {
84600                         return factory.createIdentifier("Object");
84601                     }
84602                 }
84603                 else {
84604                     // Initialize the union type
84605                     serializedUnion = serializedIndividual;
84606                 }
84607             }
84608             // If we were able to find common type, use it
84609             return serializedUnion || factory.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never
84610         }
84611         /**
84612          * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with
84613          * decorator type metadata.
84614          *
84615          * @param node The type reference node.
84616          */
84617         function serializeTypeReferenceNode(node) {
84618             var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope);
84619             switch (kind) {
84620                 case ts.TypeReferenceSerializationKind.Unknown:
84621                     // From conditional type type reference that cannot be resolved is Similar to any or unknown
84622                     if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) {
84623                         return factory.createIdentifier("Object");
84624                     }
84625                     var serialized = serializeEntityNameAsExpressionFallback(node.typeName);
84626                     var temp = factory.createTempVariable(hoistVariableDeclaration);
84627                     return factory.createConditionalExpression(factory.createTypeCheck(factory.createAssignment(temp, serialized), "function"), 
84628                     /*questionToken*/ undefined, temp, 
84629                     /*colonToken*/ undefined, factory.createIdentifier("Object"));
84630                 case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
84631                     return serializeEntityNameAsExpression(node.typeName);
84632                 case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType:
84633                     return factory.createVoidZero();
84634                 case ts.TypeReferenceSerializationKind.BigIntLikeType:
84635                     return getGlobalBigIntNameWithFallback();
84636                 case ts.TypeReferenceSerializationKind.BooleanType:
84637                     return factory.createIdentifier("Boolean");
84638                 case ts.TypeReferenceSerializationKind.NumberLikeType:
84639                     return factory.createIdentifier("Number");
84640                 case ts.TypeReferenceSerializationKind.StringLikeType:
84641                     return factory.createIdentifier("String");
84642                 case ts.TypeReferenceSerializationKind.ArrayLikeType:
84643                     return factory.createIdentifier("Array");
84644                 case ts.TypeReferenceSerializationKind.ESSymbolType:
84645                     return languageVersion < 2 /* ES2015 */
84646                         ? getGlobalSymbolNameWithFallback()
84647                         : factory.createIdentifier("Symbol");
84648                 case ts.TypeReferenceSerializationKind.TypeWithCallSignature:
84649                     return factory.createIdentifier("Function");
84650                 case ts.TypeReferenceSerializationKind.Promise:
84651                     return factory.createIdentifier("Promise");
84652                 case ts.TypeReferenceSerializationKind.ObjectType:
84653                     return factory.createIdentifier("Object");
84654                 default:
84655                     return ts.Debug.assertNever(kind);
84656             }
84657         }
84658         function createCheckedValue(left, right) {
84659             return factory.createLogicalAnd(factory.createStrictInequality(factory.createTypeOfExpression(left), factory.createStringLiteral("undefined")), right);
84660         }
84661         /**
84662          * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw
84663          *
84664          * @param node The entity name to serialize.
84665          */
84666         function serializeEntityNameAsExpressionFallback(node) {
84667             if (node.kind === 78 /* Identifier */) {
84668                 // A -> typeof A !== undefined && A
84669                 var copied = serializeEntityNameAsExpression(node);
84670                 return createCheckedValue(copied, copied);
84671             }
84672             if (node.left.kind === 78 /* Identifier */) {
84673                 // A.B -> typeof A !== undefined && A.B
84674                 return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
84675             }
84676             // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C
84677             var left = serializeEntityNameAsExpressionFallback(node.left);
84678             var temp = factory.createTempVariable(hoistVariableDeclaration);
84679             return factory.createLogicalAnd(factory.createLogicalAnd(left.left, factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero())), factory.createPropertyAccessExpression(temp, node.right));
84680         }
84681         /**
84682          * Serializes an entity name as an expression for decorator type metadata.
84683          *
84684          * @param node The entity name to serialize.
84685          */
84686         function serializeEntityNameAsExpression(node) {
84687             switch (node.kind) {
84688                 case 78 /* Identifier */:
84689                     // Create a clone of the name with a new parent, and treat it as if it were
84690                     // a source tree node for the purposes of the checker.
84691                     var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent);
84692                     name.original = undefined;
84693                     ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node.
84694                     return name;
84695                 case 157 /* QualifiedName */:
84696                     return serializeQualifiedNameAsExpression(node);
84697             }
84698         }
84699         /**
84700          * Serializes an qualified name as an expression for decorator type metadata.
84701          *
84702          * @param node The qualified name to serialize.
84703          * @param useFallback A value indicating whether to use logical operators to test for the
84704          *                    qualified name at runtime.
84705          */
84706         function serializeQualifiedNameAsExpression(node) {
84707             return factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right);
84708         }
84709         /**
84710          * Gets an expression that points to the global "Symbol" constructor at runtime if it is
84711          * available.
84712          */
84713         function getGlobalSymbolNameWithFallback() {
84714             return factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("Symbol"), "function"), 
84715             /*questionToken*/ undefined, factory.createIdentifier("Symbol"), 
84716             /*colonToken*/ undefined, factory.createIdentifier("Object"));
84717         }
84718         /**
84719          * Gets an expression that points to the global "BigInt" constructor at runtime if it is
84720          * available.
84721          */
84722         function getGlobalBigIntNameWithFallback() {
84723             return languageVersion < 99 /* ESNext */
84724                 ? factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("BigInt"), "function"), 
84725                 /*questionToken*/ undefined, factory.createIdentifier("BigInt"), 
84726                 /*colonToken*/ undefined, factory.createIdentifier("Object"))
84727                 : factory.createIdentifier("BigInt");
84728         }
84729         /**
84730          * Gets an expression that represents a property name (for decorated properties or enums).
84731          * For a computed property, a name is generated for the node.
84732          *
84733          * @param member The member whose name should be converted into an expression.
84734          */
84735         function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
84736             var name = member.name;
84737             if (ts.isPrivateIdentifier(name)) {
84738                 return factory.createIdentifier("");
84739             }
84740             else if (ts.isComputedPropertyName(name)) {
84741                 return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression)
84742                     ? factory.getGeneratedNameForNode(name)
84743                     : name.expression;
84744             }
84745             else if (ts.isIdentifier(name)) {
84746                 return factory.createStringLiteral(ts.idText(name));
84747             }
84748             else {
84749                 return factory.cloneNode(name);
84750             }
84751         }
84752         /**
84753          * Visits the property name of a class element, for use when emitting property
84754          * initializers. For a computed property on a node with decorators, a temporary
84755          * value is stored for later use.
84756          *
84757          * @param member The member whose name should be visited.
84758          */
84759         function visitPropertyNameOfClassElement(member) {
84760             var name = member.name;
84761             // Computed property names need to be transformed into a hoisted variable when they are used more than once.
84762             // The names are used more than once when:
84763             //   - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments).
84764             //   - the property has a decorator.
84765             if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) {
84766                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
84767                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
84768                 if (!ts.isSimpleInlineableExpression(innerExpression)) {
84769                     var generatedName = factory.getGeneratedNameForNode(name);
84770                     hoistVariableDeclaration(generatedName);
84771                     return factory.updateComputedPropertyName(name, factory.createAssignment(generatedName, expression));
84772                 }
84773             }
84774             return ts.visitNode(name, visitor, ts.isPropertyName);
84775         }
84776         /**
84777          * Transforms a HeritageClause with TypeScript syntax.
84778          *
84779          * This function will only be called when one of the following conditions are met:
84780          * - The node is a non-`extends` heritage clause that should be elided.
84781          * - The node is an `extends` heritage clause that should be visited, but only allow a single type.
84782          *
84783          * @param node The HeritageClause to transform.
84784          */
84785         function visitHeritageClause(node) {
84786             if (node.token === 116 /* ImplementsKeyword */) {
84787                 // implements clauses are elided
84788                 return undefined;
84789             }
84790             return ts.visitEachChild(node, visitor, context);
84791         }
84792         /**
84793          * Transforms an ExpressionWithTypeArguments with TypeScript syntax.
84794          *
84795          * This function will only be called when one of the following conditions are met:
84796          * - The node contains type arguments that should be elided.
84797          *
84798          * @param node The ExpressionWithTypeArguments to transform.
84799          */
84800         function visitExpressionWithTypeArguments(node) {
84801             return factory.updateExpressionWithTypeArguments(node, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression), 
84802             /*typeArguments*/ undefined);
84803         }
84804         /**
84805          * Determines whether to emit a function-like declaration. We should not emit the
84806          * declaration if it does not have a body.
84807          *
84808          * @param node The declaration node.
84809          */
84810         function shouldEmitFunctionLikeDeclaration(node) {
84811             return !ts.nodeIsMissing(node.body);
84812         }
84813         function visitPropertyDeclaration(node) {
84814             if (node.flags & 8388608 /* Ambient */ || ts.hasSyntacticModifier(node, 128 /* Abstract */)) {
84815                 return undefined;
84816             }
84817             var updated = factory.updatePropertyDeclaration(node, 
84818             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), 
84819             /*questionOrExclamationToken*/ undefined, 
84820             /*type*/ undefined, ts.visitNode(node.initializer, visitor));
84821             if (updated !== node) {
84822                 // While we emit the source map for the node after skipping decorators and modifiers,
84823                 // we need to emit the comments for the original range.
84824                 ts.setCommentRange(updated, node);
84825                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
84826             }
84827             return updated;
84828         }
84829         function visitConstructor(node) {
84830             if (!shouldEmitFunctionLikeDeclaration(node)) {
84831                 return undefined;
84832             }
84833             return factory.updateConstructorDeclaration(node, 
84834             /*decorators*/ undefined, 
84835             /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node));
84836         }
84837         function transformConstructorBody(body, constructor) {
84838             var parametersWithPropertyAssignments = constructor &&
84839                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
84840             if (!ts.some(parametersWithPropertyAssignments)) {
84841                 return ts.visitFunctionBody(body, visitor, context);
84842             }
84843             var statements = [];
84844             var indexOfFirstStatement = 0;
84845             resumeLexicalEnvironment();
84846             indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor);
84847             // Add parameters with property assignments. Transforms this:
84848             //
84849             //  constructor (public x, public y) {
84850             //  }
84851             //
84852             // Into this:
84853             //
84854             //  constructor (x, y) {
84855             //      this.x = x;
84856             //      this.y = y;
84857             //  }
84858             //
84859             ts.addRange(statements, ts.map(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment));
84860             // Add the existing statements, skipping the initial super call.
84861             ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexOfFirstStatement));
84862             // End the lexical environment.
84863             statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
84864             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), body.statements), /*multiLine*/ true);
84865             ts.setTextRange(block, /*location*/ body);
84866             ts.setOriginalNode(block, body);
84867             return block;
84868         }
84869         /**
84870          * Transforms a parameter into a property assignment statement.
84871          *
84872          * @param node The parameter declaration.
84873          */
84874         function transformParameterWithPropertyAssignment(node) {
84875             var name = node.name;
84876             if (!ts.isIdentifier(name)) {
84877                 return undefined;
84878             }
84879             // TODO(rbuckton): Does this need to be parented?
84880             var propertyName = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent);
84881             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
84882             // TODO(rbuckton): Does this need to be parented?
84883             var localName = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent);
84884             ts.setEmitFlags(localName, 1536 /* NoComments */);
84885             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))));
84886         }
84887         function visitMethodDeclaration(node) {
84888             if (!shouldEmitFunctionLikeDeclaration(node)) {
84889                 return undefined;
84890             }
84891             var updated = factory.updateMethodDeclaration(node, 
84892             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), 
84893             /*questionToken*/ undefined, 
84894             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
84895             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
84896             if (updated !== node) {
84897                 // While we emit the source map for the node after skipping decorators and modifiers,
84898                 // we need to emit the comments for the original range.
84899                 ts.setCommentRange(updated, node);
84900                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
84901             }
84902             return updated;
84903         }
84904         /**
84905          * Determines whether to emit an accessor declaration. We should not emit the
84906          * declaration if it does not have a body and is abstract.
84907          *
84908          * @param node The declaration node.
84909          */
84910         function shouldEmitAccessorDeclaration(node) {
84911             return !(ts.nodeIsMissing(node.body) && ts.hasSyntacticModifier(node, 128 /* Abstract */));
84912         }
84913         function visitGetAccessor(node) {
84914             if (!shouldEmitAccessorDeclaration(node)) {
84915                 return undefined;
84916             }
84917             var updated = factory.updateGetAccessorDeclaration(node, 
84918             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), 
84919             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
84920             if (updated !== node) {
84921                 // While we emit the source map for the node after skipping decorators and modifiers,
84922                 // we need to emit the comments for the original range.
84923                 ts.setCommentRange(updated, node);
84924                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
84925             }
84926             return updated;
84927         }
84928         function visitSetAccessor(node) {
84929             if (!shouldEmitAccessorDeclaration(node)) {
84930                 return undefined;
84931             }
84932             var updated = factory.updateSetAccessorDeclaration(node, 
84933             /*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([]));
84934             if (updated !== node) {
84935                 // While we emit the source map for the node after skipping decorators and modifiers,
84936                 // we need to emit the comments for the original range.
84937                 ts.setCommentRange(updated, node);
84938                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
84939             }
84940             return updated;
84941         }
84942         function visitFunctionDeclaration(node) {
84943             if (!shouldEmitFunctionLikeDeclaration(node)) {
84944                 return factory.createNotEmittedStatement(node);
84945             }
84946             var updated = factory.updateFunctionDeclaration(node, 
84947             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
84948             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
84949             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
84950             if (isExportOfNamespace(node)) {
84951                 var statements = [updated];
84952                 addExportMemberAssignment(statements, node);
84953                 return statements;
84954             }
84955             return updated;
84956         }
84957         function visitFunctionExpression(node) {
84958             if (!shouldEmitFunctionLikeDeclaration(node)) {
84959                 return factory.createOmittedExpression();
84960             }
84961             var updated = factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
84962             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
84963             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
84964             return updated;
84965         }
84966         function visitArrowFunction(node) {
84967             var updated = factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), 
84968             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
84969             /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
84970             return updated;
84971         }
84972         function visitParameter(node) {
84973             if (ts.parameterIsThisKeyword(node)) {
84974                 return undefined;
84975             }
84976             var updated = factory.updateParameterDeclaration(node, 
84977             /*decorators*/ undefined, 
84978             /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), 
84979             /*questionToken*/ undefined, 
84980             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
84981             if (updated !== node) {
84982                 // While we emit the source map for the node after skipping decorators and modifiers,
84983                 // we need to emit the comments for the original range.
84984                 ts.setCommentRange(updated, node);
84985                 ts.setTextRange(updated, ts.moveRangePastModifiers(node));
84986                 ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
84987                 ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
84988             }
84989             return updated;
84990         }
84991         function visitVariableStatement(node) {
84992             if (isExportOfNamespace(node)) {
84993                 var variables = ts.getInitializedVariables(node.declarationList);
84994                 if (variables.length === 0) {
84995                     // elide statement if there are no initialized variables.
84996                     return undefined;
84997                 }
84998                 return ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
84999             }
85000             else {
85001                 return ts.visitEachChild(node, visitor, context);
85002             }
85003         }
85004         function transformInitializedVariable(node) {
85005             var name = node.name;
85006             if (ts.isBindingPattern(name)) {
85007                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, 
85008                 /*needsValue*/ false, createNamespaceExportExpression);
85009             }
85010             else {
85011                 return ts.setTextRange(factory.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), 
85012                 /*location*/ node);
85013             }
85014         }
85015         function visitVariableDeclaration(node) {
85016             return factory.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), 
85017             /*exclamationToken*/ undefined, 
85018             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
85019         }
85020         function visitParenthesizedExpression(node) {
85021             var innerExpression = ts.skipOuterExpressions(node.expression, ~6 /* Assertions */);
85022             if (ts.isAssertionExpression(innerExpression)) {
85023                 // Make sure we consider all nested cast expressions, e.g.:
85024                 // (<any><number><any>-A).x;
85025                 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
85026                 // We have an expression of the form: (<Type>SubExpr). Emitting this as (SubExpr)
85027                 // is really not desirable. We would like to emit the subexpression as-is. Omitting
85028                 // the parentheses, however, could cause change in the semantics of the generated
85029                 // code if the casted expression has a lower precedence than the rest of the
85030                 // expression.
85031                 //
85032                 // To preserve comments, we return a "PartiallyEmittedExpression" here which will
85033                 // preserve the position information of the original expression.
85034                 //
85035                 // Due to the auto-parenthesization rules used by the visitor and factory functions
85036                 // we can safely elide the parentheses here, as a new synthetic
85037                 // ParenthesizedExpression will be inserted if we remove parentheses too
85038                 // aggressively.
85039                 // HOWEVER - if there are leading comments on the expression itself, to handle ASI
85040                 // correctly for return and throw, we must keep the parenthesis
85041                 if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
85042                     return factory.updateParenthesizedExpression(node, expression);
85043                 }
85044                 return factory.createPartiallyEmittedExpression(expression, node);
85045             }
85046             return ts.visitEachChild(node, visitor, context);
85047         }
85048         function visitAssertionExpression(node) {
85049             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
85050             return factory.createPartiallyEmittedExpression(expression, node);
85051         }
85052         function visitNonNullExpression(node) {
85053             var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression);
85054             return factory.createPartiallyEmittedExpression(expression, node);
85055         }
85056         function visitCallExpression(node) {
85057             return factory.updateCallExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
85058             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
85059         }
85060         function visitNewExpression(node) {
85061             return factory.updateNewExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
85062             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
85063         }
85064         function visitTaggedTemplateExpression(node) {
85065             return factory.updateTaggedTemplateExpression(node, ts.visitNode(node.tag, visitor, ts.isExpression), 
85066             /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression));
85067         }
85068         function visitJsxSelfClosingElement(node) {
85069             return factory.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
85070             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
85071         }
85072         function visitJsxJsxOpeningElement(node) {
85073             return factory.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
85074             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
85075         }
85076         /**
85077          * Determines whether to emit an enum declaration.
85078          *
85079          * @param node The enum declaration node.
85080          */
85081         function shouldEmitEnumDeclaration(node) {
85082             return !ts.isEnumConst(node)
85083                 || ts.shouldPreserveConstEnums(compilerOptions);
85084         }
85085         /**
85086          * Visits an enum declaration.
85087          *
85088          * This function will be called any time a TypeScript enum is encountered.
85089          *
85090          * @param node The enum declaration node.
85091          */
85092         function visitEnumDeclaration(node) {
85093             if (!shouldEmitEnumDeclaration(node)) {
85094                 return factory.createNotEmittedStatement(node);
85095             }
85096             var statements = [];
85097             // We request to be advised when the printer is about to print this node. This allows
85098             // us to set up the correct state for later substitutions.
85099             var emitFlags = 2 /* AdviseOnEmitNode */;
85100             // If needed, we should emit a variable declaration for the enum. If we emit
85101             // a leading variable declaration, we should not emit leading comments for the
85102             // enum body.
85103             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
85104             if (varAdded) {
85105                 // We should still emit the comments if we are emitting a system module.
85106                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
85107                     emitFlags |= 512 /* NoLeadingComments */;
85108                 }
85109             }
85110             // `parameterName` is the declaration name used inside of the enum.
85111             var parameterName = getNamespaceParameterName(node);
85112             // `containerName` is the expression used inside of the enum for assignments.
85113             var containerName = getNamespaceContainerName(node);
85114             // `exportName` is the expression used within this node's container for any exported references.
85115             var exportName = ts.hasSyntacticModifier(node, 1 /* Export */)
85116                 ? factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
85117                 : factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
85118             //  x || (x = {})
85119             //  exports.x || (exports.x = {})
85120             var moduleArg = factory.createLogicalOr(exportName, factory.createAssignment(exportName, factory.createObjectLiteralExpression()));
85121             if (hasNamespaceQualifiedExportName(node)) {
85122                 // `localName` is the expression used within this node's containing scope for any local references.
85123                 var localName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
85124                 //  x = (exports.x || (exports.x = {}))
85125                 moduleArg = factory.createAssignment(localName, moduleArg);
85126             }
85127             //  (function (x) {
85128             //      x[x["y"] = 0] = "y";
85129             //      ...
85130             //  })(x || (x = {}));
85131             var enumStatement = factory.createExpressionStatement(factory.createCallExpression(factory.createFunctionExpression(
85132             /*modifiers*/ undefined, 
85133             /*asteriskToken*/ undefined, 
85134             /*name*/ undefined, 
85135             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
85136             /*type*/ undefined, transformEnumBody(node, containerName)), 
85137             /*typeArguments*/ undefined, [moduleArg]));
85138             ts.setOriginalNode(enumStatement, node);
85139             if (varAdded) {
85140                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
85141                 ts.setSyntheticLeadingComments(enumStatement, undefined);
85142                 ts.setSyntheticTrailingComments(enumStatement, undefined);
85143             }
85144             ts.setTextRange(enumStatement, node);
85145             ts.addEmitFlags(enumStatement, emitFlags);
85146             statements.push(enumStatement);
85147             // Add a DeclarationMarker for the enum to preserve trailing comments and mark
85148             // the end of the declaration.
85149             statements.push(factory.createEndOfDeclarationMarker(node));
85150             return statements;
85151         }
85152         /**
85153          * Transforms the body of an enum declaration.
85154          *
85155          * @param node The enum declaration node.
85156          */
85157         function transformEnumBody(node, localName) {
85158             var savedCurrentNamespaceLocalName = currentNamespaceContainerName;
85159             currentNamespaceContainerName = localName;
85160             var statements = [];
85161             startLexicalEnvironment();
85162             var members = ts.map(node.members, transformEnumMember);
85163             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
85164             ts.addRange(statements, members);
85165             currentNamespaceContainerName = savedCurrentNamespaceLocalName;
85166             return factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), /*location*/ node.members), 
85167             /*multiLine*/ true);
85168         }
85169         /**
85170          * Transforms an enum member into a statement.
85171          *
85172          * @param member The enum member node.
85173          */
85174         function transformEnumMember(member) {
85175             // enums don't support computed properties
85176             // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
85177             // old emitter always generate 'expression' part of the name as-is.
85178             var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
85179             var valueExpression = transformEnumMemberDeclarationValue(member);
85180             var innerAssignment = factory.createAssignment(factory.createElementAccessExpression(currentNamespaceContainerName, name), valueExpression);
85181             var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ?
85182                 innerAssignment :
85183                 factory.createAssignment(factory.createElementAccessExpression(currentNamespaceContainerName, innerAssignment), name);
85184             return ts.setTextRange(factory.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member);
85185         }
85186         /**
85187          * Transforms the value of an enum member.
85188          *
85189          * @param member The enum member node.
85190          */
85191         function transformEnumMemberDeclarationValue(member) {
85192             var value = resolver.getConstantValue(member);
85193             if (value !== undefined) {
85194                 return typeof value === "string" ? factory.createStringLiteral(value) : factory.createNumericLiteral(value);
85195             }
85196             else {
85197                 enableSubstitutionForNonQualifiedEnumMembers();
85198                 if (member.initializer) {
85199                     return ts.visitNode(member.initializer, visitor, ts.isExpression);
85200                 }
85201                 else {
85202                     return factory.createVoidZero();
85203                 }
85204             }
85205         }
85206         /**
85207          * Determines whether to elide a module declaration.
85208          *
85209          * @param node The module declaration node.
85210          */
85211         function shouldEmitModuleDeclaration(nodeIn) {
85212             var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration);
85213             if (!node) {
85214                 // If we can't find a parse tree node, assume the node is instantiated.
85215                 return true;
85216             }
85217             return ts.isInstantiatedModule(node, ts.shouldPreserveConstEnums(compilerOptions));
85218         }
85219         /**
85220          * Determines whether an exported declaration will have a qualified export name (e.g. `f.x`
85221          * or `exports.x`).
85222          */
85223         function hasNamespaceQualifiedExportName(node) {
85224             return isExportOfNamespace(node)
85225                 || (isExternalModuleExport(node)
85226                     && moduleKind !== ts.ModuleKind.ES2015
85227                     && moduleKind !== ts.ModuleKind.ES2020
85228                     && moduleKind !== ts.ModuleKind.ESNext
85229                     && moduleKind !== ts.ModuleKind.System);
85230         }
85231         /**
85232          * Records that a declaration was emitted in the current scope, if it was the first
85233          * declaration for the provided symbol.
85234          */
85235         function recordEmittedDeclarationInScope(node) {
85236             if (!currentScopeFirstDeclarationsOfName) {
85237                 currentScopeFirstDeclarationsOfName = new ts.Map();
85238             }
85239             var name = declaredNameInScope(node);
85240             if (!currentScopeFirstDeclarationsOfName.has(name)) {
85241                 currentScopeFirstDeclarationsOfName.set(name, node);
85242             }
85243         }
85244         /**
85245          * Determines whether a declaration is the first declaration with
85246          * the same name emitted in the current scope.
85247          */
85248         function isFirstEmittedDeclarationInScope(node) {
85249             if (currentScopeFirstDeclarationsOfName) {
85250                 var name = declaredNameInScope(node);
85251                 return currentScopeFirstDeclarationsOfName.get(name) === node;
85252             }
85253             return true;
85254         }
85255         function declaredNameInScope(node) {
85256             ts.Debug.assertNode(node.name, ts.isIdentifier);
85257             return node.name.escapedText;
85258         }
85259         /**
85260          * Adds a leading VariableStatement for a enum or module declaration.
85261          */
85262         function addVarForEnumOrModuleDeclaration(statements, node) {
85263             // Emit a variable statement for the module. We emit top-level enums as a `var`
85264             // declaration to avoid static errors in global scripts scripts due to redeclaration.
85265             // enums in any other scope are emitted as a `let` declaration.
85266             var statement = factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([
85267                 factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
85268             ], currentLexicalScope.kind === 297 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
85269             ts.setOriginalNode(statement, node);
85270             recordEmittedDeclarationInScope(node);
85271             if (isFirstEmittedDeclarationInScope(node)) {
85272                 // Adjust the source map emit to match the old emitter.
85273                 if (node.kind === 255 /* EnumDeclaration */) {
85274                     ts.setSourceMapRange(statement.declarationList, node);
85275                 }
85276                 else {
85277                     ts.setSourceMapRange(statement, node);
85278                 }
85279                 // Trailing comments for module declaration should be emitted after the function closure
85280                 // instead of the variable statement:
85281                 //
85282                 //     /** Module comment*/
85283                 //     module m1 {
85284                 //         function foo4Export() {
85285                 //         }
85286                 //     } // trailing comment module
85287                 //
85288                 // Should emit:
85289                 //
85290                 //     /** Module comment*/
85291                 //     var m1;
85292                 //     (function (m1) {
85293                 //         function foo4Export() {
85294                 //         }
85295                 //     })(m1 || (m1 = {})); // trailing comment module
85296                 //
85297                 ts.setCommentRange(statement, node);
85298                 ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */);
85299                 statements.push(statement);
85300                 return true;
85301             }
85302             else {
85303                 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
85304                 // declaration we do not emit a leading variable declaration. To preserve the
85305                 // begin/end semantics of the declararation and to properly handle exports
85306                 // we wrap the leading variable declaration in a `MergeDeclarationMarker`.
85307                 var mergeMarker = factory.createMergeDeclarationMarker(statement);
85308                 ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */);
85309                 statements.push(mergeMarker);
85310                 return false;
85311             }
85312         }
85313         /**
85314          * Visits a module declaration node.
85315          *
85316          * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered.
85317          *
85318          * @param node The module declaration node.
85319          */
85320         function visitModuleDeclaration(node) {
85321             if (!shouldEmitModuleDeclaration(node)) {
85322                 return factory.createNotEmittedStatement(node);
85323             }
85324             ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name.");
85325             enableSubstitutionForNamespaceExports();
85326             var statements = [];
85327             // We request to be advised when the printer is about to print this node. This allows
85328             // us to set up the correct state for later substitutions.
85329             var emitFlags = 2 /* AdviseOnEmitNode */;
85330             // If needed, we should emit a variable declaration for the module. If we emit
85331             // a leading variable declaration, we should not emit leading comments for the
85332             // module body.
85333             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
85334             if (varAdded) {
85335                 // We should still emit the comments if we are emitting a system module.
85336                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
85337                     emitFlags |= 512 /* NoLeadingComments */;
85338                 }
85339             }
85340             // `parameterName` is the declaration name used inside of the namespace.
85341             var parameterName = getNamespaceParameterName(node);
85342             // `containerName` is the expression used inside of the namespace for exports.
85343             var containerName = getNamespaceContainerName(node);
85344             // `exportName` is the expression used within this node's container for any exported references.
85345             var exportName = ts.hasSyntacticModifier(node, 1 /* Export */)
85346                 ? factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
85347                 : factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
85348             //  x || (x = {})
85349             //  exports.x || (exports.x = {})
85350             var moduleArg = factory.createLogicalOr(exportName, factory.createAssignment(exportName, factory.createObjectLiteralExpression()));
85351             if (hasNamespaceQualifiedExportName(node)) {
85352                 // `localName` is the expression used within this node's containing scope for any local references.
85353                 var localName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
85354                 //  x = (exports.x || (exports.x = {}))
85355                 moduleArg = factory.createAssignment(localName, moduleArg);
85356             }
85357             //  (function (x_1) {
85358             //      x_1.y = ...;
85359             //  })(x || (x = {}));
85360             var moduleStatement = factory.createExpressionStatement(factory.createCallExpression(factory.createFunctionExpression(
85361             /*modifiers*/ undefined, 
85362             /*asteriskToken*/ undefined, 
85363             /*name*/ undefined, 
85364             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
85365             /*type*/ undefined, transformModuleBody(node, containerName)), 
85366             /*typeArguments*/ undefined, [moduleArg]));
85367             ts.setOriginalNode(moduleStatement, node);
85368             if (varAdded) {
85369                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
85370                 ts.setSyntheticLeadingComments(moduleStatement, undefined);
85371                 ts.setSyntheticTrailingComments(moduleStatement, undefined);
85372             }
85373             ts.setTextRange(moduleStatement, node);
85374             ts.addEmitFlags(moduleStatement, emitFlags);
85375             statements.push(moduleStatement);
85376             // Add a DeclarationMarker for the namespace to preserve trailing comments and mark
85377             // the end of the declaration.
85378             statements.push(factory.createEndOfDeclarationMarker(node));
85379             return statements;
85380         }
85381         /**
85382          * Transforms the body of a module declaration.
85383          *
85384          * @param node The module declaration node.
85385          */
85386         function transformModuleBody(node, namespaceLocalName) {
85387             var savedCurrentNamespaceContainerName = currentNamespaceContainerName;
85388             var savedCurrentNamespace = currentNamespace;
85389             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
85390             currentNamespaceContainerName = namespaceLocalName;
85391             currentNamespace = node;
85392             currentScopeFirstDeclarationsOfName = undefined;
85393             var statements = [];
85394             startLexicalEnvironment();
85395             var statementsLocation;
85396             var blockLocation;
85397             if (node.body) {
85398                 if (node.body.kind === 257 /* ModuleBlock */) {
85399                     saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); });
85400                     statementsLocation = node.body.statements;
85401                     blockLocation = node.body;
85402                 }
85403                 else {
85404                     var result = visitModuleDeclaration(node.body);
85405                     if (result) {
85406                         if (ts.isArray(result)) {
85407                             ts.addRange(statements, result);
85408                         }
85409                         else {
85410                             statements.push(result);
85411                         }
85412                     }
85413                     var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
85414                     statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
85415                 }
85416             }
85417             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
85418             currentNamespaceContainerName = savedCurrentNamespaceContainerName;
85419             currentNamespace = savedCurrentNamespace;
85420             currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
85421             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), 
85422             /*location*/ statementsLocation), 
85423             /*multiLine*/ true);
85424             ts.setTextRange(block, blockLocation);
85425             // namespace hello.hi.world {
85426             //      function foo() {}
85427             //
85428             //      // TODO, blah
85429             // }
85430             //
85431             // should be emitted as
85432             //
85433             // var hello;
85434             // (function (hello) {
85435             //     var hi;
85436             //     (function (hi) {
85437             //         var world;
85438             //         (function (world) {
85439             //             function foo() { }
85440             //             // TODO, blah
85441             //         })(world = hi.world || (hi.world = {}));
85442             //     })(hi = hello.hi || (hello.hi = {}));
85443             // })(hello || (hello = {}));
85444             // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces.
85445             if (!node.body || node.body.kind !== 257 /* ModuleBlock */) {
85446                 ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */);
85447             }
85448             return block;
85449         }
85450         function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
85451             if (moduleDeclaration.body.kind === 256 /* ModuleDeclaration */) {
85452                 var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
85453                 return recursiveInnerModule || moduleDeclaration.body;
85454             }
85455         }
85456         /**
85457          * Visits an import declaration, eliding it if it is not referenced and `importsNotUsedAsValues` is not 'preserve'.
85458          *
85459          * @param node The import declaration node.
85460          */
85461         function visitImportDeclaration(node) {
85462             if (!node.importClause) {
85463                 // Do not elide a side-effect only import declaration.
85464                 //  import "foo";
85465                 return node;
85466             }
85467             if (node.importClause.isTypeOnly) {
85468                 // Always elide type-only imports
85469                 return undefined;
85470             }
85471             // Elide the declaration if the import clause was elided.
85472             var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause);
85473             return importClause ||
85474                 compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ ||
85475                 compilerOptions.importsNotUsedAsValues === 2 /* Error */
85476                 ? factory.updateImportDeclaration(node, 
85477                 /*decorators*/ undefined, 
85478                 /*modifiers*/ undefined, importClause, node.moduleSpecifier)
85479                 : undefined;
85480         }
85481         /**
85482          * Visits an import clause, eliding it if it is not referenced.
85483          *
85484          * @param node The import clause node.
85485          */
85486         function visitImportClause(node) {
85487             if (node.isTypeOnly) {
85488                 return undefined;
85489             }
85490             // Elide the import clause if we elide both its name and its named bindings.
85491             var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
85492             var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings);
85493             return (name || namedBindings) ? factory.updateImportClause(node, /*isTypeOnly*/ false, name, namedBindings) : undefined;
85494         }
85495         /**
85496          * Visits named import bindings, eliding it if it is not referenced.
85497          *
85498          * @param node The named import bindings node.
85499          */
85500         function visitNamedImportBindings(node) {
85501             if (node.kind === 263 /* NamespaceImport */) {
85502                 // Elide a namespace import if it is not referenced.
85503                 return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
85504             }
85505             else {
85506                 // Elide named imports if all of its import specifiers are elided.
85507                 var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier);
85508                 return ts.some(elements) ? factory.updateNamedImports(node, elements) : undefined;
85509             }
85510         }
85511         /**
85512          * Visits an import specifier, eliding it if it is not referenced.
85513          *
85514          * @param node The import specifier node.
85515          */
85516         function visitImportSpecifier(node) {
85517             // Elide an import specifier if it is not referenced.
85518             return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
85519         }
85520         /**
85521          * Visits an export assignment, eliding it if it does not contain a clause that resolves
85522          * to a value.
85523          *
85524          * @param node The export assignment node.
85525          */
85526         function visitExportAssignment(node) {
85527             // Elide the export assignment if it does not reference a value.
85528             return resolver.isValueAliasDeclaration(node)
85529                 ? ts.visitEachChild(node, visitor, context)
85530                 : undefined;
85531         }
85532         /**
85533          * Visits an export declaration, eliding it if it does not contain a clause that resolves
85534          * to a value.
85535          *
85536          * @param node The export declaration node.
85537          */
85538         function visitExportDeclaration(node) {
85539             if (node.isTypeOnly) {
85540                 return undefined;
85541             }
85542             if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) {
85543                 // never elide `export <whatever> from <whereever>` declarations -
85544                 // they should be kept for sideffects/untyped exports, even when the
85545                 // type checker doesn't know about any exports
85546                 return node;
85547             }
85548             if (!resolver.isValueAliasDeclaration(node)) {
85549                 // Elide the export declaration if it does not export a value.
85550                 return undefined;
85551             }
85552             // Elide the export declaration if all of its named exports are elided.
85553             var exportClause = ts.visitNode(node.exportClause, visitNamedExportBindings, ts.isNamedExportBindings);
85554             return exportClause
85555                 ? factory.updateExportDeclaration(node, 
85556                 /*decorators*/ undefined, 
85557                 /*modifiers*/ undefined, node.isTypeOnly, exportClause, node.moduleSpecifier)
85558                 : undefined;
85559         }
85560         /**
85561          * Visits named exports, eliding it if it does not contain an export specifier that
85562          * resolves to a value.
85563          *
85564          * @param node The named exports node.
85565          */
85566         function visitNamedExports(node) {
85567             // Elide the named exports if all of its export specifiers were elided.
85568             var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier);
85569             return ts.some(elements) ? factory.updateNamedExports(node, elements) : undefined;
85570         }
85571         function visitNamespaceExports(node) {
85572             return factory.updateNamespaceExport(node, ts.visitNode(node.name, visitor, ts.isIdentifier));
85573         }
85574         function visitNamedExportBindings(node) {
85575             return ts.isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node);
85576         }
85577         /**
85578          * Visits an export specifier, eliding it if it does not resolve to a value.
85579          *
85580          * @param node The export specifier node.
85581          */
85582         function visitExportSpecifier(node) {
85583             // Elide an export specifier if it does not reference a value.
85584             return resolver.isValueAliasDeclaration(node) ? node : undefined;
85585         }
85586         /**
85587          * Determines whether to emit an import equals declaration.
85588          *
85589          * @param node The import equals declaration node.
85590          */
85591         function shouldEmitImportEqualsDeclaration(node) {
85592             // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when
85593             // - current file is not external module
85594             // - import declaration is top level and target is value imported by entity name
85595             return resolver.isReferencedAliasDeclaration(node)
85596                 || (!ts.isExternalModule(currentSourceFile)
85597                     && resolver.isTopLevelValueImportEqualsWithEntityName(node));
85598         }
85599         /**
85600          * Visits an import equals declaration.
85601          *
85602          * @param node The import equals declaration node.
85603          */
85604         function visitImportEqualsDeclaration(node) {
85605             // Always elide type-only imports
85606             if (node.isTypeOnly) {
85607                 return undefined;
85608             }
85609             if (ts.isExternalModuleImportEqualsDeclaration(node)) {
85610                 var isReferenced = resolver.isReferencedAliasDeclaration(node);
85611                 // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'.
85612                 if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* Preserve */) {
85613                     return ts.setOriginalNode(ts.setTextRange(factory.createImportDeclaration(
85614                     /*decorators*/ undefined, 
85615                     /*modifiers*/ undefined, 
85616                     /*importClause*/ undefined, node.moduleReference.expression), node), node);
85617                 }
85618                 return isReferenced ? ts.visitEachChild(node, visitor, context) : undefined;
85619             }
85620             if (!shouldEmitImportEqualsDeclaration(node)) {
85621                 return undefined;
85622             }
85623             var moduleReference = ts.createExpressionFromEntityName(factory, node.moduleReference);
85624             ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
85625             if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
85626                 //  export var ${name} = ${moduleReference};
85627                 //  var ${name} = ${moduleReference};
85628                 return ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([
85629                     ts.setOriginalNode(factory.createVariableDeclaration(node.name, 
85630                     /*exclamationToken*/ undefined, 
85631                     /*type*/ undefined, moduleReference), node)
85632                 ])), node), node);
85633             }
85634             else {
85635                 // exports.${name} = ${moduleReference};
85636                 return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node);
85637             }
85638         }
85639         /**
85640          * Gets a value indicating whether the node is exported from a namespace.
85641          *
85642          * @param node The node to test.
85643          */
85644         function isExportOfNamespace(node) {
85645             return currentNamespace !== undefined && ts.hasSyntacticModifier(node, 1 /* Export */);
85646         }
85647         /**
85648          * Gets a value indicating whether the node is exported from an external module.
85649          *
85650          * @param node The node to test.
85651          */
85652         function isExternalModuleExport(node) {
85653             return currentNamespace === undefined && ts.hasSyntacticModifier(node, 1 /* Export */);
85654         }
85655         /**
85656          * Gets a value indicating whether the node is a named export from an external module.
85657          *
85658          * @param node The node to test.
85659          */
85660         function isNamedExternalModuleExport(node) {
85661             return isExternalModuleExport(node)
85662                 && !ts.hasSyntacticModifier(node, 512 /* Default */);
85663         }
85664         /**
85665          * Gets a value indicating whether the node is the default export of an external module.
85666          *
85667          * @param node The node to test.
85668          */
85669         function isDefaultExternalModuleExport(node) {
85670             return isExternalModuleExport(node)
85671                 && ts.hasSyntacticModifier(node, 512 /* Default */);
85672         }
85673         /**
85674          * Creates a statement for the provided expression. This is used in calls to `map`.
85675          */
85676         function expressionToStatement(expression) {
85677             return factory.createExpressionStatement(expression);
85678         }
85679         function addExportMemberAssignment(statements, node) {
85680             var expression = factory.createAssignment(factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), factory.getLocalName(node));
85681             ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end));
85682             var statement = factory.createExpressionStatement(expression);
85683             ts.setSourceMapRange(statement, ts.createRange(-1, node.end));
85684             statements.push(statement);
85685         }
85686         function createNamespaceExport(exportName, exportValue, location) {
85687             return ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(factory.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location);
85688         }
85689         function createNamespaceExportExpression(exportName, exportValue, location) {
85690             return ts.setTextRange(factory.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
85691         }
85692         function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
85693             return factory.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true);
85694         }
85695         /**
85696          * Gets the declaration name used inside of a namespace or enum.
85697          */
85698         function getNamespaceParameterName(node) {
85699             var name = factory.getGeneratedNameForNode(node);
85700             ts.setSourceMapRange(name, node.name);
85701             return name;
85702         }
85703         /**
85704          * Gets the expression used to refer to a namespace or enum within the body
85705          * of its declaration.
85706          */
85707         function getNamespaceContainerName(node) {
85708             return factory.getGeneratedNameForNode(node);
85709         }
85710         /**
85711          * Gets a local alias for a class declaration if it is a decorated class with an internal
85712          * reference to the static side of the class. This is necessary to avoid issues with
85713          * double-binding semantics for the class name.
85714          */
85715         function getClassAliasIfNeeded(node) {
85716             if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) {
85717                 enableSubstitutionForClassAliases();
85718                 var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default");
85719                 classAliases[ts.getOriginalNodeId(node)] = classAlias;
85720                 hoistVariableDeclaration(classAlias);
85721                 return classAlias;
85722             }
85723         }
85724         function getClassPrototype(node) {
85725             return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype");
85726         }
85727         function getClassMemberPrefix(node, member) {
85728             return ts.hasSyntacticModifier(member, 32 /* Static */)
85729                 ? factory.getDeclarationName(node)
85730                 : getClassPrototype(node);
85731         }
85732         function enableSubstitutionForNonQualifiedEnumMembers() {
85733             if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) {
85734                 enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */;
85735                 context.enableSubstitution(78 /* Identifier */);
85736             }
85737         }
85738         function enableSubstitutionForClassAliases() {
85739             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
85740                 enabledSubstitutions |= 1 /* ClassAliases */;
85741                 // We need to enable substitutions for identifiers. This allows us to
85742                 // substitute class names inside of a class declaration.
85743                 context.enableSubstitution(78 /* Identifier */);
85744                 // Keep track of class aliases.
85745                 classAliases = [];
85746             }
85747         }
85748         function enableSubstitutionForNamespaceExports() {
85749             if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) {
85750                 enabledSubstitutions |= 2 /* NamespaceExports */;
85751                 // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to
85752                 // substitute the names of exported members of a namespace.
85753                 context.enableSubstitution(78 /* Identifier */);
85754                 context.enableSubstitution(289 /* ShorthandPropertyAssignment */);
85755                 // We need to be notified when entering and exiting namespaces.
85756                 context.enableEmitNotification(256 /* ModuleDeclaration */);
85757             }
85758         }
85759         function isTransformedModuleDeclaration(node) {
85760             return ts.getOriginalNode(node).kind === 256 /* ModuleDeclaration */;
85761         }
85762         function isTransformedEnumDeclaration(node) {
85763             return ts.getOriginalNode(node).kind === 255 /* EnumDeclaration */;
85764         }
85765         /**
85766          * Hook for node emit.
85767          *
85768          * @param hint A hint as to the intended usage of the node.
85769          * @param node The node to emit.
85770          * @param emit A callback used to emit the node in the printer.
85771          */
85772         function onEmitNode(hint, node, emitCallback) {
85773             var savedApplicableSubstitutions = applicableSubstitutions;
85774             var savedCurrentSourceFile = currentSourceFile;
85775             if (ts.isSourceFile(node)) {
85776                 currentSourceFile = node;
85777             }
85778             if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
85779                 applicableSubstitutions |= 2 /* NamespaceExports */;
85780             }
85781             if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
85782                 applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
85783             }
85784             previousOnEmitNode(hint, node, emitCallback);
85785             applicableSubstitutions = savedApplicableSubstitutions;
85786             currentSourceFile = savedCurrentSourceFile;
85787         }
85788         /**
85789          * Hooks node substitutions.
85790          *
85791          * @param hint A hint as to the intended usage of the node.
85792          * @param node The node to substitute.
85793          */
85794         function onSubstituteNode(hint, node) {
85795             node = previousOnSubstituteNode(hint, node);
85796             if (hint === 1 /* Expression */) {
85797                 return substituteExpression(node);
85798             }
85799             else if (ts.isShorthandPropertyAssignment(node)) {
85800                 return substituteShorthandPropertyAssignment(node);
85801             }
85802             return node;
85803         }
85804         function substituteShorthandPropertyAssignment(node) {
85805             if (enabledSubstitutions & 2 /* NamespaceExports */) {
85806                 var name = node.name;
85807                 var exportedName = trySubstituteNamespaceExportedName(name);
85808                 if (exportedName) {
85809                     // A shorthand property with an assignment initializer is probably part of a
85810                     // destructuring assignment
85811                     if (node.objectAssignmentInitializer) {
85812                         var initializer = factory.createAssignment(exportedName, node.objectAssignmentInitializer);
85813                         return ts.setTextRange(factory.createPropertyAssignment(name, initializer), node);
85814                     }
85815                     return ts.setTextRange(factory.createPropertyAssignment(name, exportedName), node);
85816                 }
85817             }
85818             return node;
85819         }
85820         function substituteExpression(node) {
85821             switch (node.kind) {
85822                 case 78 /* Identifier */:
85823                     return substituteExpressionIdentifier(node);
85824                 case 201 /* PropertyAccessExpression */:
85825                     return substitutePropertyAccessExpression(node);
85826                 case 202 /* ElementAccessExpression */:
85827                     return substituteElementAccessExpression(node);
85828             }
85829             return node;
85830         }
85831         function substituteExpressionIdentifier(node) {
85832             return trySubstituteClassAlias(node)
85833                 || trySubstituteNamespaceExportedName(node)
85834                 || node;
85835         }
85836         function trySubstituteClassAlias(node) {
85837             if (enabledSubstitutions & 1 /* ClassAliases */) {
85838                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
85839                     // Due to the emit for class decorators, any reference to the class from inside of the class body
85840                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
85841                     // behavior of class names in ES6.
85842                     // Also, when emitting statics for class expressions, we must substitute a class alias for
85843                     // constructor references in static property initializers.
85844                     var declaration = resolver.getReferencedValueDeclaration(node);
85845                     if (declaration) {
85846                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
85847                         if (classAlias) {
85848                             var clone_1 = factory.cloneNode(classAlias);
85849                             ts.setSourceMapRange(clone_1, node);
85850                             ts.setCommentRange(clone_1, node);
85851                             return clone_1;
85852                         }
85853                     }
85854                 }
85855             }
85856             return undefined;
85857         }
85858         function trySubstituteNamespaceExportedName(node) {
85859             // If this is explicitly a local name, do not substitute.
85860             if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
85861                 // If we are nested within a namespace declaration, we may need to qualifiy
85862                 // an identifier that is exported from a merged namespace.
85863                 var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
85864                 if (container && container.kind !== 297 /* SourceFile */) {
85865                     var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 256 /* ModuleDeclaration */) ||
85866                         (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 255 /* EnumDeclaration */);
85867                     if (substitute) {
85868                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(container), node), 
85869                         /*location*/ node);
85870                     }
85871                 }
85872             }
85873             return undefined;
85874         }
85875         function substitutePropertyAccessExpression(node) {
85876             return substituteConstantValue(node);
85877         }
85878         function substituteElementAccessExpression(node) {
85879             return substituteConstantValue(node);
85880         }
85881         function substituteConstantValue(node) {
85882             var constantValue = tryGetConstEnumValue(node);
85883             if (constantValue !== undefined) {
85884                 // track the constant value on the node for the printer in needsDotDotForPropertyAccess
85885                 ts.setConstantValue(node, constantValue);
85886                 var substitute = typeof constantValue === "string" ? factory.createStringLiteral(constantValue) : factory.createNumericLiteral(constantValue);
85887                 if (!compilerOptions.removeComments) {
85888                     var originalNode = ts.getOriginalNode(node, ts.isAccessExpression);
85889                     var propertyName = ts.isPropertyAccessExpression(originalNode)
85890                         ? ts.declarationNameToString(originalNode.name)
85891                         : ts.getTextOfNode(originalNode.argumentExpression);
85892                     ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " ");
85893                 }
85894                 return substitute;
85895             }
85896             return node;
85897         }
85898         function tryGetConstEnumValue(node) {
85899             if (compilerOptions.isolatedModules) {
85900                 return undefined;
85901             }
85902             return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined;
85903         }
85904     }
85905     ts.transformTypeScript = transformTypeScript;
85906 })(ts || (ts = {}));
85907 /*@internal*/
85908 var ts;
85909 (function (ts) {
85910     var ClassPropertySubstitutionFlags;
85911     (function (ClassPropertySubstitutionFlags) {
85912         /**
85913          * Enables substitutions for class expressions with static fields
85914          * which have initializers that reference the class name.
85915          */
85916         ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
85917     })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {}));
85918     var PrivateIdentifierPlacement;
85919     (function (PrivateIdentifierPlacement) {
85920         PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField";
85921     })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {}));
85922     /**
85923      * Transforms ECMAScript Class Syntax.
85924      * TypeScript parameter property syntax is transformed in the TypeScript transformer.
85925      * For now, this transforms public field declarations using TypeScript class semantics,
85926      * where declarations are elided and initializers are transformed as assignments in the constructor.
85927      * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty.
85928      */
85929     function transformClassFields(context) {
85930         var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment;
85931         var resolver = context.getEmitResolver();
85932         var compilerOptions = context.getCompilerOptions();
85933         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
85934         var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */;
85935         var previousOnSubstituteNode = context.onSubstituteNode;
85936         context.onSubstituteNode = onSubstituteNode;
85937         var enabledSubstitutions;
85938         var classAliases;
85939         /**
85940          * Tracks what computed name expressions originating from elided names must be inlined
85941          * at the next execution site, in document order
85942          */
85943         var pendingExpressions;
85944         /**
85945          * Tracks what computed name expression statements and static property initializers must be
85946          * emitted at the next execution site, in document order (for decorated classes).
85947          */
85948         var pendingStatements;
85949         var privateIdentifierEnvironmentStack = [];
85950         var currentPrivateIdentifierEnvironment;
85951         return ts.chainBundle(context, transformSourceFile);
85952         function transformSourceFile(node) {
85953             var options = context.getCompilerOptions();
85954             if (node.isDeclarationFile
85955                 || options.useDefineForClassFields && options.target === 99 /* ESNext */) {
85956                 return node;
85957             }
85958             var visited = ts.visitEachChild(node, visitor, context);
85959             ts.addEmitHelpers(visited, context.readEmitHelpers());
85960             return visited;
85961         }
85962         function visitor(node) {
85963             if (!(node.transformFlags & 4194304 /* ContainsClassFields */))
85964                 return node;
85965             switch (node.kind) {
85966                 case 221 /* ClassExpression */:
85967                 case 252 /* ClassDeclaration */:
85968                     return visitClassLike(node);
85969                 case 163 /* PropertyDeclaration */:
85970                     return visitPropertyDeclaration(node);
85971                 case 232 /* VariableStatement */:
85972                     return visitVariableStatement(node);
85973                 case 201 /* PropertyAccessExpression */:
85974                     return visitPropertyAccessExpression(node);
85975                 case 214 /* PrefixUnaryExpression */:
85976                     return visitPrefixUnaryExpression(node);
85977                 case 215 /* PostfixUnaryExpression */:
85978                     return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false);
85979                 case 203 /* CallExpression */:
85980                     return visitCallExpression(node);
85981                 case 216 /* BinaryExpression */:
85982                     return visitBinaryExpression(node);
85983                 case 79 /* PrivateIdentifier */:
85984                     return visitPrivateIdentifier(node);
85985                 case 233 /* ExpressionStatement */:
85986                     return visitExpressionStatement(node);
85987                 case 237 /* ForStatement */:
85988                     return visitForStatement(node);
85989                 case 205 /* TaggedTemplateExpression */:
85990                     return visitTaggedTemplateExpression(node);
85991             }
85992             return ts.visitEachChild(node, visitor, context);
85993         }
85994         function visitorDestructuringTarget(node) {
85995             switch (node.kind) {
85996                 case 200 /* ObjectLiteralExpression */:
85997                 case 199 /* ArrayLiteralExpression */:
85998                     return visitAssignmentPattern(node);
85999                 default:
86000                     return visitor(node);
86001             }
86002         }
86003         /**
86004          * If we visit a private name, this means it is an undeclared private name.
86005          * Replace it with an empty identifier to indicate a problem with the code.
86006          */
86007         function visitPrivateIdentifier(node) {
86008             if (!shouldTransformPrivateFields) {
86009                 return node;
86010             }
86011             return ts.setOriginalNode(factory.createIdentifier(""), node);
86012         }
86013         /**
86014          * Visits the members of a class that has fields.
86015          *
86016          * @param node The node to visit.
86017          */
86018         function classElementVisitor(node) {
86019             switch (node.kind) {
86020                 case 166 /* Constructor */:
86021                     // Constructors for classes using class fields are transformed in
86022                     // `visitClassDeclaration` or `visitClassExpression`.
86023                     return undefined;
86024                 case 167 /* GetAccessor */:
86025                 case 168 /* SetAccessor */:
86026                 case 165 /* MethodDeclaration */:
86027                     // Visit the name of the member (if it's a computed property name).
86028                     return ts.visitEachChild(node, classElementVisitor, context);
86029                 case 163 /* PropertyDeclaration */:
86030                     return visitPropertyDeclaration(node);
86031                 case 158 /* ComputedPropertyName */:
86032                     return visitComputedPropertyName(node);
86033                 case 229 /* SemicolonClassElement */:
86034                     return node;
86035                 default:
86036                     return visitor(node);
86037             }
86038         }
86039         function visitVariableStatement(node) {
86040             var savedPendingStatements = pendingStatements;
86041             pendingStatements = [];
86042             var visitedNode = ts.visitEachChild(node, visitor, context);
86043             var statement = ts.some(pendingStatements) ? __spreadArray([visitedNode], pendingStatements) :
86044                 visitedNode;
86045             pendingStatements = savedPendingStatements;
86046             return statement;
86047         }
86048         function visitComputedPropertyName(name) {
86049             var node = ts.visitEachChild(name, visitor, context);
86050             if (ts.some(pendingExpressions)) {
86051                 var expressions = pendingExpressions;
86052                 expressions.push(node.expression);
86053                 pendingExpressions = [];
86054                 node = factory.updateComputedPropertyName(node, factory.inlineExpressions(expressions));
86055             }
86056             return node;
86057         }
86058         function visitPropertyDeclaration(node) {
86059             ts.Debug.assert(!ts.some(node.decorators));
86060             if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
86061                 // Initializer is elided as the field is initialized in transformConstructor.
86062                 return factory.updatePropertyDeclaration(node, 
86063                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, 
86064                 /*questionOrExclamationToken*/ undefined, 
86065                 /*type*/ undefined, 
86066                 /*initializer*/ undefined);
86067             }
86068             // Create a temporary variable to store a computed property name (if necessary).
86069             // If it's not inlineable, then we emit an expression after the class which assigns
86070             // the property name to the temporary variable.
86071             var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields);
86072             if (expr && !ts.isSimpleInlineableExpression(expr)) {
86073                 getPendingExpressions().push(expr);
86074             }
86075             return undefined;
86076         }
86077         function createPrivateIdentifierAccess(info, receiver) {
86078             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
86079             switch (info.placement) {
86080                 case 0 /* InstanceField */:
86081                     return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(ts.nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver), info.weakMapName);
86082                 default: return ts.Debug.fail("Unexpected private identifier placement");
86083             }
86084         }
86085         function visitPropertyAccessExpression(node) {
86086             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
86087                 var privateIdentifierInfo = accessPrivateIdentifier(node.name);
86088                 if (privateIdentifierInfo) {
86089                     return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node);
86090                 }
86091             }
86092             return ts.visitEachChild(node, visitor, context);
86093         }
86094         function visitPrefixUnaryExpression(node) {
86095             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
86096                 var operator = node.operator === 45 /* PlusPlusToken */ ?
86097                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
86098                     40 /* MinusToken */ : undefined;
86099                 var info = void 0;
86100                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
86101                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
86102                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
86103                     var existingValue = factory.createPrefixUnaryExpression(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
86104                     return ts.setOriginalNode(createPrivateIdentifierAssignment(info, initializeExpression || readExpression, factory.createBinaryExpression(existingValue, operator, factory.createNumericLiteral(1)), 62 /* EqualsToken */), node);
86105                 }
86106             }
86107             return ts.visitEachChild(node, visitor, context);
86108         }
86109         function visitPostfixUnaryExpression(node, valueIsDiscarded) {
86110             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
86111                 var operator = node.operator === 45 /* PlusPlusToken */ ?
86112                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
86113                     40 /* MinusToken */ : undefined;
86114                 var info = void 0;
86115                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
86116                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
86117                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
86118                     var existingValue = factory.createPrefixUnaryExpression(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
86119                     // Create a temporary variable to store the value returned by the expression.
86120                     var returnValue = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration);
86121                     return ts.setOriginalNode(factory.inlineExpressions(ts.compact([
86122                         createPrivateIdentifierAssignment(info, initializeExpression || readExpression, factory.createBinaryExpression(returnValue ? factory.createAssignment(returnValue, existingValue) : existingValue, operator, factory.createNumericLiteral(1)), 62 /* EqualsToken */),
86123                         returnValue
86124                     ])), node);
86125                 }
86126             }
86127             return ts.visitEachChild(node, visitor, context);
86128         }
86129         function visitForStatement(node) {
86130             if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) {
86131                 return factory.updateForStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), visitPostfixUnaryExpression(node.incrementor, /*valueIsDiscarded*/ true), ts.visitNode(node.statement, visitor, ts.isStatement));
86132             }
86133             return ts.visitEachChild(node, visitor, context);
86134         }
86135         function visitExpressionStatement(node) {
86136             if (ts.isPostfixUnaryExpression(node.expression)) {
86137                 return factory.updateExpressionStatement(node, visitPostfixUnaryExpression(node.expression, /*valueIsDiscarded*/ true));
86138             }
86139             return ts.visitEachChild(node, visitor, context);
86140         }
86141         function createCopiableReceiverExpr(receiver) {
86142             var clone = ts.nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver);
86143             if (ts.isSimpleInlineableExpression(receiver)) {
86144                 return { readExpression: clone, initializeExpression: undefined };
86145             }
86146             var readExpression = factory.createTempVariable(hoistVariableDeclaration);
86147             var initializeExpression = factory.createAssignment(readExpression, clone);
86148             return { readExpression: readExpression, initializeExpression: initializeExpression };
86149         }
86150         function visitCallExpression(node) {
86151             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) {
86152                 // Transform call expressions of private names to properly bind the `this` parameter.
86153                 var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
86154                 if (ts.isCallChain(node)) {
86155                     return factory.updateCallChain(node, factory.createPropertyAccessChain(ts.visitNode(target, visitor), node.questionDotToken, "call"), 
86156                     /*questionDotToken*/ undefined, 
86157                     /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression)));
86158                 }
86159                 return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), 
86160                 /*typeArguments*/ undefined, __spreadArray([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression)));
86161             }
86162             return ts.visitEachChild(node, visitor, context);
86163         }
86164         function visitTaggedTemplateExpression(node) {
86165             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) {
86166                 // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access.
86167                 var _a = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
86168                 return factory.updateTaggedTemplateExpression(node, factory.createCallExpression(factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "bind"), 
86169                 /*typeArguments*/ undefined, [ts.visitNode(thisArg, visitor, ts.isExpression)]), 
86170                 /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isTemplateLiteral));
86171             }
86172             return ts.visitEachChild(node, visitor, context);
86173         }
86174         function visitBinaryExpression(node) {
86175             if (shouldTransformPrivateFields) {
86176                 if (ts.isDestructuringAssignment(node)) {
86177                     var savedPendingExpressions = pendingExpressions;
86178                     pendingExpressions = undefined;
86179                     node = factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorDestructuringTarget), node.operatorToken, ts.visitNode(node.right, visitor));
86180                     var expr = ts.some(pendingExpressions) ?
86181                         factory.inlineExpressions(ts.compact(__spreadArray(__spreadArray([], pendingExpressions), [node]))) :
86182                         node;
86183                     pendingExpressions = savedPendingExpressions;
86184                     return expr;
86185                 }
86186                 if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) {
86187                     var info = accessPrivateIdentifier(node.left.name);
86188                     if (info) {
86189                         return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node);
86190                     }
86191                 }
86192             }
86193             return ts.visitEachChild(node, visitor, context);
86194         }
86195         function createPrivateIdentifierAssignment(info, receiver, right, operator) {
86196             switch (info.placement) {
86197                 case 0 /* InstanceField */: {
86198                     return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator);
86199                 }
86200                 default: return ts.Debug.fail("Unexpected private identifier placement");
86201             }
86202         }
86203         function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) {
86204             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
86205             right = ts.visitNode(right, visitor, ts.isExpression);
86206             if (ts.isCompoundAssignment(operator)) {
86207                 var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
86208                 return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(initializeExpression || readExpression, info.weakMapName, factory.createBinaryExpression(context.getEmitHelperFactory().createClassPrivateFieldGetHelper(readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right));
86209             }
86210             else {
86211                 return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.weakMapName, right);
86212             }
86213         }
86214         /**
86215          * Set up the environment for a class.
86216          */
86217         function visitClassLike(node) {
86218             var savedPendingExpressions = pendingExpressions;
86219             pendingExpressions = undefined;
86220             if (shouldTransformPrivateFields) {
86221                 startPrivateIdentifierEnvironment();
86222             }
86223             var result = ts.isClassDeclaration(node) ?
86224                 visitClassDeclaration(node) :
86225                 visitClassExpression(node);
86226             if (shouldTransformPrivateFields) {
86227                 endPrivateIdentifierEnvironment();
86228             }
86229             pendingExpressions = savedPendingExpressions;
86230             return result;
86231         }
86232         function doesClassElementNeedTransform(node) {
86233             return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name));
86234         }
86235         function visitClassDeclaration(node) {
86236             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
86237                 return ts.visitEachChild(node, visitor, context);
86238             }
86239             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
86240             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */);
86241             var statements = [
86242                 factory.updateClassDeclaration(node, 
86243                 /*decorators*/ undefined, node.modifiers, node.name, 
86244                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass))
86245             ];
86246             // Write any pending expressions from elided or moved computed property names
86247             if (ts.some(pendingExpressions)) {
86248                 statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
86249             }
86250             // Emit static property assignment. Because classDeclaration is lexically evaluated,
86251             // it is safe to emit static property assignment after classDeclaration
86252             // From ES6 specification:
86253             //      HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
86254             //                                  a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
86255             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
86256             if (ts.some(staticProperties)) {
86257                 addPropertyStatements(statements, staticProperties, factory.getInternalName(node));
86258             }
86259             return statements;
86260         }
86261         function visitClassExpression(node) {
86262             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
86263                 return ts.visitEachChild(node, visitor, context);
86264             }
86265             // If this class expression is a transformation of a decorated class declaration,
86266             // then we want to output the pendingExpressions as statements, not as inlined
86267             // expressions with the class statement.
86268             //
86269             // In this case, we use pendingStatements to produce the same output as the
86270             // class declaration transformation. The VariableStatement visitor will insert
86271             // these statements after the class expression variable statement.
86272             var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node));
86273             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
86274             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
86275             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */);
86276             var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, 
86277             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass));
86278             if (ts.some(staticProperties) || ts.some(pendingExpressions)) {
86279                 if (isDecoratedClassDeclaration) {
86280                     ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
86281                     // Write any pending expressions from elided or moved computed property names
86282                     if (pendingStatements && pendingExpressions && ts.some(pendingExpressions)) {
86283                         pendingStatements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
86284                     }
86285                     if (pendingStatements && ts.some(staticProperties)) {
86286                         addPropertyStatements(pendingStatements, staticProperties, factory.getInternalName(node));
86287                     }
86288                     return classExpression;
86289                 }
86290                 else {
86291                     var expressions = [];
86292                     var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */;
86293                     var temp = factory.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference);
86294                     if (isClassWithConstructorReference) {
86295                         // record an alias as the class name is not in scope for statics.
86296                         enableSubstitutionForClassAliases();
86297                         var alias = factory.cloneNode(temp);
86298                         alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
86299                         classAliases[ts.getOriginalNodeId(node)] = alias;
86300                     }
86301                     // To preserve the behavior of the old emitter, we explicitly indent
86302                     // the body of a class with static initializers.
86303                     ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression));
86304                     expressions.push(ts.startOnNewLine(factory.createAssignment(temp, classExpression)));
86305                     // Add any pending expressions leftover from elided or relocated computed property names
86306                     ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine));
86307                     ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp));
86308                     expressions.push(ts.startOnNewLine(temp));
86309                     return factory.inlineExpressions(expressions);
86310                 }
86311             }
86312             return classExpression;
86313         }
86314         function transformClassMembers(node, isDerivedClass) {
86315             if (shouldTransformPrivateFields) {
86316                 // Declare private names.
86317                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
86318                     var member = _a[_i];
86319                     if (ts.isPrivateIdentifierPropertyDeclaration(member)) {
86320                         addPrivateIdentifierToEnvironment(member.name);
86321                     }
86322                 }
86323             }
86324             var members = [];
86325             var constructor = transformConstructor(node, isDerivedClass);
86326             if (constructor) {
86327                 members.push(constructor);
86328             }
86329             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
86330             return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members);
86331         }
86332         function isPropertyDeclarationThatRequiresConstructorStatement(member) {
86333             if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member) || ts.hasSyntacticModifier(ts.getOriginalNode(member), 128 /* Abstract */)) {
86334                 return false;
86335             }
86336             if (context.getCompilerOptions().useDefineForClassFields) {
86337                 // If we are using define semantics and targeting ESNext or higher,
86338                 // then we don't need to transform any class properties.
86339                 return languageVersion < 99 /* ESNext */;
86340             }
86341             return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member);
86342         }
86343         function transformConstructor(node, isDerivedClass) {
86344             var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration);
86345             var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement);
86346             if (!ts.some(properties)) {
86347                 return constructor;
86348             }
86349             var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context);
86350             var body = transformConstructorBody(node, constructor, isDerivedClass);
86351             if (!body) {
86352                 return undefined;
86353             }
86354             return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration(
86355             /*decorators*/ undefined, 
86356             /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor));
86357         }
86358         function transformConstructorBody(node, constructor, isDerivedClass) {
86359             var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields;
86360             var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false);
86361             if (!useDefineForClassFields) {
86362                 properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); });
86363             }
86364             // Only generate synthetic constructor when there are property initializers to move.
86365             if (!constructor && !ts.some(properties)) {
86366                 return ts.visitFunctionBody(/*node*/ undefined, visitor, context);
86367             }
86368             resumeLexicalEnvironment();
86369             var indexOfFirstStatement = 0;
86370             var statements = [];
86371             if (!constructor && isDerivedClass) {
86372                 // Add a synthetic `super` call:
86373                 //
86374                 //  super(...arguments);
86375                 //
86376                 statements.push(factory.createExpressionStatement(factory.createCallExpression(factory.createSuper(), 
86377                 /*typeArguments*/ undefined, [factory.createSpreadElement(factory.createIdentifier("arguments"))])));
86378             }
86379             if (constructor) {
86380                 indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor);
86381             }
86382             // Add the property initializers. Transforms this:
86383             //
86384             //  public x = 1;
86385             //
86386             // Into this:
86387             //
86388             //  constructor() {
86389             //      this.x = 1;
86390             //  }
86391             //
86392             if (constructor === null || constructor === void 0 ? void 0 : constructor.body) {
86393                 var afterParameterProperties = ts.findIndex(constructor.body.statements, function (s) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(s), constructor); }, indexOfFirstStatement);
86394                 if (afterParameterProperties === -1) {
86395                     afterParameterProperties = constructor.body.statements.length;
86396                 }
86397                 if (afterParameterProperties > indexOfFirstStatement) {
86398                     if (!useDefineForClassFields) {
86399                         ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement));
86400                     }
86401                     indexOfFirstStatement = afterParameterProperties;
86402                 }
86403             }
86404             addPropertyStatements(statements, properties, factory.createThis());
86405             // Add existing statements, skipping the initial super call.
86406             if (constructor) {
86407                 ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement));
86408             }
86409             statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
86410             return ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), 
86411             /*location*/ constructor ? constructor.body.statements : node.members), 
86412             /*multiLine*/ true), 
86413             /*location*/ constructor ? constructor.body : undefined);
86414         }
86415         /**
86416          * Generates assignment statements for property initializers.
86417          *
86418          * @param properties An array of property declarations to transform.
86419          * @param receiver The receiver on which each property should be assigned.
86420          */
86421         function addPropertyStatements(statements, properties, receiver) {
86422             for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) {
86423                 var property = properties_7[_i];
86424                 var expression = transformProperty(property, receiver);
86425                 if (!expression) {
86426                     continue;
86427                 }
86428                 var statement = factory.createExpressionStatement(expression);
86429                 ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
86430                 ts.setCommentRange(statement, property);
86431                 ts.setOriginalNode(statement, property);
86432                 statements.push(statement);
86433             }
86434         }
86435         /**
86436          * Generates assignment expressions for property initializers.
86437          *
86438          * @param properties An array of property declarations to transform.
86439          * @param receiver The receiver on which each property should be assigned.
86440          */
86441         function generateInitializedPropertyExpressions(properties, receiver) {
86442             var expressions = [];
86443             for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
86444                 var property = properties_8[_i];
86445                 var expression = transformProperty(property, receiver);
86446                 if (!expression) {
86447                     continue;
86448                 }
86449                 ts.startOnNewLine(expression);
86450                 ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
86451                 ts.setCommentRange(expression, property);
86452                 ts.setOriginalNode(expression, property);
86453                 expressions.push(expression);
86454             }
86455             return expressions;
86456         }
86457         /**
86458          * Transforms a property initializer into an assignment statement.
86459          *
86460          * @param property The property declaration.
86461          * @param receiver The object receiving the property assignment.
86462          */
86463         function transformProperty(property, receiver) {
86464             var _a;
86465             // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
86466             var emitAssignment = !context.getCompilerOptions().useDefineForClassFields;
86467             var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression)
86468                 ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name))
86469                 : property.name;
86470             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) {
86471                 var privateIdentifierInfo = accessPrivateIdentifier(propertyName);
86472                 if (privateIdentifierInfo) {
86473                     switch (privateIdentifierInfo.placement) {
86474                         case 0 /* InstanceField */: {
86475                             return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName);
86476                         }
86477                     }
86478                 }
86479                 else {
86480                     ts.Debug.fail("Undeclared private name for property declaration.");
86481                 }
86482             }
86483             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
86484                 return undefined;
86485             }
86486             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
86487                 return undefined;
86488             }
86489             var propertyOriginalNode = ts.getOriginalNode(property);
86490             if (ts.hasSyntacticModifier(propertyOriginalNode, 128 /* Abstract */)) {
86491                 return undefined;
86492             }
86493             var initializer = property.initializer || emitAssignment ? (_a = ts.visitNode(property.initializer, visitor, ts.isExpression)) !== null && _a !== void 0 ? _a : factory.createVoidZero()
86494                 : ts.isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && ts.isIdentifier(propertyName) ? propertyName
86495                     : factory.createVoidZero();
86496             if (emitAssignment || ts.isPrivateIdentifier(propertyName)) {
86497                 var memberAccess = ts.createMemberAccessForPropertyName(factory, receiver, propertyName, /*location*/ propertyName);
86498                 return factory.createAssignment(memberAccess, initializer);
86499             }
86500             else {
86501                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
86502                     : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
86503                         : propertyName;
86504                 var descriptor = factory.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true });
86505                 return factory.createObjectDefinePropertyCall(receiver, name, descriptor);
86506             }
86507         }
86508         function enableSubstitutionForClassAliases() {
86509             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
86510                 enabledSubstitutions |= 1 /* ClassAliases */;
86511                 // We need to enable substitutions for identifiers. This allows us to
86512                 // substitute class names inside of a class declaration.
86513                 context.enableSubstitution(78 /* Identifier */);
86514                 // Keep track of class aliases.
86515                 classAliases = [];
86516             }
86517         }
86518         /**
86519          * Hooks node substitutions.
86520          *
86521          * @param hint The context for the emitter.
86522          * @param node The node to substitute.
86523          */
86524         function onSubstituteNode(hint, node) {
86525             node = previousOnSubstituteNode(hint, node);
86526             if (hint === 1 /* Expression */) {
86527                 return substituteExpression(node);
86528             }
86529             return node;
86530         }
86531         function substituteExpression(node) {
86532             switch (node.kind) {
86533                 case 78 /* Identifier */:
86534                     return substituteExpressionIdentifier(node);
86535             }
86536             return node;
86537         }
86538         function substituteExpressionIdentifier(node) {
86539             return trySubstituteClassAlias(node) || node;
86540         }
86541         function trySubstituteClassAlias(node) {
86542             if (enabledSubstitutions & 1 /* ClassAliases */) {
86543                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
86544                     // Due to the emit for class decorators, any reference to the class from inside of the class body
86545                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
86546                     // behavior of class names in ES6.
86547                     // Also, when emitting statics for class expressions, we must substitute a class alias for
86548                     // constructor references in static property initializers.
86549                     var declaration = resolver.getReferencedValueDeclaration(node);
86550                     if (declaration) {
86551                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
86552                         if (classAlias) {
86553                             var clone_2 = factory.cloneNode(classAlias);
86554                             ts.setSourceMapRange(clone_2, node);
86555                             ts.setCommentRange(clone_2, node);
86556                             return clone_2;
86557                         }
86558                     }
86559                 }
86560             }
86561             return undefined;
86562         }
86563         /**
86564          * If the name is a computed property, this function transforms it, then either returns an expression which caches the
86565          * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
86566          * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
86567          */
86568         function getPropertyNameExpressionIfNeeded(name, shouldHoist) {
86569             if (ts.isComputedPropertyName(name)) {
86570                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
86571                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
86572                 var inlinable = ts.isSimpleInlineableExpression(innerExpression);
86573                 var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left);
86574                 if (!alreadyTransformed && !inlinable && shouldHoist) {
86575                     var generatedName = factory.getGeneratedNameForNode(name);
86576                     hoistVariableDeclaration(generatedName);
86577                     return factory.createAssignment(generatedName, expression);
86578                 }
86579                 return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression;
86580             }
86581         }
86582         function startPrivateIdentifierEnvironment() {
86583             privateIdentifierEnvironmentStack.push(currentPrivateIdentifierEnvironment);
86584             currentPrivateIdentifierEnvironment = undefined;
86585         }
86586         function endPrivateIdentifierEnvironment() {
86587             currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop();
86588         }
86589         function getPrivateIdentifierEnvironment() {
86590             return currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = new ts.Map());
86591         }
86592         function getPendingExpressions() {
86593             return pendingExpressions || (pendingExpressions = []);
86594         }
86595         function addPrivateIdentifierToEnvironment(name) {
86596             var text = ts.getTextOfPropertyName(name);
86597             var weakMapName = factory.createUniqueName("_" + text.substring(1), 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */);
86598             hoistVariableDeclaration(weakMapName);
86599             getPrivateIdentifierEnvironment().set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName });
86600             getPendingExpressions().push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), 
86601             /*typeArguments*/ undefined, [])));
86602         }
86603         function accessPrivateIdentifier(name) {
86604             if (currentPrivateIdentifierEnvironment) {
86605                 var info = currentPrivateIdentifierEnvironment.get(name.escapedText);
86606                 if (info) {
86607                     return info;
86608                 }
86609             }
86610             for (var i = privateIdentifierEnvironmentStack.length - 1; i >= 0; --i) {
86611                 var env = privateIdentifierEnvironmentStack[i];
86612                 if (!env) {
86613                     continue;
86614                 }
86615                 var info = env.get(name.escapedText);
86616                 if (info) {
86617                     return info;
86618                 }
86619             }
86620             return undefined;
86621         }
86622         function wrapPrivateIdentifierForDestructuringTarget(node) {
86623             var parameter = factory.getGeneratedNameForNode(node);
86624             var info = accessPrivateIdentifier(node.name);
86625             if (!info) {
86626                 return ts.visitEachChild(node, visitor, context);
86627             }
86628             var receiver = node.expression;
86629             // We cannot copy `this` or `super` into the function because they will be bound
86630             // differently inside the function.
86631             if (ts.isThisProperty(node) || ts.isSuperProperty(node) || !ts.isSimpleCopiableExpression(node.expression)) {
86632                 receiver = factory.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ true);
86633                 getPendingExpressions().push(factory.createBinaryExpression(receiver, 62 /* EqualsToken */, node.expression));
86634             }
86635             return factory.createPropertyAccessExpression(
86636             // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560)
86637             factory.createParenthesizedExpression(factory.createObjectLiteralExpression([
86638                 factory.createSetAccessorDeclaration(
86639                 /*decorators*/ undefined, 
86640                 /*modifiers*/ undefined, "value", [factory.createParameterDeclaration(
86641                     /*decorators*/ undefined, 
86642                     /*modifiers*/ undefined, 
86643                     /*dotDotDotToken*/ undefined, parameter, 
86644                     /*questionToken*/ undefined, 
86645                     /*type*/ undefined, 
86646                     /*initializer*/ undefined)], factory.createBlock([factory.createExpressionStatement(createPrivateIdentifierAssignment(info, receiver, parameter, 62 /* EqualsToken */))]))
86647             ])), "value");
86648         }
86649         function visitArrayAssignmentTarget(node) {
86650             var target = ts.getTargetOfBindingOrAssignmentElement(node);
86651             if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
86652                 var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
86653                 if (ts.isAssignmentExpression(node)) {
86654                     return factory.updateBinaryExpression(node, wrapped, node.operatorToken, ts.visitNode(node.right, visitor, ts.isExpression));
86655                 }
86656                 else if (ts.isSpreadElement(node)) {
86657                     return factory.updateSpreadElement(node, wrapped);
86658                 }
86659                 else {
86660                     return wrapped;
86661                 }
86662             }
86663             return ts.visitNode(node, visitorDestructuringTarget);
86664         }
86665         function visitObjectAssignmentTarget(node) {
86666             if (ts.isPropertyAssignment(node)) {
86667                 var target = ts.getTargetOfBindingOrAssignmentElement(node);
86668                 if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
86669                     var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
86670                     var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
86671                     return factory.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), initializer ? factory.createAssignment(wrapped, ts.visitNode(initializer, visitor)) : wrapped);
86672                 }
86673                 return factory.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), ts.visitNode(node.initializer, visitorDestructuringTarget));
86674             }
86675             return ts.visitNode(node, visitor);
86676         }
86677         function visitAssignmentPattern(node) {
86678             if (ts.isArrayLiteralExpression(node)) {
86679                 // Transforms private names in destructuring assignment array bindings.
86680                 //
86681                 // Source:
86682                 // ([ this.#myProp ] = [ "hello" ]);
86683                 //
86684                 // Transformation:
86685                 // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ];
86686                 return factory.updateArrayLiteralExpression(node, ts.visitNodes(node.elements, visitArrayAssignmentTarget, ts.isExpression));
86687             }
86688             else {
86689                 // Transforms private names in destructuring assignment object bindings.
86690                 //
86691                 // Source:
86692                 // ({ stringProperty: this.#myProp } = { stringProperty: "hello" });
86693                 //
86694                 // Transformation:
86695                 // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" };
86696                 return factory.updateObjectLiteralExpression(node, ts.visitNodes(node.properties, visitObjectAssignmentTarget, ts.isObjectLiteralElementLike));
86697             }
86698         }
86699     }
86700     ts.transformClassFields = transformClassFields;
86701     function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) {
86702         return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakMapName, "set"), 
86703         /*typeArguments*/ undefined, [receiver, initializer || ts.factory.createVoidZero()]);
86704     }
86705 })(ts || (ts = {}));
86706 /*@internal*/
86707 var ts;
86708 (function (ts) {
86709     var ES2017SubstitutionFlags;
86710     (function (ES2017SubstitutionFlags) {
86711         /** Enables substitutions for async methods with `super` calls. */
86712         ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
86713     })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
86714     var ContextFlags;
86715     (function (ContextFlags) {
86716         ContextFlags[ContextFlags["NonTopLevel"] = 1] = "NonTopLevel";
86717         ContextFlags[ContextFlags["HasLexicalThis"] = 2] = "HasLexicalThis";
86718     })(ContextFlags || (ContextFlags = {}));
86719     function transformES2017(context) {
86720         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
86721         var resolver = context.getEmitResolver();
86722         var compilerOptions = context.getCompilerOptions();
86723         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
86724         /**
86725          * Keeps track of whether expression substitution has been enabled for specific edge cases.
86726          * They are persisted between each SourceFile transformation and should not be reset.
86727          */
86728         var enabledSubstitutions;
86729         /**
86730          * This keeps track of containers where `super` is valid, for use with
86731          * just-in-time substitution for `super` expressions inside of async methods.
86732          */
86733         var enclosingSuperContainerFlags = 0;
86734         var enclosingFunctionParameterNames;
86735         /**
86736          * Keeps track of property names accessed on super (`super.x`) within async functions.
86737          */
86738         var capturedSuperProperties;
86739         /** Whether the async function contains an element access on super (`super[x]`). */
86740         var hasSuperElementAccess;
86741         /** A set of node IDs for generated super accessors (variable statements). */
86742         var substitutedSuperAccessors = [];
86743         var contextFlags = 0;
86744         // Save the previous transformation hooks.
86745         var previousOnEmitNode = context.onEmitNode;
86746         var previousOnSubstituteNode = context.onSubstituteNode;
86747         // Set new transformation hooks.
86748         context.onEmitNode = onEmitNode;
86749         context.onSubstituteNode = onSubstituteNode;
86750         return ts.chainBundle(context, transformSourceFile);
86751         function transformSourceFile(node) {
86752             if (node.isDeclarationFile) {
86753                 return node;
86754             }
86755             setContextFlag(1 /* NonTopLevel */, false);
86756             setContextFlag(2 /* HasLexicalThis */, !ts.isEffectiveStrictModeSourceFile(node, compilerOptions));
86757             var visited = ts.visitEachChild(node, visitor, context);
86758             ts.addEmitHelpers(visited, context.readEmitHelpers());
86759             return visited;
86760         }
86761         function setContextFlag(flag, val) {
86762             contextFlags = val ? contextFlags | flag : contextFlags & ~flag;
86763         }
86764         function inContext(flags) {
86765             return (contextFlags & flags) !== 0;
86766         }
86767         function inTopLevelContext() {
86768             return !inContext(1 /* NonTopLevel */);
86769         }
86770         function inHasLexicalThisContext() {
86771             return inContext(2 /* HasLexicalThis */);
86772         }
86773         function doWithContext(flags, cb, value) {
86774             var contextFlagsToSet = flags & ~contextFlags;
86775             if (contextFlagsToSet) {
86776                 setContextFlag(contextFlagsToSet, /*val*/ true);
86777                 var result = cb(value);
86778                 setContextFlag(contextFlagsToSet, /*val*/ false);
86779                 return result;
86780             }
86781             return cb(value);
86782         }
86783         function visitDefault(node) {
86784             return ts.visitEachChild(node, visitor, context);
86785         }
86786         function visitor(node) {
86787             if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) {
86788                 return node;
86789             }
86790             switch (node.kind) {
86791                 case 129 /* AsyncKeyword */:
86792                     // ES2017 async modifier should be elided for targets < ES2017
86793                     return undefined;
86794                 case 213 /* AwaitExpression */:
86795                     return visitAwaitExpression(node);
86796                 case 165 /* MethodDeclaration */:
86797                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node);
86798                 case 251 /* FunctionDeclaration */:
86799                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node);
86800                 case 208 /* FunctionExpression */:
86801                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node);
86802                 case 209 /* ArrowFunction */:
86803                     return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node);
86804                 case 201 /* PropertyAccessExpression */:
86805                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) {
86806                         capturedSuperProperties.add(node.name.escapedText);
86807                     }
86808                     return ts.visitEachChild(node, visitor, context);
86809                 case 202 /* ElementAccessExpression */:
86810                     if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) {
86811                         hasSuperElementAccess = true;
86812                     }
86813                     return ts.visitEachChild(node, visitor, context);
86814                 case 167 /* GetAccessor */:
86815                 case 168 /* SetAccessor */:
86816                 case 166 /* Constructor */:
86817                 case 252 /* ClassDeclaration */:
86818                 case 221 /* ClassExpression */:
86819                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node);
86820                 default:
86821                     return ts.visitEachChild(node, visitor, context);
86822             }
86823         }
86824         function asyncBodyVisitor(node) {
86825             if (ts.isNodeWithPossibleHoistedDeclaration(node)) {
86826                 switch (node.kind) {
86827                     case 232 /* VariableStatement */:
86828                         return visitVariableStatementInAsyncBody(node);
86829                     case 237 /* ForStatement */:
86830                         return visitForStatementInAsyncBody(node);
86831                     case 238 /* ForInStatement */:
86832                         return visitForInStatementInAsyncBody(node);
86833                     case 239 /* ForOfStatement */:
86834                         return visitForOfStatementInAsyncBody(node);
86835                     case 287 /* CatchClause */:
86836                         return visitCatchClauseInAsyncBody(node);
86837                     case 230 /* Block */:
86838                     case 244 /* SwitchStatement */:
86839                     case 258 /* CaseBlock */:
86840                     case 284 /* CaseClause */:
86841                     case 285 /* DefaultClause */:
86842                     case 247 /* TryStatement */:
86843                     case 235 /* DoStatement */:
86844                     case 236 /* WhileStatement */:
86845                     case 234 /* IfStatement */:
86846                     case 243 /* WithStatement */:
86847                     case 245 /* LabeledStatement */:
86848                         return ts.visitEachChild(node, asyncBodyVisitor, context);
86849                     default:
86850                         return ts.Debug.assertNever(node, "Unhandled node.");
86851                 }
86852             }
86853             return visitor(node);
86854         }
86855         function visitCatchClauseInAsyncBody(node) {
86856             var catchClauseNames = new ts.Set();
86857             recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217
86858             // names declared in a catch variable are block scoped
86859             var catchClauseUnshadowedNames;
86860             catchClauseNames.forEach(function (_, escapedName) {
86861                 if (enclosingFunctionParameterNames.has(escapedName)) {
86862                     if (!catchClauseUnshadowedNames) {
86863                         catchClauseUnshadowedNames = new ts.Set(enclosingFunctionParameterNames);
86864                     }
86865                     catchClauseUnshadowedNames.delete(escapedName);
86866                 }
86867             });
86868             if (catchClauseUnshadowedNames) {
86869                 var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
86870                 enclosingFunctionParameterNames = catchClauseUnshadowedNames;
86871                 var result = ts.visitEachChild(node, asyncBodyVisitor, context);
86872                 enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
86873                 return result;
86874             }
86875             else {
86876                 return ts.visitEachChild(node, asyncBodyVisitor, context);
86877             }
86878         }
86879         function visitVariableStatementInAsyncBody(node) {
86880             if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
86881                 var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false);
86882                 return expression ? factory.createExpressionStatement(expression) : undefined;
86883             }
86884             return ts.visitEachChild(node, visitor, context);
86885         }
86886         function visitForInStatementInAsyncBody(node) {
86887             return factory.updateForInStatement(node, isVariableDeclarationListWithCollidingName(node.initializer)
86888                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
86889                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock));
86890         }
86891         function visitForOfStatementInAsyncBody(node) {
86892             return factory.updateForOfStatement(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer)
86893                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
86894                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock));
86895         }
86896         function visitForStatementInAsyncBody(node) {
86897             var initializer = node.initializer; // TODO: GH#18217
86898             return factory.updateForStatement(node, isVariableDeclarationListWithCollidingName(initializer)
86899                 ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
86900                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock));
86901         }
86902         /**
86903          * Visits an AwaitExpression node.
86904          *
86905          * This function will be called any time a ES2017 await expression is encountered.
86906          *
86907          * @param node The node to visit.
86908          */
86909         function visitAwaitExpression(node) {
86910             // do not downlevel a top-level await as it is module syntax...
86911             if (inTopLevelContext()) {
86912                 return ts.visitEachChild(node, visitor, context);
86913             }
86914             return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(
86915             /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
86916         }
86917         /**
86918          * Visits a MethodDeclaration node.
86919          *
86920          * This function will be called when one of the following conditions are met:
86921          * - The node is marked as async
86922          *
86923          * @param node The node to visit.
86924          */
86925         function visitMethodDeclaration(node) {
86926             return factory.updateMethodDeclaration(node, 
86927             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
86928             /*questionToken*/ undefined, 
86929             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86930             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
86931                 ? transformAsyncFunctionBody(node)
86932                 : ts.visitFunctionBody(node.body, visitor, context));
86933         }
86934         /**
86935          * Visits a FunctionDeclaration node.
86936          *
86937          * This function will be called when one of the following conditions are met:
86938          * - The node is marked async
86939          *
86940          * @param node The node to visit.
86941          */
86942         function visitFunctionDeclaration(node) {
86943             return factory.updateFunctionDeclaration(node, 
86944             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
86945             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86946             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
86947                 ? transformAsyncFunctionBody(node)
86948                 : ts.visitFunctionBody(node.body, visitor, context));
86949         }
86950         /**
86951          * Visits a FunctionExpression node.
86952          *
86953          * This function will be called when one of the following conditions are met:
86954          * - The node is marked async
86955          *
86956          * @param node The node to visit.
86957          */
86958         function visitFunctionExpression(node) {
86959             return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
86960             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86961             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
86962                 ? transformAsyncFunctionBody(node)
86963                 : ts.visitFunctionBody(node.body, visitor, context));
86964         }
86965         /**
86966          * Visits an ArrowFunction.
86967          *
86968          * This function will be called when one of the following conditions are met:
86969          * - The node is marked async
86970          *
86971          * @param node The node to visit.
86972          */
86973         function visitArrowFunction(node) {
86974             return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), 
86975             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86976             /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */
86977                 ? transformAsyncFunctionBody(node)
86978                 : ts.visitFunctionBody(node.body, visitor, context));
86979         }
86980         function recordDeclarationName(_a, names) {
86981             var name = _a.name;
86982             if (ts.isIdentifier(name)) {
86983                 names.add(name.escapedText);
86984             }
86985             else {
86986                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
86987                     var element = _b[_i];
86988                     if (!ts.isOmittedExpression(element)) {
86989                         recordDeclarationName(element, names);
86990                     }
86991                 }
86992             }
86993         }
86994         function isVariableDeclarationListWithCollidingName(node) {
86995             return !!node
86996                 && ts.isVariableDeclarationList(node)
86997                 && !(node.flags & 3 /* BlockScoped */)
86998                 && node.declarations.some(collidesWithParameterName);
86999         }
87000         function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) {
87001             hoistVariableDeclarationList(node);
87002             var variables = ts.getInitializedVariables(node);
87003             if (variables.length === 0) {
87004                 if (hasReceiver) {
87005                     return ts.visitNode(factory.converters.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression);
87006                 }
87007                 return undefined;
87008             }
87009             return factory.inlineExpressions(ts.map(variables, transformInitializedVariable));
87010         }
87011         function hoistVariableDeclarationList(node) {
87012             ts.forEach(node.declarations, hoistVariable);
87013         }
87014         function hoistVariable(_a) {
87015             var name = _a.name;
87016             if (ts.isIdentifier(name)) {
87017                 hoistVariableDeclaration(name);
87018             }
87019             else {
87020                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
87021                     var element = _b[_i];
87022                     if (!ts.isOmittedExpression(element)) {
87023                         hoistVariable(element);
87024                     }
87025                 }
87026             }
87027         }
87028         function transformInitializedVariable(node) {
87029             var converted = ts.setSourceMapRange(factory.createAssignment(factory.converters.convertToAssignmentElementTarget(node.name), node.initializer), node);
87030             return ts.visitNode(converted, visitor, ts.isExpression);
87031         }
87032         function collidesWithParameterName(_a) {
87033             var name = _a.name;
87034             if (ts.isIdentifier(name)) {
87035                 return enclosingFunctionParameterNames.has(name.escapedText);
87036             }
87037             else {
87038                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
87039                     var element = _b[_i];
87040                     if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) {
87041                         return true;
87042                     }
87043                 }
87044             }
87045             return false;
87046         }
87047         function transformAsyncFunctionBody(node) {
87048             resumeLexicalEnvironment();
87049             var original = ts.getOriginalNode(node, ts.isFunctionLike);
87050             var nodeType = original.type;
87051             var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
87052             var isArrowFunction = node.kind === 209 /* ArrowFunction */;
87053             var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
87054             // An async function is emit as an outer function that calls an inner
87055             // generator function. To preserve lexical bindings, we pass the current
87056             // `this` and `arguments` objects to `__awaiter`. The generator function
87057             // passed to `__awaiter` is executed inside of the callback to the
87058             // promise constructor.
87059             var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
87060             enclosingFunctionParameterNames = new ts.Set();
87061             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
87062                 var parameter = _a[_i];
87063                 recordDeclarationName(parameter, enclosingFunctionParameterNames);
87064             }
87065             var savedCapturedSuperProperties = capturedSuperProperties;
87066             var savedHasSuperElementAccess = hasSuperElementAccess;
87067             if (!isArrowFunction) {
87068                 capturedSuperProperties = new ts.Set();
87069                 hasSuperElementAccess = false;
87070             }
87071             var result;
87072             if (!isArrowFunction) {
87073                 var statements = [];
87074                 var statementOffset = factory.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ false, visitor);
87075                 statements.push(factory.createReturnStatement(emitHelpers().createAwaiterHelper(inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
87076                 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
87077                 // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
87078                 // This step isn't needed if we eventually transform this to ES5.
87079                 var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
87080                 if (emitSuperHelpers) {
87081                     enableSubstitutionForAsyncMethodsWithSuper();
87082                     if (capturedSuperProperties.size) {
87083                         var variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties);
87084                         substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
87085                         ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
87086                     }
87087                 }
87088                 var block = factory.createBlock(statements, /*multiLine*/ true);
87089                 ts.setTextRange(block, node.body);
87090                 if (emitSuperHelpers && hasSuperElementAccess) {
87091                     // Emit helpers for super element access expressions (`super[x]`).
87092                     if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
87093                         ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
87094                     }
87095                     else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
87096                         ts.addEmitHelper(block, ts.asyncSuperHelper);
87097                     }
87098                 }
87099                 result = block;
87100             }
87101             else {
87102                 var expression = emitHelpers().createAwaiterHelper(inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body));
87103                 var declarations = endLexicalEnvironment();
87104                 if (ts.some(declarations)) {
87105                     var block = factory.converters.convertToFunctionBlock(expression);
87106                     result = factory.updateBlock(block, ts.setTextRange(factory.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
87107                 }
87108                 else {
87109                     result = expression;
87110                 }
87111             }
87112             enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
87113             if (!isArrowFunction) {
87114                 capturedSuperProperties = savedCapturedSuperProperties;
87115                 hasSuperElementAccess = savedHasSuperElementAccess;
87116             }
87117             return result;
87118         }
87119         function transformAsyncFunctionBodyWorker(body, start) {
87120             if (ts.isBlock(body)) {
87121                 return factory.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start));
87122             }
87123             else {
87124                 return factory.converters.convertToFunctionBlock(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody));
87125             }
87126         }
87127         function getPromiseConstructor(type) {
87128             var typeName = type && ts.getEntityNameFromTypeNode(type);
87129             if (typeName && ts.isEntityName(typeName)) {
87130                 var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
87131                 if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
87132                     || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
87133                     return typeName;
87134                 }
87135             }
87136             return undefined;
87137         }
87138         function enableSubstitutionForAsyncMethodsWithSuper() {
87139             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
87140                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
87141                 // We need to enable substitutions for call, property access, and element access
87142                 // if we need to rewrite super calls.
87143                 context.enableSubstitution(203 /* CallExpression */);
87144                 context.enableSubstitution(201 /* PropertyAccessExpression */);
87145                 context.enableSubstitution(202 /* ElementAccessExpression */);
87146                 // We need to be notified when entering and exiting declarations that bind super.
87147                 context.enableEmitNotification(252 /* ClassDeclaration */);
87148                 context.enableEmitNotification(165 /* MethodDeclaration */);
87149                 context.enableEmitNotification(167 /* GetAccessor */);
87150                 context.enableEmitNotification(168 /* SetAccessor */);
87151                 context.enableEmitNotification(166 /* Constructor */);
87152                 // We need to be notified when entering the generated accessor arrow functions.
87153                 context.enableEmitNotification(232 /* VariableStatement */);
87154             }
87155         }
87156         /**
87157          * Hook for node emit.
87158          *
87159          * @param hint A hint as to the intended usage of the node.
87160          * @param node The node to emit.
87161          * @param emit A callback used to emit the node in the printer.
87162          */
87163         function onEmitNode(hint, node, emitCallback) {
87164             // If we need to support substitutions for `super` in an async method,
87165             // we should track it here.
87166             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
87167                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
87168                 if (superContainerFlags !== enclosingSuperContainerFlags) {
87169                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
87170                     enclosingSuperContainerFlags = superContainerFlags;
87171                     previousOnEmitNode(hint, node, emitCallback);
87172                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
87173                     return;
87174                 }
87175             }
87176             // Disable substitution in the generated super accessor itself.
87177             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
87178                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
87179                 enclosingSuperContainerFlags = 0;
87180                 previousOnEmitNode(hint, node, emitCallback);
87181                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
87182                 return;
87183             }
87184             previousOnEmitNode(hint, node, emitCallback);
87185         }
87186         /**
87187          * Hooks node substitutions.
87188          *
87189          * @param hint A hint as to the intended usage of the node.
87190          * @param node The node to substitute.
87191          */
87192         function onSubstituteNode(hint, node) {
87193             node = previousOnSubstituteNode(hint, node);
87194             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
87195                 return substituteExpression(node);
87196             }
87197             return node;
87198         }
87199         function substituteExpression(node) {
87200             switch (node.kind) {
87201                 case 201 /* PropertyAccessExpression */:
87202                     return substitutePropertyAccessExpression(node);
87203                 case 202 /* ElementAccessExpression */:
87204                     return substituteElementAccessExpression(node);
87205                 case 203 /* CallExpression */:
87206                     return substituteCallExpression(node);
87207             }
87208             return node;
87209         }
87210         function substitutePropertyAccessExpression(node) {
87211             if (node.expression.kind === 105 /* SuperKeyword */) {
87212                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), node.name), node);
87213             }
87214             return node;
87215         }
87216         function substituteElementAccessExpression(node) {
87217             if (node.expression.kind === 105 /* SuperKeyword */) {
87218                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
87219             }
87220             return node;
87221         }
87222         function substituteCallExpression(node) {
87223             var expression = node.expression;
87224             if (ts.isSuperProperty(expression)) {
87225                 var argumentExpression = ts.isPropertyAccessExpression(expression)
87226                     ? substitutePropertyAccessExpression(expression)
87227                     : substituteElementAccessExpression(expression);
87228                 return factory.createCallExpression(factory.createPropertyAccessExpression(argumentExpression, "call"), 
87229                 /*typeArguments*/ undefined, __spreadArray([
87230                     factory.createThis()
87231                 ], node.arguments));
87232             }
87233             return node;
87234         }
87235         function isSuperContainer(node) {
87236             var kind = node.kind;
87237             return kind === 252 /* ClassDeclaration */
87238                 || kind === 166 /* Constructor */
87239                 || kind === 165 /* MethodDeclaration */
87240                 || kind === 167 /* GetAccessor */
87241                 || kind === 168 /* SetAccessor */;
87242         }
87243         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
87244             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
87245                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */), 
87246                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
87247             }
87248             else {
87249                 return ts.setTextRange(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */), 
87250                 /*typeArguments*/ undefined, [argumentExpression]), location);
87251             }
87252         }
87253     }
87254     ts.transformES2017 = transformES2017;
87255     /** Creates a variable named `_super` with accessor properties for the given property names. */
87256     function createSuperAccessVariableStatement(factory, resolver, node, names) {
87257         // Create a variable declaration with a getter/setter (if binding) definition for each name:
87258         //   const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... });
87259         var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0;
87260         var accessors = [];
87261         names.forEach(function (_, key) {
87262             var name = ts.unescapeLeadingUnderscores(key);
87263             var getterAndSetter = [];
87264             getterAndSetter.push(factory.createPropertyAssignment("get", factory.createArrowFunction(
87265             /* modifiers */ undefined, 
87266             /* typeParameters */ undefined, 
87267             /* parameters */ [], 
87268             /* type */ undefined, 
87269             /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
87270             if (hasBinding) {
87271                 getterAndSetter.push(factory.createPropertyAssignment("set", factory.createArrowFunction(
87272                 /* modifiers */ undefined, 
87273                 /* typeParameters */ undefined, 
87274                 /* parameters */ [
87275                     factory.createParameterDeclaration(
87276                     /* decorators */ undefined, 
87277                     /* modifiers */ undefined, 
87278                     /* dotDotDotToken */ undefined, "v", 
87279                     /* questionToken */ undefined, 
87280                     /* type */ undefined, 
87281                     /* initializer */ undefined)
87282                 ], 
87283                 /* type */ undefined, 
87284                 /* equalsGreaterThanToken */ undefined, factory.createAssignment(ts.setEmitFlags(factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), factory.createIdentifier("v")))));
87285             }
87286             accessors.push(factory.createPropertyAssignment(name, factory.createObjectLiteralExpression(getterAndSetter)));
87287         });
87288         return factory.createVariableStatement(
87289         /* modifiers */ undefined, factory.createVariableDeclarationList([
87290             factory.createVariableDeclaration(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), 
87291             /*exclamationToken*/ undefined, 
87292             /* type */ undefined, factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "create"), 
87293             /* typeArguments */ undefined, [
87294                 factory.createNull(),
87295                 factory.createObjectLiteralExpression(accessors, /* multiline */ true)
87296             ]))
87297         ], 2 /* Const */));
87298     }
87299     ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
87300 })(ts || (ts = {}));
87301 /*@internal*/
87302 var ts;
87303 (function (ts) {
87304     var ESNextSubstitutionFlags;
87305     (function (ESNextSubstitutionFlags) {
87306         /** Enables substitutions for async methods with `super` calls. */
87307         ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
87308     })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
87309     // Facts we track as we traverse the tree
87310     var HierarchyFacts;
87311     (function (HierarchyFacts) {
87312         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
87313         //
87314         // Ancestor facts
87315         //
87316         HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis";
87317         HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer";
87318         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
87319         //
87320         // Ancestor masks
87321         //
87322         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask";
87323         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes";
87324         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes";
87325         HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes";
87326         HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes";
87327         HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes";
87328         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes";
87329         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes";
87330         HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes";
87331         HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes";
87332     })(HierarchyFacts || (HierarchyFacts = {}));
87333     function transformES2018(context) {
87334         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
87335         var resolver = context.getEmitResolver();
87336         var compilerOptions = context.getCompilerOptions();
87337         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
87338         var previousOnEmitNode = context.onEmitNode;
87339         context.onEmitNode = onEmitNode;
87340         var previousOnSubstituteNode = context.onSubstituteNode;
87341         context.onSubstituteNode = onSubstituteNode;
87342         var exportedVariableStatement = false;
87343         var enabledSubstitutions;
87344         var enclosingFunctionFlags;
87345         var enclosingSuperContainerFlags = 0;
87346         var hierarchyFacts = 0;
87347         var currentSourceFile;
87348         var taggedTemplateStringDeclarations;
87349         /** Keeps track of property names accessed on super (`super.x`) within async functions. */
87350         var capturedSuperProperties;
87351         /** Whether the async function contains an element access on super (`super[x]`). */
87352         var hasSuperElementAccess;
87353         /** A set of node IDs for generated super accessors. */
87354         var substitutedSuperAccessors = [];
87355         return ts.chainBundle(context, transformSourceFile);
87356         function affectsSubtree(excludeFacts, includeFacts) {
87357             return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts);
87358         }
87359         /**
87360          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
87361          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
87362          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
87363          */
87364         function enterSubtree(excludeFacts, includeFacts) {
87365             var ancestorFacts = hierarchyFacts;
87366             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */;
87367             return ancestorFacts;
87368         }
87369         /**
87370          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
87371          * subtree.
87372          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
87373          */
87374         function exitSubtree(ancestorFacts) {
87375             hierarchyFacts = ancestorFacts;
87376         }
87377         function recordTaggedTemplateString(temp) {
87378             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, factory.createVariableDeclaration(temp));
87379         }
87380         function transformSourceFile(node) {
87381             if (node.isDeclarationFile) {
87382                 return node;
87383             }
87384             currentSourceFile = node;
87385             var visited = visitSourceFile(node);
87386             ts.addEmitHelpers(visited, context.readEmitHelpers());
87387             currentSourceFile = undefined;
87388             taggedTemplateStringDeclarations = undefined;
87389             return visited;
87390         }
87391         function visitor(node) {
87392             return visitorWorker(node, /*expressionResultIsUnused*/ false);
87393         }
87394         function visitorWithUnusedExpressionResult(node) {
87395             return visitorWorker(node, /*expressionResultIsUnused*/ true);
87396         }
87397         function visitorNoAsyncModifier(node) {
87398             if (node.kind === 129 /* AsyncKeyword */) {
87399                 return undefined;
87400             }
87401             return node;
87402         }
87403         function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) {
87404             if (affectsSubtree(excludeFacts, includeFacts)) {
87405                 var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
87406                 var result = cb(value);
87407                 exitSubtree(ancestorFacts);
87408                 return result;
87409             }
87410             return cb(value);
87411         }
87412         function visitDefault(node) {
87413             return ts.visitEachChild(node, visitor, context);
87414         }
87415         /**
87416          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
87417          * expression of an `ExpressionStatement`).
87418          */
87419         function visitorWorker(node, expressionResultIsUnused) {
87420             if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) {
87421                 return node;
87422             }
87423             switch (node.kind) {
87424                 case 213 /* AwaitExpression */:
87425                     return visitAwaitExpression(node);
87426                 case 219 /* YieldExpression */:
87427                     return visitYieldExpression(node);
87428                 case 242 /* ReturnStatement */:
87429                     return visitReturnStatement(node);
87430                 case 245 /* LabeledStatement */:
87431                     return visitLabeledStatement(node);
87432                 case 200 /* ObjectLiteralExpression */:
87433                     return visitObjectLiteralExpression(node);
87434                 case 216 /* BinaryExpression */:
87435                     return visitBinaryExpression(node, expressionResultIsUnused);
87436                 case 337 /* CommaListExpression */:
87437                     return visitCommaListExpression(node, expressionResultIsUnused);
87438                 case 287 /* CatchClause */:
87439                     return visitCatchClause(node);
87440                 case 232 /* VariableStatement */:
87441                     return visitVariableStatement(node);
87442                 case 249 /* VariableDeclaration */:
87443                     return visitVariableDeclaration(node);
87444                 case 235 /* DoStatement */:
87445                 case 236 /* WhileStatement */:
87446                 case 238 /* ForInStatement */:
87447                     return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
87448                 case 239 /* ForOfStatement */:
87449                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
87450                 case 237 /* ForStatement */:
87451                     return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
87452                 case 212 /* VoidExpression */:
87453                     return visitVoidExpression(node);
87454                 case 166 /* Constructor */:
87455                     return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
87456                 case 165 /* MethodDeclaration */:
87457                     return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
87458                 case 167 /* GetAccessor */:
87459                     return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
87460                 case 168 /* SetAccessor */:
87461                     return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
87462                 case 251 /* FunctionDeclaration */:
87463                     return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
87464                 case 208 /* FunctionExpression */:
87465                     return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
87466                 case 209 /* ArrowFunction */:
87467                     return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */);
87468                 case 160 /* Parameter */:
87469                     return visitParameter(node);
87470                 case 233 /* ExpressionStatement */:
87471                     return visitExpressionStatement(node);
87472                 case 207 /* ParenthesizedExpression */:
87473                     return visitParenthesizedExpression(node, expressionResultIsUnused);
87474                 case 205 /* TaggedTemplateExpression */:
87475                     return visitTaggedTemplateExpression(node);
87476                 case 201 /* PropertyAccessExpression */:
87477                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) {
87478                         capturedSuperProperties.add(node.name.escapedText);
87479                     }
87480                     return ts.visitEachChild(node, visitor, context);
87481                 case 202 /* ElementAccessExpression */:
87482                     if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) {
87483                         hasSuperElementAccess = true;
87484                     }
87485                     return ts.visitEachChild(node, visitor, context);
87486                 case 252 /* ClassDeclaration */:
87487                 case 221 /* ClassExpression */:
87488                     return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
87489                 default:
87490                     return ts.visitEachChild(node, visitor, context);
87491             }
87492         }
87493         function visitAwaitExpression(node) {
87494             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
87495                 return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(/*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(ts.visitNode(node.expression, visitor, ts.isExpression))), 
87496                 /*location*/ node), node);
87497             }
87498             return ts.visitEachChild(node, visitor, context);
87499         }
87500         function visitYieldExpression(node) {
87501             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
87502                 if (node.asteriskToken) {
87503                     var expression = ts.visitNode(ts.Debug.assertDefined(node.expression), visitor, ts.isExpression);
87504                     return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(
87505                     /*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(factory.updateYieldExpression(node, node.asteriskToken, ts.setTextRange(emitHelpers().createAsyncDelegatorHelper(ts.setTextRange(emitHelpers().createAsyncValuesHelper(expression), expression)), expression)))), node), node);
87506                 }
87507                 return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(
87508                 /*asteriskToken*/ undefined, createDownlevelAwait(node.expression
87509                     ? ts.visitNode(node.expression, visitor, ts.isExpression)
87510                     : factory.createVoidZero())), node), node);
87511             }
87512             return ts.visitEachChild(node, visitor, context);
87513         }
87514         function visitReturnStatement(node) {
87515             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
87516                 return factory.updateReturnStatement(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : factory.createVoidZero()));
87517             }
87518             return ts.visitEachChild(node, visitor, context);
87519         }
87520         function visitLabeledStatement(node) {
87521             if (enclosingFunctionFlags & 2 /* Async */) {
87522                 var statement = ts.unwrapInnermostStatementOfLabel(node);
87523                 if (statement.kind === 239 /* ForOfStatement */ && statement.awaitModifier) {
87524                     return visitForOfStatement(statement, node);
87525                 }
87526                 return factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node);
87527             }
87528             return ts.visitEachChild(node, visitor, context);
87529         }
87530         function chunkObjectLiteralElements(elements) {
87531             var chunkObject;
87532             var objects = [];
87533             for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
87534                 var e = elements_4[_i];
87535                 if (e.kind === 290 /* SpreadAssignment */) {
87536                     if (chunkObject) {
87537                         objects.push(factory.createObjectLiteralExpression(chunkObject));
87538                         chunkObject = undefined;
87539                     }
87540                     var target = e.expression;
87541                     objects.push(ts.visitNode(target, visitor, ts.isExpression));
87542                 }
87543                 else {
87544                     chunkObject = ts.append(chunkObject, e.kind === 288 /* PropertyAssignment */
87545                         ? factory.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression))
87546                         : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike));
87547                 }
87548             }
87549             if (chunkObject) {
87550                 objects.push(factory.createObjectLiteralExpression(chunkObject));
87551             }
87552             return objects;
87553         }
87554         function visitObjectLiteralExpression(node) {
87555             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
87556                 // spread elements emit like so:
87557                 // non-spread elements are chunked together into object literals, and then all are passed to __assign:
87558                 //     { a, ...o, b } => __assign(__assign({a}, o), {b});
87559                 // If the first element is a spread element, then the first argument to __assign is {}:
87560                 //     { ...o, a, b, ...o2 } => __assign(__assign(__assign({}, o), {a, b}), o2)
87561                 //
87562                 // We cannot call __assign with more than two elements, since any element could cause side effects. For
87563                 // example:
87564                 //      var k = { a: 1, b: 2 };
87565                 //      var o = { a: 3, ...k, b: k.a++ };
87566                 //      // expected: { a: 1, b: 1 }
87567                 // If we translate the above to `__assign({ a: 3 }, k, { b: k.a++ })`, the `k.a++` will evaluate before
87568                 // `k` is spread and we end up with `{ a: 2, b: 1 }`.
87569                 //
87570                 // This also occurs for spread elements, not just property assignments:
87571                 //      var k = { a: 1, get b() { l = { z: 9 }; return 2; } };
87572                 //      var l = { c: 3 };
87573                 //      var o = { ...k, ...l };
87574                 //      // expected: { a: 1, b: 2, z: 9 }
87575                 // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we
87576                 // end up with `{ a: 1, b: 2, c: 3 }`
87577                 var objects = chunkObjectLiteralElements(node.properties);
87578                 if (objects.length && objects[0].kind !== 200 /* ObjectLiteralExpression */) {
87579                     objects.unshift(factory.createObjectLiteralExpression());
87580                 }
87581                 var expression = objects[0];
87582                 if (objects.length > 1) {
87583                     for (var i = 1; i < objects.length; i++) {
87584                         expression = emitHelpers().createAssignHelper([expression, objects[i]]);
87585                     }
87586                     return expression;
87587                 }
87588                 else {
87589                     return emitHelpers().createAssignHelper(objects);
87590                 }
87591             }
87592             return ts.visitEachChild(node, visitor, context);
87593         }
87594         function visitExpressionStatement(node) {
87595             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
87596         }
87597         /**
87598          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
87599          * expression of an `ExpressionStatement`).
87600          */
87601         function visitParenthesizedExpression(node, expressionResultIsUnused) {
87602             return ts.visitEachChild(node, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, context);
87603         }
87604         function visitSourceFile(node) {
87605             var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ?
87606                 0 /* StrictModeSourceFileIncludes */ :
87607                 1 /* SourceFileIncludes */);
87608             exportedVariableStatement = false;
87609             var visited = ts.visitEachChild(node, visitor, context);
87610             var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [
87611                 factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList(taggedTemplateStringDeclarations))
87612             ]);
87613             var result = factory.updateSourceFile(visited, ts.setTextRange(factory.createNodeArray(statement), node.statements));
87614             exitSubtree(ancestorFacts);
87615             return result;
87616         }
87617         function visitTaggedTemplateExpression(node) {
87618             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction);
87619         }
87620         /**
87621          * Visits a BinaryExpression that contains a destructuring assignment.
87622          *
87623          * @param node A BinaryExpression node.
87624          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
87625          * expression of an `ExpressionStatement`).
87626          */
87627         function visitBinaryExpression(node, expressionResultIsUnused) {
87628             if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
87629                 return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !expressionResultIsUnused);
87630             }
87631             if (node.operatorToken.kind === 27 /* CommaToken */) {
87632                 return factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorWithUnusedExpressionResult, ts.isExpression), node.operatorToken, ts.visitNode(node.right, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, ts.isExpression));
87633             }
87634             return ts.visitEachChild(node, visitor, context);
87635         }
87636         /**
87637          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
87638          * expression of an `ExpressionStatement`).
87639          */
87640         function visitCommaListExpression(node, expressionResultIsUnused) {
87641             if (expressionResultIsUnused) {
87642                 return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
87643             }
87644             var result;
87645             for (var i = 0; i < node.elements.length; i++) {
87646                 var element = node.elements[i];
87647                 var visited = ts.visitNode(element, i < node.elements.length - 1 ? visitorWithUnusedExpressionResult : visitor, ts.isExpression);
87648                 if (result || visited !== element) {
87649                     result || (result = node.elements.slice(0, i));
87650                     result.push(visited);
87651                 }
87652             }
87653             var elements = result ? ts.setTextRange(factory.createNodeArray(result), node.elements) : node.elements;
87654             return factory.updateCommaListExpression(node, elements);
87655         }
87656         function visitCatchClause(node) {
87657             if (node.variableDeclaration &&
87658                 ts.isBindingPattern(node.variableDeclaration.name) &&
87659                 node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
87660                 var name = factory.getGeneratedNameForNode(node.variableDeclaration.name);
87661                 var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name);
87662                 var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */);
87663                 var block = ts.visitNode(node.block, visitor, ts.isBlock);
87664                 if (ts.some(visitedBindings)) {
87665                     block = factory.updateBlock(block, __spreadArray([
87666                         factory.createVariableStatement(/*modifiers*/ undefined, visitedBindings)
87667                     ], block.statements));
87668                 }
87669                 return factory.updateCatchClause(node, factory.updateVariableDeclaration(node.variableDeclaration, name, /*exclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined), block);
87670             }
87671             return ts.visitEachChild(node, visitor, context);
87672         }
87673         function visitVariableStatement(node) {
87674             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
87675                 var savedExportedVariableStatement = exportedVariableStatement;
87676                 exportedVariableStatement = true;
87677                 var visited = ts.visitEachChild(node, visitor, context);
87678                 exportedVariableStatement = savedExportedVariableStatement;
87679                 return visited;
87680             }
87681             return ts.visitEachChild(node, visitor, context);
87682         }
87683         /**
87684          * Visits a VariableDeclaration node with a binding pattern.
87685          *
87686          * @param node A VariableDeclaration node.
87687          */
87688         function visitVariableDeclaration(node) {
87689             if (exportedVariableStatement) {
87690                 var savedExportedVariableStatement = exportedVariableStatement;
87691                 exportedVariableStatement = false;
87692                 var visited = visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ true);
87693                 exportedVariableStatement = savedExportedVariableStatement;
87694                 return visited;
87695             }
87696             return visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ false);
87697         }
87698         function visitVariableDeclarationWorker(node, exportedVariableStatement) {
87699             // If we are here it is because the name contains a binding pattern with a rest somewhere in it.
87700             if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
87701                 return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, 
87702                 /*rval*/ undefined, exportedVariableStatement);
87703             }
87704             return ts.visitEachChild(node, visitor, context);
87705         }
87706         function visitForStatement(node) {
87707             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));
87708         }
87709         function visitVoidExpression(node) {
87710             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
87711         }
87712         /**
87713          * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
87714          *
87715          * @param node A ForOfStatement.
87716          */
87717         function visitForOfStatement(node, outermostLabeledStatement) {
87718             var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
87719             if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
87720                 node = transformForOfStatementWithObjectRest(node);
87721             }
87722             var result = node.awaitModifier ?
87723                 transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) :
87724                 factory.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement);
87725             exitSubtree(ancestorFacts);
87726             return result;
87727         }
87728         function transformForOfStatementWithObjectRest(node) {
87729             var initializerWithoutParens = ts.skipParentheses(node.initializer);
87730             if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) {
87731                 var bodyLocation = void 0;
87732                 var statementsLocation = void 0;
87733                 var temp = factory.createTempVariable(/*recordTempVariable*/ undefined);
87734                 var statements = [ts.createForOfBindingStatement(factory, initializerWithoutParens, temp)];
87735                 if (ts.isBlock(node.statement)) {
87736                     ts.addRange(statements, node.statement.statements);
87737                     bodyLocation = node.statement;
87738                     statementsLocation = node.statement.statements;
87739                 }
87740                 else if (node.statement) {
87741                     ts.append(statements, node.statement);
87742                     bodyLocation = node.statement;
87743                     statementsLocation = node.statement;
87744                 }
87745                 return factory.updateForOfStatement(node, node.awaitModifier, ts.setTextRange(factory.createVariableDeclarationList([
87746                     ts.setTextRange(factory.createVariableDeclaration(temp), node.initializer)
87747                 ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), 
87748                 /*multiLine*/ true), bodyLocation));
87749             }
87750             return node;
87751         }
87752         function convertForOfStatementHead(node, boundValue) {
87753             var binding = ts.createForOfBindingStatement(factory, node.initializer, boundValue);
87754             var bodyLocation;
87755             var statementsLocation;
87756             var statements = [ts.visitNode(binding, visitor, ts.isStatement)];
87757             var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
87758             if (ts.isBlock(statement)) {
87759                 ts.addRange(statements, statement.statements);
87760                 bodyLocation = statement;
87761                 statementsLocation = statement.statements;
87762             }
87763             else {
87764                 statements.push(statement);
87765             }
87766             return ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), 
87767             /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
87768         }
87769         function createDownlevelAwait(expression) {
87770             return enclosingFunctionFlags & 1 /* Generator */
87771                 ? factory.createYieldExpression(/*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(expression))
87772                 : factory.createAwaitExpression(expression);
87773         }
87774         function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) {
87775             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
87776             var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
87777             var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined);
87778             var errorRecord = factory.createUniqueName("e");
87779             var catchVariable = factory.getGeneratedNameForNode(errorRecord);
87780             var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined);
87781             var callValues = ts.setTextRange(emitHelpers().createAsyncValuesHelper(expression), node.expression);
87782             var callNext = factory.createCallExpression(factory.createPropertyAccessExpression(iterator, "next"), /*typeArguments*/ undefined, []);
87783             var getDone = factory.createPropertyAccessExpression(result, "done");
87784             var getValue = factory.createPropertyAccessExpression(result, "value");
87785             var callReturn = factory.createFunctionCallCall(returnMethod, iterator, []);
87786             hoistVariableDeclaration(errorRecord);
87787             hoistVariableDeclaration(returnMethod);
87788             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
87789             var initializer = ancestorFacts & 2 /* IterationContainer */ ?
87790                 factory.inlineExpressions([factory.createAssignment(errorRecord, factory.createVoidZero()), callValues]) :
87791                 callValues;
87792             var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement(
87793             /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([
87794                 ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression),
87795                 factory.createVariableDeclaration(result)
87796             ]), node.expression), 2097152 /* NoHoisting */), 
87797             /*condition*/ factory.createComma(factory.createAssignment(result, createDownlevelAwait(callNext)), factory.createLogicalNot(getDone)), 
87798             /*incrementor*/ undefined, 
87799             /*statement*/ convertForOfStatementHead(node, getValue)), 
87800             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
87801             return factory.createTryStatement(factory.createBlock([
87802                 factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement)
87803             ]), factory.createCatchClause(factory.createVariableDeclaration(catchVariable), ts.setEmitFlags(factory.createBlock([
87804                 factory.createExpressionStatement(factory.createAssignment(errorRecord, factory.createObjectLiteralExpression([
87805                     factory.createPropertyAssignment("error", catchVariable)
87806                 ])))
87807             ]), 1 /* SingleLine */)), factory.createBlock([
87808                 factory.createTryStatement(
87809                 /*tryBlock*/ factory.createBlock([
87810                     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 */)
87811                 ]), 
87812                 /*catchClause*/ undefined, 
87813                 /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([
87814                     ts.setEmitFlags(factory.createIfStatement(errorRecord, factory.createThrowStatement(factory.createPropertyAccessExpression(errorRecord, "error"))), 1 /* SingleLine */)
87815                 ]), 1 /* SingleLine */))
87816             ]));
87817         }
87818         function visitParameter(node) {
87819             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
87820                 // Binding patterns are converted into a generated name and are
87821                 // evaluated inside the function body.
87822                 return factory.updateParameterDeclaration(node, 
87823                 /*decorators*/ undefined, 
87824                 /*modifiers*/ undefined, node.dotDotDotToken, factory.getGeneratedNameForNode(node), 
87825                 /*questionToken*/ undefined, 
87826                 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
87827             }
87828             return ts.visitEachChild(node, visitor, context);
87829         }
87830         function visitConstructorDeclaration(node) {
87831             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
87832             enclosingFunctionFlags = 0 /* Normal */;
87833             var updated = factory.updateConstructorDeclaration(node, 
87834             /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
87835             enclosingFunctionFlags = savedEnclosingFunctionFlags;
87836             return updated;
87837         }
87838         function visitGetAccessorDeclaration(node) {
87839             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
87840             enclosingFunctionFlags = 0 /* Normal */;
87841             var updated = factory.updateGetAccessorDeclaration(node, 
87842             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), 
87843             /*type*/ undefined, transformFunctionBody(node));
87844             enclosingFunctionFlags = savedEnclosingFunctionFlags;
87845             return updated;
87846         }
87847         function visitSetAccessorDeclaration(node) {
87848             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
87849             enclosingFunctionFlags = 0 /* Normal */;
87850             var updated = factory.updateSetAccessorDeclaration(node, 
87851             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
87852             enclosingFunctionFlags = savedEnclosingFunctionFlags;
87853             return updated;
87854         }
87855         function visitMethodDeclaration(node) {
87856             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
87857             enclosingFunctionFlags = ts.getFunctionFlags(node);
87858             var updated = factory.updateMethodDeclaration(node, 
87859             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
87860                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
87861                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
87862                 ? undefined
87863                 : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), 
87864             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
87865             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
87866                 ? transformAsyncGeneratorFunctionBody(node)
87867                 : transformFunctionBody(node));
87868             enclosingFunctionFlags = savedEnclosingFunctionFlags;
87869             return updated;
87870         }
87871         function visitFunctionDeclaration(node) {
87872             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
87873             enclosingFunctionFlags = ts.getFunctionFlags(node);
87874             var updated = factory.updateFunctionDeclaration(node, 
87875             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
87876                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
87877                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
87878                 ? undefined
87879                 : node.asteriskToken, node.name, 
87880             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
87881             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
87882                 ? transformAsyncGeneratorFunctionBody(node)
87883                 : transformFunctionBody(node));
87884             enclosingFunctionFlags = savedEnclosingFunctionFlags;
87885             return updated;
87886         }
87887         function visitArrowFunction(node) {
87888             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
87889             enclosingFunctionFlags = ts.getFunctionFlags(node);
87890             var updated = factory.updateArrowFunction(node, node.modifiers, 
87891             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
87892             /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node));
87893             enclosingFunctionFlags = savedEnclosingFunctionFlags;
87894             return updated;
87895         }
87896         function visitFunctionExpression(node) {
87897             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
87898             enclosingFunctionFlags = ts.getFunctionFlags(node);
87899             var updated = factory.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */
87900                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
87901                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
87902                 ? undefined
87903                 : node.asteriskToken, node.name, 
87904             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
87905             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
87906                 ? transformAsyncGeneratorFunctionBody(node)
87907                 : transformFunctionBody(node));
87908             enclosingFunctionFlags = savedEnclosingFunctionFlags;
87909             return updated;
87910         }
87911         function transformAsyncGeneratorFunctionBody(node) {
87912             resumeLexicalEnvironment();
87913             var statements = [];
87914             var statementOffset = factory.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ false, visitor);
87915             appendObjectRestAssignmentsIfNeeded(statements, node);
87916             var savedCapturedSuperProperties = capturedSuperProperties;
87917             var savedHasSuperElementAccess = hasSuperElementAccess;
87918             capturedSuperProperties = new ts.Set();
87919             hasSuperElementAccess = false;
87920             var returnStatement = factory.createReturnStatement(emitHelpers().createAsyncGeneratorHelper(factory.createFunctionExpression(
87921             /*modifiers*/ undefined, factory.createToken(41 /* AsteriskToken */), node.name && factory.getGeneratedNameForNode(node.name), 
87922             /*typeParameters*/ undefined, 
87923             /*parameters*/ [], 
87924             /*type*/ undefined, factory.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */)));
87925             // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
87926             // This step isn't needed if we eventually transform this to ES5.
87927             var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
87928             if (emitSuperHelpers) {
87929                 enableSubstitutionForAsyncMethodsWithSuper();
87930                 var variableStatement = ts.createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties);
87931                 substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
87932                 ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
87933             }
87934             statements.push(returnStatement);
87935             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
87936             var block = factory.updateBlock(node.body, statements);
87937             if (emitSuperHelpers && hasSuperElementAccess) {
87938                 if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
87939                     ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
87940                 }
87941                 else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
87942                     ts.addEmitHelper(block, ts.asyncSuperHelper);
87943                 }
87944             }
87945             capturedSuperProperties = savedCapturedSuperProperties;
87946             hasSuperElementAccess = savedHasSuperElementAccess;
87947             return block;
87948         }
87949         function transformFunctionBody(node) {
87950             var _a;
87951             resumeLexicalEnvironment();
87952             var statementOffset = 0;
87953             var statements = [];
87954             var body = (_a = ts.visitNode(node.body, visitor, ts.isConciseBody)) !== null && _a !== void 0 ? _a : factory.createBlock([]);
87955             if (ts.isBlock(body)) {
87956                 statementOffset = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor);
87957             }
87958             ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
87959             var leadingStatements = endLexicalEnvironment();
87960             if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
87961                 var block = factory.converters.convertToFunctionBlock(body, /*multiLine*/ true);
87962                 ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
87963                 ts.addRange(statements, block.statements.slice(statementOffset));
87964                 return factory.updateBlock(block, ts.setTextRange(factory.createNodeArray(statements), block.statements));
87965             }
87966             return body;
87967         }
87968         function appendObjectRestAssignmentsIfNeeded(statements, node) {
87969             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
87970                 var parameter = _a[_i];
87971                 if (parameter.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
87972                     var temp = factory.getGeneratedNameForNode(parameter);
87973                     var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, 
87974                     /*doNotRecordTempVariablesInLine*/ false, 
87975                     /*skipInitializer*/ true);
87976                     if (ts.some(declarations)) {
87977                         var statement = factory.createVariableStatement(
87978                         /*modifiers*/ undefined, factory.createVariableDeclarationList(declarations));
87979                         ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
87980                         statements = ts.append(statements, statement);
87981                     }
87982                 }
87983             }
87984             return statements;
87985         }
87986         function enableSubstitutionForAsyncMethodsWithSuper() {
87987             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
87988                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
87989                 // We need to enable substitutions for call, property access, and element access
87990                 // if we need to rewrite super calls.
87991                 context.enableSubstitution(203 /* CallExpression */);
87992                 context.enableSubstitution(201 /* PropertyAccessExpression */);
87993                 context.enableSubstitution(202 /* ElementAccessExpression */);
87994                 // We need to be notified when entering and exiting declarations that bind super.
87995                 context.enableEmitNotification(252 /* ClassDeclaration */);
87996                 context.enableEmitNotification(165 /* MethodDeclaration */);
87997                 context.enableEmitNotification(167 /* GetAccessor */);
87998                 context.enableEmitNotification(168 /* SetAccessor */);
87999                 context.enableEmitNotification(166 /* Constructor */);
88000                 // We need to be notified when entering the generated accessor arrow functions.
88001                 context.enableEmitNotification(232 /* VariableStatement */);
88002             }
88003         }
88004         /**
88005          * Called by the printer just before a node is printed.
88006          *
88007          * @param hint A hint as to the intended usage of the node.
88008          * @param node The node to be printed.
88009          * @param emitCallback The callback used to emit the node.
88010          */
88011         function onEmitNode(hint, node, emitCallback) {
88012             // If we need to support substitutions for `super` in an async method,
88013             // we should track it here.
88014             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
88015                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
88016                 if (superContainerFlags !== enclosingSuperContainerFlags) {
88017                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
88018                     enclosingSuperContainerFlags = superContainerFlags;
88019                     previousOnEmitNode(hint, node, emitCallback);
88020                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
88021                     return;
88022                 }
88023             }
88024             // Disable substitution in the generated super accessor itself.
88025             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
88026                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
88027                 enclosingSuperContainerFlags = 0;
88028                 previousOnEmitNode(hint, node, emitCallback);
88029                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
88030                 return;
88031             }
88032             previousOnEmitNode(hint, node, emitCallback);
88033         }
88034         /**
88035          * Hooks node substitutions.
88036          *
88037          * @param hint The context for the emitter.
88038          * @param node The node to substitute.
88039          */
88040         function onSubstituteNode(hint, node) {
88041             node = previousOnSubstituteNode(hint, node);
88042             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
88043                 return substituteExpression(node);
88044             }
88045             return node;
88046         }
88047         function substituteExpression(node) {
88048             switch (node.kind) {
88049                 case 201 /* PropertyAccessExpression */:
88050                     return substitutePropertyAccessExpression(node);
88051                 case 202 /* ElementAccessExpression */:
88052                     return substituteElementAccessExpression(node);
88053                 case 203 /* CallExpression */:
88054                     return substituteCallExpression(node);
88055             }
88056             return node;
88057         }
88058         function substitutePropertyAccessExpression(node) {
88059             if (node.expression.kind === 105 /* SuperKeyword */) {
88060                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), node.name), node);
88061             }
88062             return node;
88063         }
88064         function substituteElementAccessExpression(node) {
88065             if (node.expression.kind === 105 /* SuperKeyword */) {
88066                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
88067             }
88068             return node;
88069         }
88070         function substituteCallExpression(node) {
88071             var expression = node.expression;
88072             if (ts.isSuperProperty(expression)) {
88073                 var argumentExpression = ts.isPropertyAccessExpression(expression)
88074                     ? substitutePropertyAccessExpression(expression)
88075                     : substituteElementAccessExpression(expression);
88076                 return factory.createCallExpression(factory.createPropertyAccessExpression(argumentExpression, "call"), 
88077                 /*typeArguments*/ undefined, __spreadArray([
88078                     factory.createThis()
88079                 ], node.arguments));
88080             }
88081             return node;
88082         }
88083         function isSuperContainer(node) {
88084             var kind = node.kind;
88085             return kind === 252 /* ClassDeclaration */
88086                 || kind === 166 /* Constructor */
88087                 || kind === 165 /* MethodDeclaration */
88088                 || kind === 167 /* GetAccessor */
88089                 || kind === 168 /* SetAccessor */;
88090         }
88091         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
88092             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
88093                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createIdentifier("_superIndex"), 
88094                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
88095             }
88096             else {
88097                 return ts.setTextRange(factory.createCallExpression(factory.createIdentifier("_superIndex"), 
88098                 /*typeArguments*/ undefined, [argumentExpression]), location);
88099             }
88100         }
88101     }
88102     ts.transformES2018 = transformES2018;
88103 })(ts || (ts = {}));
88104 /*@internal*/
88105 var ts;
88106 (function (ts) {
88107     function transformES2019(context) {
88108         var factory = context.factory;
88109         return ts.chainBundle(context, transformSourceFile);
88110         function transformSourceFile(node) {
88111             if (node.isDeclarationFile) {
88112                 return node;
88113             }
88114             return ts.visitEachChild(node, visitor, context);
88115         }
88116         function visitor(node) {
88117             if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) {
88118                 return node;
88119             }
88120             switch (node.kind) {
88121                 case 287 /* CatchClause */:
88122                     return visitCatchClause(node);
88123                 default:
88124                     return ts.visitEachChild(node, visitor, context);
88125             }
88126         }
88127         function visitCatchClause(node) {
88128             if (!node.variableDeclaration) {
88129                 return factory.updateCatchClause(node, factory.createVariableDeclaration(factory.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
88130             }
88131             return ts.visitEachChild(node, visitor, context);
88132         }
88133     }
88134     ts.transformES2019 = transformES2019;
88135 })(ts || (ts = {}));
88136 /*@internal*/
88137 var ts;
88138 (function (ts) {
88139     function transformES2020(context) {
88140         var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration;
88141         return ts.chainBundle(context, transformSourceFile);
88142         function transformSourceFile(node) {
88143             if (node.isDeclarationFile) {
88144                 return node;
88145             }
88146             return ts.visitEachChild(node, visitor, context);
88147         }
88148         function visitor(node) {
88149             if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) {
88150                 return node;
88151             }
88152             switch (node.kind) {
88153                 case 201 /* PropertyAccessExpression */:
88154                 case 202 /* ElementAccessExpression */:
88155                 case 203 /* CallExpression */:
88156                     if (node.flags & 32 /* OptionalChain */) {
88157                         var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false);
88158                         ts.Debug.assertNotNode(updated, ts.isSyntheticReference);
88159                         return updated;
88160                     }
88161                     return ts.visitEachChild(node, visitor, context);
88162                 case 216 /* BinaryExpression */:
88163                     if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) {
88164                         return transformNullishCoalescingExpression(node);
88165                     }
88166                     return ts.visitEachChild(node, visitor, context);
88167                 case 210 /* DeleteExpression */:
88168                     return visitDeleteExpression(node);
88169                 default:
88170                     return ts.visitEachChild(node, visitor, context);
88171             }
88172         }
88173         function flattenChain(chain) {
88174             ts.Debug.assertNotNode(chain, ts.isNonNullChain);
88175             var links = [chain];
88176             while (!chain.questionDotToken && !ts.isTaggedTemplateExpression(chain)) {
88177                 chain = ts.cast(ts.skipPartiallyEmittedExpressions(chain.expression), ts.isOptionalChain);
88178                 ts.Debug.assertNotNode(chain, ts.isNonNullChain);
88179                 links.unshift(chain);
88180             }
88181             return { expression: chain.expression, chain: links };
88182         }
88183         function visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete) {
88184             var expression = visitNonOptionalExpression(node.expression, captureThisArg, isDelete);
88185             if (ts.isSyntheticReference(expression)) {
88186                 // `(a.b)` -> { expression `((_a = a).b)`, thisArg: `_a` }
88187                 // `(a[b])` -> { expression `((_a = a)[b])`, thisArg: `_a` }
88188                 return factory.createSyntheticReferenceExpression(factory.updateParenthesizedExpression(node, expression.expression), expression.thisArg);
88189             }
88190             return factory.updateParenthesizedExpression(node, expression);
88191         }
88192         function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete) {
88193             if (ts.isOptionalChain(node)) {
88194                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
88195                 return visitOptionalExpression(node, captureThisArg, isDelete);
88196             }
88197             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
88198             ts.Debug.assertNotNode(expression, ts.isSyntheticReference);
88199             var thisArg;
88200             if (captureThisArg) {
88201                 if (!ts.isSimpleCopiableExpression(expression)) {
88202                     thisArg = factory.createTempVariable(hoistVariableDeclaration);
88203                     expression = factory.createAssignment(thisArg, expression);
88204                 }
88205                 else {
88206                     thisArg = expression;
88207                 }
88208             }
88209             expression = node.kind === 201 /* PropertyAccessExpression */
88210                 ? factory.updatePropertyAccessExpression(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier))
88211                 : factory.updateElementAccessExpression(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
88212             return thisArg ? factory.createSyntheticReferenceExpression(expression, thisArg) : expression;
88213         }
88214         function visitNonOptionalCallExpression(node, captureThisArg) {
88215             if (ts.isOptionalChain(node)) {
88216                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
88217                 return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false);
88218             }
88219             return ts.visitEachChild(node, visitor, context);
88220         }
88221         function visitNonOptionalExpression(node, captureThisArg, isDelete) {
88222             switch (node.kind) {
88223                 case 207 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete);
88224                 case 201 /* PropertyAccessExpression */:
88225                 case 202 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete);
88226                 case 203 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg);
88227                 default: return ts.visitNode(node, visitor, ts.isExpression);
88228             }
88229         }
88230         function visitOptionalExpression(node, captureThisArg, isDelete) {
88231             var _a = flattenChain(node), expression = _a.expression, chain = _a.chain;
88232             var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0]), /*isDelete*/ false);
88233             var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined;
88234             var leftExpression = ts.isSyntheticReference(left) ? left.expression : left;
88235             var capturedLeft = leftExpression;
88236             if (!ts.isSimpleCopiableExpression(leftExpression)) {
88237                 capturedLeft = factory.createTempVariable(hoistVariableDeclaration);
88238                 leftExpression = factory.createAssignment(capturedLeft, leftExpression);
88239             }
88240             var rightExpression = capturedLeft;
88241             var thisArg;
88242             for (var i = 0; i < chain.length; i++) {
88243                 var segment = chain[i];
88244                 switch (segment.kind) {
88245                     case 201 /* PropertyAccessExpression */:
88246                     case 202 /* ElementAccessExpression */:
88247                         if (i === chain.length - 1 && captureThisArg) {
88248                             if (!ts.isSimpleCopiableExpression(rightExpression)) {
88249                                 thisArg = factory.createTempVariable(hoistVariableDeclaration);
88250                                 rightExpression = factory.createAssignment(thisArg, rightExpression);
88251                             }
88252                             else {
88253                                 thisArg = rightExpression;
88254                             }
88255                         }
88256                         rightExpression = segment.kind === 201 /* PropertyAccessExpression */
88257                             ? factory.createPropertyAccessExpression(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier))
88258                             : factory.createElementAccessExpression(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression));
88259                         break;
88260                     case 203 /* CallExpression */:
88261                         if (i === 0 && leftThisArg) {
88262                             rightExpression = factory.createFunctionCallCall(rightExpression, leftThisArg.kind === 105 /* SuperKeyword */ ? factory.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
88263                         }
88264                         else {
88265                             rightExpression = factory.createCallExpression(rightExpression, 
88266                             /*typeArguments*/ undefined, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
88267                         }
88268                         break;
88269                 }
88270                 ts.setOriginalNode(rightExpression, segment);
88271             }
88272             var target = isDelete
88273                 ? factory.createConditionalExpression(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), /*questionToken*/ undefined, factory.createTrue(), /*colonToken*/ undefined, factory.createDeleteExpression(rightExpression))
88274                 : factory.createConditionalExpression(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), /*questionToken*/ undefined, factory.createVoidZero(), /*colonToken*/ undefined, rightExpression);
88275             ts.setTextRange(target, node);
88276             return thisArg ? factory.createSyntheticReferenceExpression(target, thisArg) : target;
88277         }
88278         function createNotNullCondition(left, right, invert) {
88279             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()));
88280         }
88281         function transformNullishCoalescingExpression(node) {
88282             var left = ts.visitNode(node.left, visitor, ts.isExpression);
88283             var right = left;
88284             if (!ts.isSimpleCopiableExpression(left)) {
88285                 right = factory.createTempVariable(hoistVariableDeclaration);
88286                 left = factory.createAssignment(right, left);
88287             }
88288             return ts.setTextRange(factory.createConditionalExpression(createNotNullCondition(left, right), 
88289             /*questionToken*/ undefined, right, 
88290             /*colonToken*/ undefined, ts.visitNode(node.right, visitor, ts.isExpression)), node);
88291         }
88292         function visitDeleteExpression(node) {
88293             return ts.isOptionalChain(ts.skipParentheses(node.expression))
88294                 ? ts.setOriginalNode(visitNonOptionalExpression(node.expression, /*captureThisArg*/ false, /*isDelete*/ true), node)
88295                 : factory.updateDeleteExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression));
88296         }
88297     }
88298     ts.transformES2020 = transformES2020;
88299 })(ts || (ts = {}));
88300 /*@internal*/
88301 var ts;
88302 (function (ts) {
88303     function transformESNext(context) {
88304         var hoistVariableDeclaration = context.hoistVariableDeclaration, factory = context.factory;
88305         return ts.chainBundle(context, transformSourceFile);
88306         function transformSourceFile(node) {
88307             if (node.isDeclarationFile) {
88308                 return node;
88309             }
88310             return ts.visitEachChild(node, visitor, context);
88311         }
88312         function visitor(node) {
88313             if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
88314                 return node;
88315             }
88316             switch (node.kind) {
88317                 case 216 /* BinaryExpression */:
88318                     var binaryExpression = node;
88319                     if (ts.isLogicalOrCoalescingAssignmentExpression(binaryExpression)) {
88320                         return transformLogicalAssignment(binaryExpression);
88321                     }
88322                 // falls through
88323                 default:
88324                     return ts.visitEachChild(node, visitor, context);
88325             }
88326         }
88327         function transformLogicalAssignment(binaryExpression) {
88328             var operator = binaryExpression.operatorToken;
88329             var nonAssignmentOperator = ts.getNonAssignmentOperatorForCompoundAssignment(operator.kind);
88330             var left = ts.skipParentheses(ts.visitNode(binaryExpression.left, visitor, ts.isLeftHandSideExpression));
88331             var assignmentTarget = left;
88332             var right = ts.skipParentheses(ts.visitNode(binaryExpression.right, visitor, ts.isExpression));
88333             if (ts.isAccessExpression(left)) {
88334                 var propertyAccessTargetSimpleCopiable = ts.isSimpleCopiableExpression(left.expression);
88335                 var propertyAccessTarget = propertyAccessTargetSimpleCopiable ? left.expression :
88336                     factory.createTempVariable(hoistVariableDeclaration);
88337                 var propertyAccessTargetAssignment = propertyAccessTargetSimpleCopiable ? left.expression : factory.createAssignment(propertyAccessTarget, left.expression);
88338                 if (ts.isPropertyAccessExpression(left)) {
88339                     assignmentTarget = factory.createPropertyAccessExpression(propertyAccessTarget, left.name);
88340                     left = factory.createPropertyAccessExpression(propertyAccessTargetAssignment, left.name);
88341                 }
88342                 else {
88343                     var elementAccessArgumentSimpleCopiable = ts.isSimpleCopiableExpression(left.argumentExpression);
88344                     var elementAccessArgument = elementAccessArgumentSimpleCopiable ? left.argumentExpression :
88345                         factory.createTempVariable(hoistVariableDeclaration);
88346                     assignmentTarget = factory.createElementAccessExpression(propertyAccessTarget, elementAccessArgument);
88347                     left = factory.createElementAccessExpression(propertyAccessTargetAssignment, elementAccessArgumentSimpleCopiable ? left.argumentExpression : factory.createAssignment(elementAccessArgument, left.argumentExpression));
88348                 }
88349             }
88350             return factory.createBinaryExpression(left, nonAssignmentOperator, factory.createParenthesizedExpression(factory.createAssignment(assignmentTarget, right)));
88351         }
88352     }
88353     ts.transformESNext = transformESNext;
88354 })(ts || (ts = {}));
88355 /*@internal*/
88356 var ts;
88357 (function (ts) {
88358     function transformJsx(context) {
88359         var factory = context.factory, emitHelpers = context.getEmitHelperFactory;
88360         var compilerOptions = context.getCompilerOptions();
88361         var currentSourceFile;
88362         var currentFileState;
88363         return ts.chainBundle(context, transformSourceFile);
88364         function getCurrentFileNameExpression() {
88365             if (currentFileState.filenameDeclaration) {
88366                 return currentFileState.filenameDeclaration.name;
88367             }
88368             var declaration = factory.createVariableDeclaration(factory.createUniqueName("_jsxFileName", 16 /* Optimistic */ | 32 /* FileLevel */), /*exclaimationToken*/ undefined, /*type*/ undefined, factory.createStringLiteral(currentSourceFile.fileName));
88369             currentFileState.filenameDeclaration = declaration;
88370             return currentFileState.filenameDeclaration.name;
88371         }
88372         function getJsxFactoryCalleePrimitive(childrenLength) {
88373             return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : childrenLength > 1 ? "jsxs" : "jsx";
88374         }
88375         function getJsxFactoryCallee(childrenLength) {
88376             var type = getJsxFactoryCalleePrimitive(childrenLength);
88377             return getImplicitImportForName(type);
88378         }
88379         function getImplicitJsxFragmentReference() {
88380             return getImplicitImportForName("Fragment");
88381         }
88382         function getImplicitImportForName(name) {
88383             var _a, _b;
88384             var importSource = name === "createElement"
88385                 ? currentFileState.importSpecifier
88386                 : ts.getJSXRuntimeImport(currentFileState.importSpecifier, compilerOptions);
88387             var existing = (_b = (_a = currentFileState.utilizedImplicitRuntimeImports) === null || _a === void 0 ? void 0 : _a.get(importSource)) === null || _b === void 0 ? void 0 : _b.get(name);
88388             if (existing) {
88389                 return existing.name;
88390             }
88391             if (!currentFileState.utilizedImplicitRuntimeImports) {
88392                 currentFileState.utilizedImplicitRuntimeImports = ts.createMap();
88393             }
88394             var specifierSourceImports = currentFileState.utilizedImplicitRuntimeImports.get(importSource);
88395             if (!specifierSourceImports) {
88396                 specifierSourceImports = ts.createMap();
88397                 currentFileState.utilizedImplicitRuntimeImports.set(importSource, specifierSourceImports);
88398             }
88399             var generatedName = factory.createUniqueName("_" + name, 16 /* Optimistic */ | 32 /* FileLevel */ | 64 /* AllowNameSubstitution */);
88400             var specifier = factory.createImportSpecifier(factory.createIdentifier(name), generatedName);
88401             generatedName.generatedImportReference = specifier;
88402             specifierSourceImports.set(name, specifier);
88403             return generatedName;
88404         }
88405         /**
88406          * Transform JSX-specific syntax in a SourceFile.
88407          *
88408          * @param node A SourceFile node.
88409          */
88410         function transformSourceFile(node) {
88411             if (node.isDeclarationFile) {
88412                 return node;
88413             }
88414             currentSourceFile = node;
88415             currentFileState = {};
88416             currentFileState.importSpecifier = ts.getJSXImplicitImportBase(compilerOptions, node);
88417             var visited = ts.visitEachChild(node, visitor, context);
88418             ts.addEmitHelpers(visited, context.readEmitHelpers());
88419             var statements = visited.statements;
88420             if (currentFileState.filenameDeclaration) {
88421                 statements = ts.insertStatementAfterCustomPrologue(statements.slice(), factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([currentFileState.filenameDeclaration], 2 /* Const */)));
88422             }
88423             if (currentFileState.utilizedImplicitRuntimeImports) {
88424                 for (var _i = 0, _a = ts.arrayFrom(currentFileState.utilizedImplicitRuntimeImports.entries()); _i < _a.length; _i++) {
88425                     var _b = _a[_i], importSource = _b[0], importSpecifiersMap = _b[1];
88426                     if (ts.isExternalModule(node)) {
88427                         // Add `import` statement
88428                         var importStatement = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource));
88429                         ts.setParentRecursive(importStatement, /*incremental*/ false);
88430                         statements = ts.insertStatementAfterCustomPrologue(statements.slice(), importStatement);
88431                     }
88432                     else if (ts.isExternalOrCommonJsModule(node)) {
88433                         // Add `require` statement
88434                         var requireStatement = factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([
88435                             factory.createVariableDeclaration(factory.createObjectBindingPattern(ts.map(ts.arrayFrom(importSpecifiersMap.values()), function (s) { return factory.createBindingElement(/*dotdotdot*/ undefined, s.propertyName, s.name); })), 
88436                             /*exclaimationToken*/ undefined, 
88437                             /*type*/ undefined, factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, [factory.createStringLiteral(importSource)]))
88438                         ], 2 /* Const */));
88439                         ts.setParentRecursive(requireStatement, /*incremental*/ false);
88440                         statements = ts.insertStatementAfterCustomPrologue(statements.slice(), requireStatement);
88441                     }
88442                     else {
88443                         // Do nothing (script file) - consider an error in the checker?
88444                     }
88445                 }
88446             }
88447             if (statements !== visited.statements) {
88448                 visited = factory.updateSourceFile(visited, statements);
88449             }
88450             currentFileState = undefined;
88451             return visited;
88452         }
88453         function visitor(node) {
88454             if (node.transformFlags & 2 /* ContainsJsx */) {
88455                 return visitorWorker(node);
88456             }
88457             else {
88458                 return node;
88459             }
88460         }
88461         function visitorWorker(node) {
88462             switch (node.kind) {
88463                 case 273 /* JsxElement */:
88464                     return visitJsxElement(node, /*isChild*/ false);
88465                 case 274 /* JsxSelfClosingElement */:
88466                     return visitJsxSelfClosingElement(node, /*isChild*/ false);
88467                 case 277 /* JsxFragment */:
88468                     return visitJsxFragment(node, /*isChild*/ false);
88469                 case 283 /* JsxExpression */:
88470                     return visitJsxExpression(node);
88471                 default:
88472                     return ts.visitEachChild(node, visitor, context);
88473             }
88474         }
88475         function transformJsxChildToExpression(node) {
88476             switch (node.kind) {
88477                 case 11 /* JsxText */:
88478                     return visitJsxText(node);
88479                 case 283 /* JsxExpression */:
88480                     return visitJsxExpression(node);
88481                 case 273 /* JsxElement */:
88482                     return visitJsxElement(node, /*isChild*/ true);
88483                 case 274 /* JsxSelfClosingElement */:
88484                     return visitJsxSelfClosingElement(node, /*isChild*/ true);
88485                 case 277 /* JsxFragment */:
88486                     return visitJsxFragment(node, /*isChild*/ true);
88487                 default:
88488                     return ts.Debug.failBadSyntaxKind(node);
88489             }
88490         }
88491         /**
88492          * The react jsx/jsxs transform falls back to `createElement` when an explicit `key` argument comes after a spread
88493          */
88494         function hasKeyAfterPropsSpread(node) {
88495             var spread = false;
88496             for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
88497                 var elem = _a[_i];
88498                 if (ts.isJsxSpreadAttribute(elem)) {
88499                     spread = true;
88500                 }
88501                 else if (spread && ts.isJsxAttribute(elem) && elem.name.escapedText === "key") {
88502                     return true;
88503                 }
88504             }
88505             return false;
88506         }
88507         function shouldUseCreateElement(node) {
88508             return currentFileState.importSpecifier === undefined || hasKeyAfterPropsSpread(node);
88509         }
88510         function visitJsxElement(node, isChild) {
88511             var tagTransform = shouldUseCreateElement(node.openingElement) ? visitJsxOpeningLikeElementCreateElement : visitJsxOpeningLikeElementJSX;
88512             return tagTransform(node.openingElement, node.children, isChild, /*location*/ node);
88513         }
88514         function visitJsxSelfClosingElement(node, isChild) {
88515             var tagTransform = shouldUseCreateElement(node) ? visitJsxOpeningLikeElementCreateElement : visitJsxOpeningLikeElementJSX;
88516             return tagTransform(node, /*children*/ undefined, isChild, /*location*/ node);
88517         }
88518         function visitJsxFragment(node, isChild) {
88519             var tagTransform = currentFileState.importSpecifier === undefined ? visitJsxOpeningFragmentCreateElement : visitJsxOpeningFragmentJSX;
88520             return tagTransform(node.openingFragment, node.children, isChild, /*location*/ node);
88521         }
88522         function convertJsxChildrenToChildrenPropObject(children) {
88523             var nonWhitespaceChildren = ts.getSemanticJsxChildren(children);
88524             if (ts.length(nonWhitespaceChildren) === 1) {
88525                 var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]);
88526                 return result_13 && factory.createObjectLiteralExpression([
88527                     factory.createPropertyAssignment("children", result_13)
88528                 ]);
88529             }
88530             var result = ts.mapDefined(children, transformJsxChildToExpression);
88531             return !result.length ? undefined : factory.createObjectLiteralExpression([
88532                 factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result))
88533             ]);
88534         }
88535         function visitJsxOpeningLikeElementJSX(node, children, isChild, location) {
88536             var tagName = getTagName(node);
88537             var objectProperties;
88538             var keyAttr = ts.find(node.attributes.properties, function (p) { return !!p.name && ts.isIdentifier(p.name) && p.name.escapedText === "key"; });
88539             var attrs = keyAttr ? ts.filter(node.attributes.properties, function (p) { return p !== keyAttr; }) : node.attributes.properties;
88540             var segments = [];
88541             if (attrs.length) {
88542                 // Map spans of JsxAttribute nodes into object literals and spans
88543                 // of JsxSpreadAttribute nodes into expressions.
88544                 segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
88545                     ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
88546                     : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
88547                 if (ts.isJsxSpreadAttribute(attrs[0])) {
88548                     // We must always emit at least one object literal before a spread
88549                     // argument.factory.createObjectLiteral
88550                     segments.unshift(factory.createObjectLiteralExpression());
88551                 }
88552             }
88553             if (children && children.length) {
88554                 var result = convertJsxChildrenToChildrenPropObject(children);
88555                 if (result) {
88556                     segments.push(result);
88557                 }
88558             }
88559             if (segments.length === 0) {
88560                 objectProperties = factory.createObjectLiteralExpression([]);
88561                 // When there are no attributes, React wants {}
88562             }
88563             else {
88564                 // Either emit one big object literal (no spread attribs), or
88565                 // a call to the __assign helper.
88566                 objectProperties = ts.singleOrUndefined(segments) || emitHelpers().createAssignHelper(segments);
88567             }
88568             return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, ts.length(ts.getSemanticJsxChildren(children || ts.emptyArray)), isChild, location);
88569         }
88570         function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, childrenLength, isChild, location) {
88571             var args = [tagName, objectProperties, !keyAttr ? factory.createVoidZero() : transformJsxAttributeInitializer(keyAttr.initializer)];
88572             if (compilerOptions.jsx === 5 /* ReactJSXDev */) {
88573                 var originalFile = ts.getOriginalNode(currentSourceFile);
88574                 if (originalFile && ts.isSourceFile(originalFile)) {
88575                     // isStaticChildren development flag
88576                     args.push(childrenLength > 1 ? factory.createTrue() : factory.createFalse());
88577                     // __source development flag
88578                     var lineCol = ts.getLineAndCharacterOfPosition(originalFile, location.pos);
88579                     args.push(factory.createObjectLiteralExpression([
88580                         factory.createPropertyAssignment("fileName", getCurrentFileNameExpression()),
88581                         factory.createPropertyAssignment("lineNumber", factory.createNumericLiteral(lineCol.line + 1)),
88582                         factory.createPropertyAssignment("columnNumber", factory.createNumericLiteral(lineCol.character + 1))
88583                     ]));
88584                     // __self development flag
88585                     args.push(factory.createThis());
88586                 }
88587             }
88588             var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(childrenLength), /*typeArguments*/ undefined, args), location);
88589             if (isChild) {
88590                 ts.startOnNewLine(element);
88591             }
88592             return element;
88593         }
88594         function visitJsxOpeningLikeElementCreateElement(node, children, isChild, location) {
88595             var tagName = getTagName(node);
88596             var objectProperties;
88597             var attrs = node.attributes.properties;
88598             if (attrs.length === 0) {
88599                 objectProperties = factory.createNull();
88600                 // When there are no attributes, React wants "null"
88601             }
88602             else {
88603                 // Map spans of JsxAttribute nodes into object literals and spans
88604                 // of JsxSpreadAttribute nodes into expressions.
88605                 var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
88606                     ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
88607                     : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
88608                 if (ts.isJsxSpreadAttribute(attrs[0])) {
88609                     // We must always emit at least one object literal before a spread
88610                     // argument.factory.createObjectLiteral
88611                     segments.unshift(factory.createObjectLiteralExpression());
88612                 }
88613                 // Either emit one big object literal (no spread attribs), or
88614                 // a call to the __assign helper.
88615                 objectProperties = ts.singleOrUndefined(segments);
88616                 if (!objectProperties) {
88617                     objectProperties = emitHelpers().createAssignHelper(segments);
88618                 }
88619             }
88620             var callee = currentFileState.importSpecifier === undefined
88621                 ? ts.createJsxFactoryExpression(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
88622                 node)
88623                 : getImplicitImportForName("createElement");
88624             var element = ts.createExpressionForJsxElement(factory, callee, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), location);
88625             if (isChild) {
88626                 ts.startOnNewLine(element);
88627             }
88628             return element;
88629         }
88630         function visitJsxOpeningFragmentJSX(_node, children, isChild, location) {
88631             var childrenProps;
88632             if (children && children.length) {
88633                 var result = convertJsxChildrenToChildrenPropObject(children);
88634                 if (result) {
88635                     childrenProps = result;
88636                 }
88637             }
88638             return visitJsxOpeningLikeElementOrFragmentJSX(getImplicitJsxFragmentReference(), childrenProps || factory.createObjectLiteralExpression([]), 
88639             /*keyAttr*/ undefined, ts.length(ts.getSemanticJsxChildren(children)), isChild, location);
88640         }
88641         function visitJsxOpeningFragmentCreateElement(node, children, isChild, location) {
88642             var element = ts.createExpressionForJsxFragment(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), context.getEmitResolver().getJsxFragmentFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
88643             ts.mapDefined(children, transformJsxChildToExpression), node, location);
88644             if (isChild) {
88645                 ts.startOnNewLine(element);
88646             }
88647             return element;
88648         }
88649         function transformJsxSpreadAttributeToExpression(node) {
88650             return ts.visitNode(node.expression, visitor, ts.isExpression);
88651         }
88652         function transformJsxAttributeToObjectLiteralElement(node) {
88653             var name = getAttributeName(node);
88654             var expression = transformJsxAttributeInitializer(node.initializer);
88655             return factory.createPropertyAssignment(name, expression);
88656         }
88657         function transformJsxAttributeInitializer(node) {
88658             if (node === undefined) {
88659                 return factory.createTrue();
88660             }
88661             else if (node.kind === 10 /* StringLiteral */) {
88662                 // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which
88663                 // Need to be escaped to be handled correctly in a normal string
88664                 var singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile);
88665                 var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote);
88666                 return ts.setTextRange(literal, node);
88667             }
88668             else if (node.kind === 283 /* JsxExpression */) {
88669                 if (node.expression === undefined) {
88670                     return factory.createTrue();
88671                 }
88672                 return ts.visitNode(node.expression, visitor, ts.isExpression);
88673             }
88674             else {
88675                 return ts.Debug.failBadSyntaxKind(node);
88676             }
88677         }
88678         function visitJsxText(node) {
88679             var fixed = fixupWhitespaceAndDecodeEntities(node.text);
88680             return fixed === undefined ? undefined : factory.createStringLiteral(fixed);
88681         }
88682         /**
88683          * JSX trims whitespace at the end and beginning of lines, except that the
88684          * start/end of a tag is considered a start/end of a line only if that line is
88685          * on the same line as the closing tag. See examples in
88686          * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
88687          * 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
88688          *
88689          * An equivalent algorithm would be:
88690          * - If there is only one line, return it.
88691          * - If there is only whitespace (but multiple lines), return `undefined`.
88692          * - Split the text into lines.
88693          * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines.
88694          * - Decode entities on each line (individually).
88695          * - Remove empty lines and join the rest with " ".
88696          */
88697         function fixupWhitespaceAndDecodeEntities(text) {
88698             var acc;
88699             // First non-whitespace character on this line.
88700             var firstNonWhitespace = 0;
88701             // Last non-whitespace character on this line.
88702             var lastNonWhitespace = -1;
88703             // These initial values are special because the first line is:
88704             // firstNonWhitespace = 0 to indicate that we want leading whitsepace,
88705             // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace.
88706             for (var i = 0; i < text.length; i++) {
88707                 var c = text.charCodeAt(i);
88708                 if (ts.isLineBreak(c)) {
88709                     // If we've seen any non-whitespace characters on this line, add the 'trim' of the line.
88710                     // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.)
88711                     if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
88712                         acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
88713                     }
88714                     // Reset firstNonWhitespace for the next line.
88715                     // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1.
88716                     firstNonWhitespace = -1;
88717                 }
88718                 else if (!ts.isWhiteSpaceSingleLine(c)) {
88719                     lastNonWhitespace = i;
88720                     if (firstNonWhitespace === -1) {
88721                         firstNonWhitespace = i;
88722                     }
88723                 }
88724             }
88725             return firstNonWhitespace !== -1
88726                 // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace.
88727                 ? addLineOfJsxText(acc, text.substr(firstNonWhitespace))
88728                 // Last line was all whitespace, so ignore it
88729                 : acc;
88730         }
88731         function addLineOfJsxText(acc, trimmedLine) {
88732             // We do not escape the string here as that is handled by the printer
88733             // when it emits the literal. We do, however, need to decode JSX entities.
88734             var decoded = decodeEntities(trimmedLine);
88735             return acc === undefined ? decoded : acc + " " + decoded;
88736         }
88737         /**
88738          * Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
88739          * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
88740          */
88741         function decodeEntities(text) {
88742             return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) {
88743                 if (decimal) {
88744                     return ts.utf16EncodeAsString(parseInt(decimal, 10));
88745                 }
88746                 else if (hex) {
88747                     return ts.utf16EncodeAsString(parseInt(hex, 16));
88748                 }
88749                 else {
88750                     var ch = entities.get(word);
88751                     // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
88752                     return ch ? ts.utf16EncodeAsString(ch) : match;
88753                 }
88754             });
88755         }
88756         /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
88757         function tryDecodeEntities(text) {
88758             var decoded = decodeEntities(text);
88759             return decoded === text ? undefined : decoded;
88760         }
88761         function getTagName(node) {
88762             if (node.kind === 273 /* JsxElement */) {
88763                 return getTagName(node.openingElement);
88764             }
88765             else {
88766                 var name = node.tagName;
88767                 if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) {
88768                     return factory.createStringLiteral(ts.idText(name));
88769                 }
88770                 else {
88771                     return ts.createExpressionFromEntityName(factory, name);
88772                 }
88773             }
88774         }
88775         /**
88776          * Emit an attribute name, which is quoted if it needs to be quoted. Because
88777          * these emit into an object literal property name, we don't need to be worried
88778          * about keywords, just non-identifier characters
88779          */
88780         function getAttributeName(node) {
88781             var name = node.name;
88782             var text = ts.idText(name);
88783             if (/^[A-Za-z_]\w*$/.test(text)) {
88784                 return name;
88785             }
88786             else {
88787                 return factory.createStringLiteral(text);
88788             }
88789         }
88790         function visitJsxExpression(node) {
88791             return ts.visitNode(node.expression, visitor, ts.isExpression);
88792         }
88793     }
88794     ts.transformJsx = transformJsx;
88795     var entities = new ts.Map(ts.getEntries({
88796         quot: 0x0022,
88797         amp: 0x0026,
88798         apos: 0x0027,
88799         lt: 0x003C,
88800         gt: 0x003E,
88801         nbsp: 0x00A0,
88802         iexcl: 0x00A1,
88803         cent: 0x00A2,
88804         pound: 0x00A3,
88805         curren: 0x00A4,
88806         yen: 0x00A5,
88807         brvbar: 0x00A6,
88808         sect: 0x00A7,
88809         uml: 0x00A8,
88810         copy: 0x00A9,
88811         ordf: 0x00AA,
88812         laquo: 0x00AB,
88813         not: 0x00AC,
88814         shy: 0x00AD,
88815         reg: 0x00AE,
88816         macr: 0x00AF,
88817         deg: 0x00B0,
88818         plusmn: 0x00B1,
88819         sup2: 0x00B2,
88820         sup3: 0x00B3,
88821         acute: 0x00B4,
88822         micro: 0x00B5,
88823         para: 0x00B6,
88824         middot: 0x00B7,
88825         cedil: 0x00B8,
88826         sup1: 0x00B9,
88827         ordm: 0x00BA,
88828         raquo: 0x00BB,
88829         frac14: 0x00BC,
88830         frac12: 0x00BD,
88831         frac34: 0x00BE,
88832         iquest: 0x00BF,
88833         Agrave: 0x00C0,
88834         Aacute: 0x00C1,
88835         Acirc: 0x00C2,
88836         Atilde: 0x00C3,
88837         Auml: 0x00C4,
88838         Aring: 0x00C5,
88839         AElig: 0x00C6,
88840         Ccedil: 0x00C7,
88841         Egrave: 0x00C8,
88842         Eacute: 0x00C9,
88843         Ecirc: 0x00CA,
88844         Euml: 0x00CB,
88845         Igrave: 0x00CC,
88846         Iacute: 0x00CD,
88847         Icirc: 0x00CE,
88848         Iuml: 0x00CF,
88849         ETH: 0x00D0,
88850         Ntilde: 0x00D1,
88851         Ograve: 0x00D2,
88852         Oacute: 0x00D3,
88853         Ocirc: 0x00D4,
88854         Otilde: 0x00D5,
88855         Ouml: 0x00D6,
88856         times: 0x00D7,
88857         Oslash: 0x00D8,
88858         Ugrave: 0x00D9,
88859         Uacute: 0x00DA,
88860         Ucirc: 0x00DB,
88861         Uuml: 0x00DC,
88862         Yacute: 0x00DD,
88863         THORN: 0x00DE,
88864         szlig: 0x00DF,
88865         agrave: 0x00E0,
88866         aacute: 0x00E1,
88867         acirc: 0x00E2,
88868         atilde: 0x00E3,
88869         auml: 0x00E4,
88870         aring: 0x00E5,
88871         aelig: 0x00E6,
88872         ccedil: 0x00E7,
88873         egrave: 0x00E8,
88874         eacute: 0x00E9,
88875         ecirc: 0x00EA,
88876         euml: 0x00EB,
88877         igrave: 0x00EC,
88878         iacute: 0x00ED,
88879         icirc: 0x00EE,
88880         iuml: 0x00EF,
88881         eth: 0x00F0,
88882         ntilde: 0x00F1,
88883         ograve: 0x00F2,
88884         oacute: 0x00F3,
88885         ocirc: 0x00F4,
88886         otilde: 0x00F5,
88887         ouml: 0x00F6,
88888         divide: 0x00F7,
88889         oslash: 0x00F8,
88890         ugrave: 0x00F9,
88891         uacute: 0x00FA,
88892         ucirc: 0x00FB,
88893         uuml: 0x00FC,
88894         yacute: 0x00FD,
88895         thorn: 0x00FE,
88896         yuml: 0x00FF,
88897         OElig: 0x0152,
88898         oelig: 0x0153,
88899         Scaron: 0x0160,
88900         scaron: 0x0161,
88901         Yuml: 0x0178,
88902         fnof: 0x0192,
88903         circ: 0x02C6,
88904         tilde: 0x02DC,
88905         Alpha: 0x0391,
88906         Beta: 0x0392,
88907         Gamma: 0x0393,
88908         Delta: 0x0394,
88909         Epsilon: 0x0395,
88910         Zeta: 0x0396,
88911         Eta: 0x0397,
88912         Theta: 0x0398,
88913         Iota: 0x0399,
88914         Kappa: 0x039A,
88915         Lambda: 0x039B,
88916         Mu: 0x039C,
88917         Nu: 0x039D,
88918         Xi: 0x039E,
88919         Omicron: 0x039F,
88920         Pi: 0x03A0,
88921         Rho: 0x03A1,
88922         Sigma: 0x03A3,
88923         Tau: 0x03A4,
88924         Upsilon: 0x03A5,
88925         Phi: 0x03A6,
88926         Chi: 0x03A7,
88927         Psi: 0x03A8,
88928         Omega: 0x03A9,
88929         alpha: 0x03B1,
88930         beta: 0x03B2,
88931         gamma: 0x03B3,
88932         delta: 0x03B4,
88933         epsilon: 0x03B5,
88934         zeta: 0x03B6,
88935         eta: 0x03B7,
88936         theta: 0x03B8,
88937         iota: 0x03B9,
88938         kappa: 0x03BA,
88939         lambda: 0x03BB,
88940         mu: 0x03BC,
88941         nu: 0x03BD,
88942         xi: 0x03BE,
88943         omicron: 0x03BF,
88944         pi: 0x03C0,
88945         rho: 0x03C1,
88946         sigmaf: 0x03C2,
88947         sigma: 0x03C3,
88948         tau: 0x03C4,
88949         upsilon: 0x03C5,
88950         phi: 0x03C6,
88951         chi: 0x03C7,
88952         psi: 0x03C8,
88953         omega: 0x03C9,
88954         thetasym: 0x03D1,
88955         upsih: 0x03D2,
88956         piv: 0x03D6,
88957         ensp: 0x2002,
88958         emsp: 0x2003,
88959         thinsp: 0x2009,
88960         zwnj: 0x200C,
88961         zwj: 0x200D,
88962         lrm: 0x200E,
88963         rlm: 0x200F,
88964         ndash: 0x2013,
88965         mdash: 0x2014,
88966         lsquo: 0x2018,
88967         rsquo: 0x2019,
88968         sbquo: 0x201A,
88969         ldquo: 0x201C,
88970         rdquo: 0x201D,
88971         bdquo: 0x201E,
88972         dagger: 0x2020,
88973         Dagger: 0x2021,
88974         bull: 0x2022,
88975         hellip: 0x2026,
88976         permil: 0x2030,
88977         prime: 0x2032,
88978         Prime: 0x2033,
88979         lsaquo: 0x2039,
88980         rsaquo: 0x203A,
88981         oline: 0x203E,
88982         frasl: 0x2044,
88983         euro: 0x20AC,
88984         image: 0x2111,
88985         weierp: 0x2118,
88986         real: 0x211C,
88987         trade: 0x2122,
88988         alefsym: 0x2135,
88989         larr: 0x2190,
88990         uarr: 0x2191,
88991         rarr: 0x2192,
88992         darr: 0x2193,
88993         harr: 0x2194,
88994         crarr: 0x21B5,
88995         lArr: 0x21D0,
88996         uArr: 0x21D1,
88997         rArr: 0x21D2,
88998         dArr: 0x21D3,
88999         hArr: 0x21D4,
89000         forall: 0x2200,
89001         part: 0x2202,
89002         exist: 0x2203,
89003         empty: 0x2205,
89004         nabla: 0x2207,
89005         isin: 0x2208,
89006         notin: 0x2209,
89007         ni: 0x220B,
89008         prod: 0x220F,
89009         sum: 0x2211,
89010         minus: 0x2212,
89011         lowast: 0x2217,
89012         radic: 0x221A,
89013         prop: 0x221D,
89014         infin: 0x221E,
89015         ang: 0x2220,
89016         and: 0x2227,
89017         or: 0x2228,
89018         cap: 0x2229,
89019         cup: 0x222A,
89020         int: 0x222B,
89021         there4: 0x2234,
89022         sim: 0x223C,
89023         cong: 0x2245,
89024         asymp: 0x2248,
89025         ne: 0x2260,
89026         equiv: 0x2261,
89027         le: 0x2264,
89028         ge: 0x2265,
89029         sub: 0x2282,
89030         sup: 0x2283,
89031         nsub: 0x2284,
89032         sube: 0x2286,
89033         supe: 0x2287,
89034         oplus: 0x2295,
89035         otimes: 0x2297,
89036         perp: 0x22A5,
89037         sdot: 0x22C5,
89038         lceil: 0x2308,
89039         rceil: 0x2309,
89040         lfloor: 0x230A,
89041         rfloor: 0x230B,
89042         lang: 0x2329,
89043         rang: 0x232A,
89044         loz: 0x25CA,
89045         spades: 0x2660,
89046         clubs: 0x2663,
89047         hearts: 0x2665,
89048         diams: 0x2666
89049     }));
89050 })(ts || (ts = {}));
89051 /*@internal*/
89052 var ts;
89053 (function (ts) {
89054     function transformES2016(context) {
89055         var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration;
89056         return ts.chainBundle(context, transformSourceFile);
89057         function transformSourceFile(node) {
89058             if (node.isDeclarationFile) {
89059                 return node;
89060             }
89061             return ts.visitEachChild(node, visitor, context);
89062         }
89063         function visitor(node) {
89064             if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) {
89065                 return node;
89066             }
89067             switch (node.kind) {
89068                 case 216 /* BinaryExpression */:
89069                     return visitBinaryExpression(node);
89070                 default:
89071                     return ts.visitEachChild(node, visitor, context);
89072             }
89073         }
89074         function visitBinaryExpression(node) {
89075             switch (node.operatorToken.kind) {
89076                 case 66 /* AsteriskAsteriskEqualsToken */:
89077                     return visitExponentiationAssignmentExpression(node);
89078                 case 42 /* AsteriskAsteriskToken */:
89079                     return visitExponentiationExpression(node);
89080                 default:
89081                     return ts.visitEachChild(node, visitor, context);
89082             }
89083         }
89084         function visitExponentiationAssignmentExpression(node) {
89085             var target;
89086             var value;
89087             var left = ts.visitNode(node.left, visitor, ts.isExpression);
89088             var right = ts.visitNode(node.right, visitor, ts.isExpression);
89089             if (ts.isElementAccessExpression(left)) {
89090                 // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
89091                 var expressionTemp = factory.createTempVariable(hoistVariableDeclaration);
89092                 var argumentExpressionTemp = factory.createTempVariable(hoistVariableDeclaration);
89093                 target = ts.setTextRange(factory.createElementAccessExpression(ts.setTextRange(factory.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(factory.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left);
89094                 value = ts.setTextRange(factory.createElementAccessExpression(expressionTemp, argumentExpressionTemp), left);
89095             }
89096             else if (ts.isPropertyAccessExpression(left)) {
89097                 // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
89098                 var expressionTemp = factory.createTempVariable(hoistVariableDeclaration);
89099                 target = ts.setTextRange(factory.createPropertyAccessExpression(ts.setTextRange(factory.createAssignment(expressionTemp, left.expression), left.expression), left.name), left);
89100                 value = ts.setTextRange(factory.createPropertyAccessExpression(expressionTemp, left.name), left);
89101             }
89102             else {
89103                 // Transforms `a **= b` into `a = Math.pow(a, b)`
89104                 target = left;
89105                 value = left;
89106             }
89107             return ts.setTextRange(factory.createAssignment(target, ts.setTextRange(factory.createGlobalMethodCall("Math", "pow", [value, right]), node)), node);
89108         }
89109         function visitExponentiationExpression(node) {
89110             // Transforms `a ** b` into `Math.pow(a, b)`
89111             var left = ts.visitNode(node.left, visitor, ts.isExpression);
89112             var right = ts.visitNode(node.right, visitor, ts.isExpression);
89113             return ts.setTextRange(factory.createGlobalMethodCall("Math", "pow", [left, right]), node);
89114         }
89115     }
89116     ts.transformES2016 = transformES2016;
89117 })(ts || (ts = {}));
89118 /*@internal*/
89119 var ts;
89120 (function (ts) {
89121     var ES2015SubstitutionFlags;
89122     (function (ES2015SubstitutionFlags) {
89123         /** Enables substitutions for captured `this` */
89124         ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis";
89125         /** Enables substitutions for block-scoped bindings. */
89126         ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings";
89127     })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {}));
89128     var LoopOutParameterFlags;
89129     (function (LoopOutParameterFlags) {
89130         LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body";
89131         LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer";
89132     })(LoopOutParameterFlags || (LoopOutParameterFlags = {}));
89133     var CopyDirection;
89134     (function (CopyDirection) {
89135         CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal";
89136         CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter";
89137     })(CopyDirection || (CopyDirection = {}));
89138     var Jump;
89139     (function (Jump) {
89140         Jump[Jump["Break"] = 2] = "Break";
89141         Jump[Jump["Continue"] = 4] = "Continue";
89142         Jump[Jump["Return"] = 8] = "Return";
89143     })(Jump || (Jump = {}));
89144     // Facts we track as we traverse the tree
89145     var HierarchyFacts;
89146     (function (HierarchyFacts) {
89147         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
89148         //
89149         // Ancestor facts
89150         //
89151         HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function";
89152         HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction";
89153         HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody";
89154         HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement";
89155         HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis";
89156         HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement";
89157         HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel";
89158         HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block";
89159         HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement";
89160         HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock";
89161         HierarchyFacts[HierarchyFacts["IterationContainer"] = 1024] = "IterationContainer";
89162         HierarchyFacts[HierarchyFacts["ForStatement"] = 2048] = "ForStatement";
89163         HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 4096] = "ForInOrForOfStatement";
89164         HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 8192] = "ConstructorWithCapturedSuper";
89165         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
89166         // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
89167         //
89168         // Ancestor masks
89169         //
89170         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
89171         // We are always in *some* kind of block scope, but only specific block-scope containers are
89172         // top-level or Blocks.
89173         HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
89174         HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 7104] = "BlockScopeExcludes";
89175         // A source file is a top-level block scope.
89176         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes";
89177         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 8064] = "SourceFileExcludes";
89178         // Functions, methods, and accessors are both new lexical scopes and new block scopes.
89179         HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
89180         HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
89181         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
89182         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
89183         // Arrow functions are lexically scoped to their container, but are new block scopes.
89184         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
89185         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 15232] = "ArrowFunctionExcludes";
89186         // Constructors are both new lexical scopes and new block scopes. Constructors are also
89187         // always considered non-static members of a class.
89188         HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
89189         HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
89190         // 'do' and 'while' statements are not block scopes. We track that the subtree is contained
89191         // within an IterationStatement to indicate whether the embedded statement is an
89192         // IterationStatementBlock.
89193         HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 1280] = "DoOrWhileStatementIncludes";
89194         HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes";
89195         // 'for' statements are new block scopes and have special handling for 'let' declarations.
89196         HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 3328] = "ForStatementIncludes";
89197         HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 5056] = "ForStatementExcludes";
89198         // 'for-in' and 'for-of' statements are new block scopes and have special handling for
89199         // 'let' declarations.
89200         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 5376] = "ForInOrForOfStatementIncludes";
89201         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 3008] = "ForInOrForOfStatementExcludes";
89202         // Blocks (other than function bodies) are new block scopes.
89203         HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes";
89204         HierarchyFacts[HierarchyFacts["BlockExcludes"] = 6976] = "BlockExcludes";
89205         HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
89206         HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 7104] = "IterationStatementBlockExcludes";
89207         //
89208         // Subtree facts
89209         //
89210         HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
89211         HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 32768] = "CapturedLexicalThis";
89212         //
89213         // Subtree masks
89214         //
89215         HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
89216         HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
89217         HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 49152] = "FunctionSubtreeExcludes";
89218     })(HierarchyFacts || (HierarchyFacts = {}));
89219     function transformES2015(context) {
89220         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
89221         var compilerOptions = context.getCompilerOptions();
89222         var resolver = context.getEmitResolver();
89223         var previousOnSubstituteNode = context.onSubstituteNode;
89224         var previousOnEmitNode = context.onEmitNode;
89225         context.onEmitNode = onEmitNode;
89226         context.onSubstituteNode = onSubstituteNode;
89227         var currentSourceFile;
89228         var currentText;
89229         var hierarchyFacts;
89230         var taggedTemplateStringDeclarations;
89231         function recordTaggedTemplateString(temp) {
89232             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, factory.createVariableDeclaration(temp));
89233         }
89234         /**
89235          * Used to track if we are emitting body of the converted loop
89236          */
89237         var convertedLoopState;
89238         /**
89239          * Keeps track of whether substitutions have been enabled for specific cases.
89240          * They are persisted between each SourceFile transformation and should not
89241          * be reset.
89242          */
89243         var enabledSubstitutions;
89244         return ts.chainBundle(context, transformSourceFile);
89245         function transformSourceFile(node) {
89246             if (node.isDeclarationFile) {
89247                 return node;
89248             }
89249             currentSourceFile = node;
89250             currentText = node.text;
89251             var visited = visitSourceFile(node);
89252             ts.addEmitHelpers(visited, context.readEmitHelpers());
89253             currentSourceFile = undefined;
89254             currentText = undefined;
89255             taggedTemplateStringDeclarations = undefined;
89256             hierarchyFacts = 0 /* None */;
89257             return visited;
89258         }
89259         /**
89260          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
89261          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
89262          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
89263          */
89264         function enterSubtree(excludeFacts, includeFacts) {
89265             var ancestorFacts = hierarchyFacts;
89266             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
89267             return ancestorFacts;
89268         }
89269         /**
89270          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
89271          * subtree, propagating specific facts from the subtree.
89272          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
89273          * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
89274          * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
89275          */
89276         function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
89277             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
89278         }
89279         function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
89280             return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0
89281                 && node.kind === 242 /* ReturnStatement */
89282                 && !node.expression;
89283         }
89284         function isOrMayContainReturnCompletion(node) {
89285             return node.transformFlags & 1048576 /* ContainsHoistedDeclarationOrCompletion */
89286                 && (ts.isReturnStatement(node)
89287                     || ts.isIfStatement(node)
89288                     || ts.isWithStatement(node)
89289                     || ts.isSwitchStatement(node)
89290                     || ts.isCaseBlock(node)
89291                     || ts.isCaseClause(node)
89292                     || ts.isDefaultClause(node)
89293                     || ts.isTryStatement(node)
89294                     || ts.isCatchClause(node)
89295                     || ts.isLabeledStatement(node)
89296                     || ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)
89297                     || ts.isBlock(node));
89298         }
89299         function shouldVisitNode(node) {
89300             return (node.transformFlags & 256 /* ContainsES2015 */) !== 0
89301                 || convertedLoopState !== undefined
89302                 || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && isOrMayContainReturnCompletion(node))
89303                 || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node))
89304                 || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0;
89305         }
89306         function visitor(node) {
89307             return shouldVisitNode(node) ? visitorWorker(node, /*expressionResultIsUnused*/ false) : node;
89308         }
89309         function visitorWithUnusedExpressionResult(node) {
89310             return shouldVisitNode(node) ? visitorWorker(node, /*expressionResultIsUnused*/ true) : node;
89311         }
89312         function callExpressionVisitor(node) {
89313             if (node.kind === 105 /* SuperKeyword */) {
89314                 return visitSuperKeyword(/*isExpressionOfCall*/ true);
89315             }
89316             return visitor(node);
89317         }
89318         function visitorWorker(node, expressionResultIsUnused) {
89319             switch (node.kind) {
89320                 case 123 /* StaticKeyword */:
89321                     return undefined; // elide static keyword
89322                 case 252 /* ClassDeclaration */:
89323                     return visitClassDeclaration(node);
89324                 case 221 /* ClassExpression */:
89325                     return visitClassExpression(node);
89326                 case 160 /* Parameter */:
89327                     return visitParameter(node);
89328                 case 251 /* FunctionDeclaration */:
89329                     return visitFunctionDeclaration(node);
89330                 case 209 /* ArrowFunction */:
89331                     return visitArrowFunction(node);
89332                 case 208 /* FunctionExpression */:
89333                     return visitFunctionExpression(node);
89334                 case 249 /* VariableDeclaration */:
89335                     return visitVariableDeclaration(node);
89336                 case 78 /* Identifier */:
89337                     return visitIdentifier(node);
89338                 case 250 /* VariableDeclarationList */:
89339                     return visitVariableDeclarationList(node);
89340                 case 244 /* SwitchStatement */:
89341                     return visitSwitchStatement(node);
89342                 case 258 /* CaseBlock */:
89343                     return visitCaseBlock(node);
89344                 case 230 /* Block */:
89345                     return visitBlock(node, /*isFunctionBody*/ false);
89346                 case 241 /* BreakStatement */:
89347                 case 240 /* ContinueStatement */:
89348                     return visitBreakOrContinueStatement(node);
89349                 case 245 /* LabeledStatement */:
89350                     return visitLabeledStatement(node);
89351                 case 235 /* DoStatement */:
89352                 case 236 /* WhileStatement */:
89353                     return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined);
89354                 case 237 /* ForStatement */:
89355                     return visitForStatement(node, /*outermostLabeledStatement*/ undefined);
89356                 case 238 /* ForInStatement */:
89357                     return visitForInStatement(node, /*outermostLabeledStatement*/ undefined);
89358                 case 239 /* ForOfStatement */:
89359                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
89360                 case 233 /* ExpressionStatement */:
89361                     return visitExpressionStatement(node);
89362                 case 200 /* ObjectLiteralExpression */:
89363                     return visitObjectLiteralExpression(node);
89364                 case 287 /* CatchClause */:
89365                     return visitCatchClause(node);
89366                 case 289 /* ShorthandPropertyAssignment */:
89367                     return visitShorthandPropertyAssignment(node);
89368                 case 158 /* ComputedPropertyName */:
89369                     return visitComputedPropertyName(node);
89370                 case 199 /* ArrayLiteralExpression */:
89371                     return visitArrayLiteralExpression(node);
89372                 case 203 /* CallExpression */:
89373                     return visitCallExpression(node);
89374                 case 204 /* NewExpression */:
89375                     return visitNewExpression(node);
89376                 case 207 /* ParenthesizedExpression */:
89377                     return visitParenthesizedExpression(node, expressionResultIsUnused);
89378                 case 216 /* BinaryExpression */:
89379                     return visitBinaryExpression(node, expressionResultIsUnused);
89380                 case 337 /* CommaListExpression */:
89381                     return visitCommaListExpression(node, expressionResultIsUnused);
89382                 case 14 /* NoSubstitutionTemplateLiteral */:
89383                 case 15 /* TemplateHead */:
89384                 case 16 /* TemplateMiddle */:
89385                 case 17 /* TemplateTail */:
89386                     return visitTemplateLiteral(node);
89387                 case 10 /* StringLiteral */:
89388                     return visitStringLiteral(node);
89389                 case 8 /* NumericLiteral */:
89390                     return visitNumericLiteral(node);
89391                 case 205 /* TaggedTemplateExpression */:
89392                     return visitTaggedTemplateExpression(node);
89393                 case 218 /* TemplateExpression */:
89394                     return visitTemplateExpression(node);
89395                 case 219 /* YieldExpression */:
89396                     return visitYieldExpression(node);
89397                 case 220 /* SpreadElement */:
89398                     return visitSpreadElement(node);
89399                 case 105 /* SuperKeyword */:
89400                     return visitSuperKeyword(/*isExpressionOfCall*/ false);
89401                 case 107 /* ThisKeyword */:
89402                     return visitThisKeyword(node);
89403                 case 226 /* MetaProperty */:
89404                     return visitMetaProperty(node);
89405                 case 165 /* MethodDeclaration */:
89406                     return visitMethodDeclaration(node);
89407                 case 167 /* GetAccessor */:
89408                 case 168 /* SetAccessor */:
89409                     return visitAccessorDeclaration(node);
89410                 case 232 /* VariableStatement */:
89411                     return visitVariableStatement(node);
89412                 case 242 /* ReturnStatement */:
89413                     return visitReturnStatement(node);
89414                 case 212 /* VoidExpression */:
89415                     return visitVoidExpression(node);
89416                 default:
89417                     return ts.visitEachChild(node, visitor, context);
89418             }
89419         }
89420         function visitSourceFile(node) {
89421             var ancestorFacts = enterSubtree(8064 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
89422             var prologue = [];
89423             var statements = [];
89424             startLexicalEnvironment();
89425             var statementOffset = factory.copyPrologue(node.statements, prologue, /*ensureUseStrict*/ false, visitor);
89426             ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
89427             if (taggedTemplateStringDeclarations) {
89428                 statements.push(factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList(taggedTemplateStringDeclarations)));
89429             }
89430             factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
89431             insertCaptureThisForNodeIfNeeded(prologue, node);
89432             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
89433             return factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
89434         }
89435         function visitSwitchStatement(node) {
89436             if (convertedLoopState !== undefined) {
89437                 var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
89438                 // for switch statement allow only non-labeled break
89439                 convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
89440                 var result = ts.visitEachChild(node, visitor, context);
89441                 convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
89442                 return result;
89443             }
89444             return ts.visitEachChild(node, visitor, context);
89445         }
89446         function visitCaseBlock(node) {
89447             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
89448             var updated = ts.visitEachChild(node, visitor, context);
89449             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
89450             return updated;
89451         }
89452         function returnCapturedThis(node) {
89453             return ts.setOriginalNode(factory.createReturnStatement(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */)), node);
89454         }
89455         function visitReturnStatement(node) {
89456             if (convertedLoopState) {
89457                 convertedLoopState.nonLocalJumps |= 8 /* Return */;
89458                 if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
89459                     node = returnCapturedThis(node);
89460                 }
89461                 return factory.createReturnStatement(factory.createObjectLiteralExpression([
89462                     factory.createPropertyAssignment(factory.createIdentifier("value"), node.expression
89463                         ? ts.visitNode(node.expression, visitor, ts.isExpression)
89464                         : factory.createVoidZero())
89465                 ]));
89466             }
89467             else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
89468                 return returnCapturedThis(node);
89469             }
89470             return ts.visitEachChild(node, visitor, context);
89471         }
89472         function visitThisKeyword(node) {
89473             if (hierarchyFacts & 2 /* ArrowFunction */) {
89474                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
89475             }
89476             if (convertedLoopState) {
89477                 if (hierarchyFacts & 2 /* ArrowFunction */) {
89478                     // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
89479                     convertedLoopState.containsLexicalThis = true;
89480                     return node;
89481                 }
89482                 return convertedLoopState.thisName || (convertedLoopState.thisName = factory.createUniqueName("this"));
89483             }
89484             return node;
89485         }
89486         function visitVoidExpression(node) {
89487             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
89488         }
89489         function visitIdentifier(node) {
89490             if (!convertedLoopState) {
89491                 return node;
89492             }
89493             if (resolver.isArgumentsLocalBinding(node)) {
89494                 return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments"));
89495             }
89496             return node;
89497         }
89498         function visitBreakOrContinueStatement(node) {
89499             if (convertedLoopState) {
89500                 // check if we can emit break/continue as is
89501                 // it is possible if either
89502                 //   - break/continue is labeled and label is located inside the converted loop
89503                 //   - break/continue is non-labeled and located in non-converted loop/switch statement
89504                 var jump = node.kind === 241 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
89505                 var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) ||
89506                     (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
89507                 if (!canUseBreakOrContinue) {
89508                     var labelMarker = void 0;
89509                     var label = node.label;
89510                     if (!label) {
89511                         if (node.kind === 241 /* BreakStatement */) {
89512                             convertedLoopState.nonLocalJumps |= 2 /* Break */;
89513                             labelMarker = "break";
89514                         }
89515                         else {
89516                             convertedLoopState.nonLocalJumps |= 4 /* Continue */;
89517                             // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
89518                             labelMarker = "continue";
89519                         }
89520                     }
89521                     else {
89522                         if (node.kind === 241 /* BreakStatement */) {
89523                             labelMarker = "break-" + label.escapedText;
89524                             setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker);
89525                         }
89526                         else {
89527                             labelMarker = "continue-" + label.escapedText;
89528                             setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker);
89529                         }
89530                     }
89531                     var returnExpression = factory.createStringLiteral(labelMarker);
89532                     if (convertedLoopState.loopOutParameters.length) {
89533                         var outParams = convertedLoopState.loopOutParameters;
89534                         var expr = void 0;
89535                         for (var i = 0; i < outParams.length; i++) {
89536                             var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */);
89537                             if (i === 0) {
89538                                 expr = copyExpr;
89539                             }
89540                             else {
89541                                 expr = factory.createBinaryExpression(expr, 27 /* CommaToken */, copyExpr);
89542                             }
89543                         }
89544                         returnExpression = factory.createBinaryExpression(expr, 27 /* CommaToken */, returnExpression);
89545                     }
89546                     return factory.createReturnStatement(returnExpression);
89547                 }
89548             }
89549             return ts.visitEachChild(node, visitor, context);
89550         }
89551         /**
89552          * Visits a ClassDeclaration and transforms it into a variable statement.
89553          *
89554          * @param node A ClassDeclaration node.
89555          */
89556         function visitClassDeclaration(node) {
89557             // [source]
89558             //      class C { }
89559             //
89560             // [output]
89561             //      var C = (function () {
89562             //          function C() {
89563             //          }
89564             //          return C;
89565             //      }());
89566             var variable = factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ true), 
89567             /*exclamationToken*/ undefined, 
89568             /*type*/ undefined, transformClassLikeDeclarationToExpression(node));
89569             ts.setOriginalNode(variable, node);
89570             var statements = [];
89571             var statement = factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([variable]));
89572             ts.setOriginalNode(statement, node);
89573             ts.setTextRange(statement, node);
89574             ts.startOnNewLine(statement);
89575             statements.push(statement);
89576             // Add an `export default` statement for default exports (for `--target es5 --module es6`)
89577             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
89578                 var exportStatement = ts.hasSyntacticModifier(node, 512 /* Default */)
89579                     ? factory.createExportDefault(factory.getLocalName(node))
89580                     : factory.createExternalModuleExport(factory.getLocalName(node));
89581                 ts.setOriginalNode(exportStatement, statement);
89582                 statements.push(exportStatement);
89583             }
89584             var emitFlags = ts.getEmitFlags(node);
89585             if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) {
89586                 // Add a DeclarationMarker as a marker for the end of the declaration
89587                 statements.push(factory.createEndOfDeclarationMarker(node));
89588                 ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */);
89589             }
89590             return ts.singleOrMany(statements);
89591         }
89592         /**
89593          * Visits a ClassExpression and transforms it into an expression.
89594          *
89595          * @param node A ClassExpression node.
89596          */
89597         function visitClassExpression(node) {
89598             // [source]
89599             //      C = class { }
89600             //
89601             // [output]
89602             //      C = (function () {
89603             //          function class_1() {
89604             //          }
89605             //          return class_1;
89606             //      }())
89607             return transformClassLikeDeclarationToExpression(node);
89608         }
89609         /**
89610          * Transforms a ClassExpression or ClassDeclaration into an expression.
89611          *
89612          * @param node A ClassExpression or ClassDeclaration node.
89613          */
89614         function transformClassLikeDeclarationToExpression(node) {
89615             // [source]
89616             //      class C extends D {
89617             //          constructor() {}
89618             //          method() {}
89619             //          get prop() {}
89620             //          set prop(v) {}
89621             //      }
89622             //
89623             // [output]
89624             //      (function (_super) {
89625             //          __extends(C, _super);
89626             //          function C() {
89627             //          }
89628             //          C.prototype.method = function () {}
89629             //          Object.defineProperty(C.prototype, "prop", {
89630             //              get: function() {},
89631             //              set: function() {},
89632             //              enumerable: true,
89633             //              configurable: true
89634             //          });
89635             //          return C;
89636             //      }(D))
89637             if (node.name) {
89638                 enableSubstitutionsForBlockScopedBindings();
89639             }
89640             var extendsClauseElement = ts.getClassExtendsHeritageElement(node);
89641             var classFunction = factory.createFunctionExpression(
89642             /*modifiers*/ undefined, 
89643             /*asteriskToken*/ undefined, 
89644             /*name*/ undefined, 
89645             /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */))] : [], 
89646             /*type*/ undefined, transformClassBody(node, extendsClauseElement));
89647             // To preserve the behavior of the old emitter, we explicitly indent
89648             // the body of the function here if it was requested in an earlier
89649             // transformation.
89650             ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */);
89651             // "inner" and "outer" below are added purely to preserve source map locations from
89652             // the old emitter
89653             var inner = factory.createPartiallyEmittedExpression(classFunction);
89654             ts.setTextRangeEnd(inner, node.end);
89655             ts.setEmitFlags(inner, 1536 /* NoComments */);
89656             var outer = factory.createPartiallyEmittedExpression(inner);
89657             ts.setTextRangeEnd(outer, ts.skipTrivia(currentText, node.pos));
89658             ts.setEmitFlags(outer, 1536 /* NoComments */);
89659             var result = factory.createParenthesizedExpression(factory.createCallExpression(outer, 
89660             /*typeArguments*/ undefined, extendsClauseElement
89661                 ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)]
89662                 : []));
89663             ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class ");
89664             return result;
89665         }
89666         /**
89667          * Transforms a ClassExpression or ClassDeclaration into a function body.
89668          *
89669          * @param node A ClassExpression or ClassDeclaration node.
89670          * @param extendsClauseElement The expression for the class `extends` clause.
89671          */
89672         function transformClassBody(node, extendsClauseElement) {
89673             var statements = [];
89674             var name = factory.getInternalName(node);
89675             var constructorLikeName = ts.isIdentifierANonContextualKeyword(name) ? factory.getGeneratedNameForNode(name) : name;
89676             startLexicalEnvironment();
89677             addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
89678             addConstructor(statements, node, constructorLikeName, extendsClauseElement);
89679             addClassMembers(statements, node);
89680             // Create a synthetic text range for the return statement.
89681             var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */);
89682             // The following partially-emitted expression exists purely to align our sourcemap
89683             // emit with the original emitter.
89684             var outer = factory.createPartiallyEmittedExpression(constructorLikeName);
89685             ts.setTextRangeEnd(outer, closingBraceLocation.end);
89686             ts.setEmitFlags(outer, 1536 /* NoComments */);
89687             var statement = factory.createReturnStatement(outer);
89688             ts.setTextRangePos(statement, closingBraceLocation.pos);
89689             ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
89690             statements.push(statement);
89691             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
89692             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
89693             ts.setEmitFlags(block, 1536 /* NoComments */);
89694             return block;
89695         }
89696         /**
89697          * Adds a call to the `__extends` helper if needed for a class.
89698          *
89699          * @param statements The statements of the class body function.
89700          * @param node The ClassExpression or ClassDeclaration node.
89701          * @param extendsClauseElement The expression for the class `extends` clause.
89702          */
89703         function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
89704             if (extendsClauseElement) {
89705                 statements.push(ts.setTextRange(factory.createExpressionStatement(emitHelpers().createExtendsHelper(factory.getInternalName(node))), 
89706                 /*location*/ extendsClauseElement));
89707             }
89708         }
89709         /**
89710          * Adds the constructor of the class to a class body function.
89711          *
89712          * @param statements The statements of the class body function.
89713          * @param node The ClassExpression or ClassDeclaration node.
89714          * @param extendsClauseElement The expression for the class `extends` clause.
89715          */
89716         function addConstructor(statements, node, name, extendsClauseElement) {
89717             var savedConvertedLoopState = convertedLoopState;
89718             convertedLoopState = undefined;
89719             var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
89720             var constructor = ts.getFirstConstructorWithBody(node);
89721             var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
89722             var constructorFunction = factory.createFunctionDeclaration(
89723             /*decorators*/ undefined, 
89724             /*modifiers*/ undefined, 
89725             /*asteriskToken*/ undefined, name, 
89726             /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), 
89727             /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
89728             ts.setTextRange(constructorFunction, constructor || node);
89729             if (extendsClauseElement) {
89730                 ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
89731             }
89732             statements.push(constructorFunction);
89733             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
89734             convertedLoopState = savedConvertedLoopState;
89735         }
89736         /**
89737          * Transforms the parameters of the constructor declaration of a class.
89738          *
89739          * @param constructor The constructor for the class.
89740          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
89741          *                            synthesized `super` call.
89742          */
89743         function transformConstructorParameters(constructor, hasSynthesizedSuper) {
89744             // If the TypeScript transformer needed to synthesize a constructor for property
89745             // initializers, it would have also added a synthetic `...args` parameter and
89746             // `super` call.
89747             // If this is the case, we do not include the synthetic `...args` parameter and
89748             // will instead use the `arguments` object in ES5/3.
89749             return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
89750                 || [];
89751         }
89752         function createDefaultConstructorBody(node, isDerivedClass) {
89753             // We must be here because the user didn't write a constructor
89754             // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
89755             // If that's the case we can just immediately return the result of a 'super()' call.
89756             var statements = [];
89757             resumeLexicalEnvironment();
89758             factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
89759             if (isDerivedClass) {
89760                 // return _super !== null && _super.apply(this, arguments) || this;
89761                 statements.push(factory.createReturnStatement(createDefaultSuperCallOrThis()));
89762             }
89763             var statementsArray = factory.createNodeArray(statements);
89764             ts.setTextRange(statementsArray, node.members);
89765             var block = factory.createBlock(statementsArray, /*multiLine*/ true);
89766             ts.setTextRange(block, node);
89767             ts.setEmitFlags(block, 1536 /* NoComments */);
89768             return block;
89769         }
89770         /**
89771          * Transforms the body of a constructor declaration of a class.
89772          *
89773          * @param constructor The constructor for the class.
89774          * @param node The node which contains the constructor.
89775          * @param extendsClauseElement The expression for the class `extends` clause.
89776          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
89777          *                            synthesized `super` call.
89778          */
89779         function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
89780             // determine whether the class is known syntactically to be a derived class (e.g. a
89781             // class that extends a value that is not syntactically known to be `null`).
89782             var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */;
89783             // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
89784             // representation:
89785             //
89786             // ```
89787             // // es2015 (source)
89788             // class C extends Base { }
89789             //
89790             // // es5 (transformed)
89791             // var C = (function (_super) {
89792             //     function C() {
89793             //         return _super.apply(this, arguments) || this;
89794             //     }
89795             //     return C;
89796             // })(Base);
89797             // ```
89798             if (!constructor)
89799                 return createDefaultConstructorBody(node, isDerivedClass);
89800             // The prologue will contain all leading standard and custom prologue statements added by this transform
89801             var prologue = [];
89802             var statements = [];
89803             resumeLexicalEnvironment();
89804             // If a super call has already been synthesized,
89805             // we're going to assume that we should just transform everything after that.
89806             // The assumption is that no prior step in the pipeline has added any prologue directives.
89807             var statementOffset = 0;
89808             if (!hasSynthesizedSuper)
89809                 statementOffset = factory.copyStandardPrologue(constructor.body.statements, prologue, /*ensureUseStrict*/ false);
89810             addDefaultValueAssignmentsIfNeeded(statements, constructor);
89811             addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
89812             if (!hasSynthesizedSuper)
89813                 statementOffset = factory.copyCustomPrologue(constructor.body.statements, statements, statementOffset, visitor);
89814             // If the first statement is a call to `super()`, visit the statement directly
89815             var superCallExpression;
89816             if (hasSynthesizedSuper) {
89817                 superCallExpression = createDefaultSuperCallOrThis();
89818             }
89819             else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
89820                 var firstStatement = constructor.body.statements[statementOffset];
89821                 if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
89822                     superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
89823                 }
89824             }
89825             if (superCallExpression) {
89826                 hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */;
89827                 statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
89828             }
89829             // visit the remaining statements
89830             ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
89831             factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
89832             insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
89833             if (isDerivedClass) {
89834                 if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) {
89835                     // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
89836                     // following representation:
89837                     //
89838                     // ```
89839                     // // es2015 (source)
89840                     // class C extends Base {
89841                     //     constructor() {
89842                     //         super("foo");
89843                     //     }
89844                     // }
89845                     //
89846                     // // es5 (transformed)
89847                     // var C = (function (_super) {
89848                     //     function C() {
89849                     //         return _super.call(this, "foo") || this;
89850                     //     }
89851                     //     return C;
89852                     // })(Base);
89853                     // ```
89854                     var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
89855                     var returnStatement = factory.createReturnStatement(superCallExpression);
89856                     ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
89857                     ts.setEmitFlags(superCall, 1536 /* NoComments */);
89858                     statements.push(returnStatement);
89859                 }
89860                 else {
89861                     // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
89862                     //
89863                     // ```
89864                     // // es2015 (source)
89865                     // class C extends Base {
89866                     //     constructor() {
89867                     //         super("foo");
89868                     //         this.x = 1;
89869                     //     }
89870                     // }
89871                     //
89872                     // // es5 (transformed)
89873                     // var C = (function (_super) {
89874                     //     function C() {
89875                     //         var _this = _super.call(this, "foo") || this;
89876                     //         _this.x = 1;
89877                     //         return _this;
89878                     //     }
89879                     //     return C;
89880                     // })(Base);
89881                     // ```
89882                     // Since the `super()` call was the first statement, we insert the `this` capturing call to
89883                     // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
89884                     insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
89885                     if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
89886                         statements.push(factory.createReturnStatement(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */)));
89887                     }
89888                 }
89889             }
89890             else {
89891                 // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
89892                 // captured when necessitated by an arrow function capturing the lexical `this`:
89893                 //
89894                 // ```
89895                 // // es2015
89896                 // class C {}
89897                 //
89898                 // // es5
89899                 // var C = (function () {
89900                 //     function C() {
89901                 //     }
89902                 //     return C;
89903                 // })();
89904                 // ```
89905                 insertCaptureThisForNodeIfNeeded(prologue, constructor);
89906             }
89907             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(ts.concatenate(prologue, statements)), 
89908             /*location*/ constructor.body.statements), 
89909             /*multiLine*/ true);
89910             ts.setTextRange(block, constructor.body);
89911             return block;
89912         }
89913         /**
89914          * We want to try to avoid emitting a return statement in certain cases if a user already returned something.
89915          * It would generate obviously dead code, so we'll try to make things a little bit prettier
89916          * by doing a minimal check on whether some common patterns always explicitly return.
89917          */
89918         function isSufficientlyCoveredByReturnStatements(statement) {
89919             // A return statement is considered covered.
89920             if (statement.kind === 242 /* ReturnStatement */) {
89921                 return true;
89922             }
89923             // An if-statement with two covered branches is covered.
89924             else if (statement.kind === 234 /* IfStatement */) {
89925                 var ifStatement = statement;
89926                 if (ifStatement.elseStatement) {
89927                     return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) &&
89928                         isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
89929                 }
89930             }
89931             // A block is covered if it has a last statement which is covered.
89932             else if (statement.kind === 230 /* Block */) {
89933                 var lastStatement = ts.lastOrUndefined(statement.statements);
89934                 if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
89935                     return true;
89936                 }
89937             }
89938             return false;
89939         }
89940         function createActualThis() {
89941             return ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */);
89942         }
89943         function createDefaultSuperCallOrThis() {
89944             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());
89945         }
89946         /**
89947          * Visits a parameter declaration.
89948          *
89949          * @param node A ParameterDeclaration node.
89950          */
89951         function visitParameter(node) {
89952             if (node.dotDotDotToken) {
89953                 // rest parameters are elided
89954                 return undefined;
89955             }
89956             else if (ts.isBindingPattern(node.name)) {
89957                 // Binding patterns are converted into a generated name and are
89958                 // evaluated inside the function body.
89959                 return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration(
89960                 /*decorators*/ undefined, 
89961                 /*modifiers*/ undefined, 
89962                 /*dotDotDotToken*/ undefined, factory.getGeneratedNameForNode(node), 
89963                 /*questionToken*/ undefined, 
89964                 /*type*/ undefined, 
89965                 /*initializer*/ undefined), 
89966                 /*location*/ node), 
89967                 /*original*/ node);
89968             }
89969             else if (node.initializer) {
89970                 // Initializers are elided
89971                 return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration(
89972                 /*decorators*/ undefined, 
89973                 /*modifiers*/ undefined, 
89974                 /*dotDotDotToken*/ undefined, node.name, 
89975                 /*questionToken*/ undefined, 
89976                 /*type*/ undefined, 
89977                 /*initializer*/ undefined), 
89978                 /*location*/ node), 
89979                 /*original*/ node);
89980             }
89981             else {
89982                 return node;
89983             }
89984         }
89985         function hasDefaultValueOrBindingPattern(node) {
89986             return node.initializer !== undefined
89987                 || ts.isBindingPattern(node.name);
89988         }
89989         /**
89990          * Adds statements to the body of a function-like node if it contains parameters with
89991          * binding patterns or initializers.
89992          *
89993          * @param statements The statements for the new function body.
89994          * @param node A function-like node.
89995          */
89996         function addDefaultValueAssignmentsIfNeeded(statements, node) {
89997             if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
89998                 return false;
89999             }
90000             var added = false;
90001             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
90002                 var parameter = _a[_i];
90003                 var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
90004                 // A rest parameter cannot have a binding pattern or an initializer,
90005                 // so let's just ignore it.
90006                 if (dotDotDotToken) {
90007                     continue;
90008                 }
90009                 if (ts.isBindingPattern(name)) {
90010                     added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
90011                 }
90012                 else if (initializer) {
90013                     insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
90014                     added = true;
90015                 }
90016             }
90017             return added;
90018         }
90019         /**
90020          * Adds statements to the body of a function-like node for parameters with binding patterns
90021          *
90022          * @param statements The statements for the new function body.
90023          * @param parameter The parameter for the function.
90024          * @param name The name of the parameter.
90025          * @param initializer The initializer for the parameter.
90026          */
90027         function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
90028             // In cases where a binding pattern is simply '[]' or '{}',
90029             // we usually don't want to emit a var declaration; however, in the presence
90030             // of an initializer, we must emit that expression to preserve side effects.
90031             if (name.elements.length > 0) {
90032                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(factory.createVariableStatement(
90033                 /*modifiers*/ undefined, factory.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, factory.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
90034                 return true;
90035             }
90036             else if (initializer) {
90037                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(factory.createExpressionStatement(factory.createAssignment(factory.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
90038                 return true;
90039             }
90040             return false;
90041         }
90042         /**
90043          * Adds statements to the body of a function-like node for parameters with initializers.
90044          *
90045          * @param statements The statements for the new function body.
90046          * @param parameter The parameter for the function.
90047          * @param name The name of the parameter.
90048          * @param initializer The initializer for the parameter.
90049          */
90050         function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
90051             initializer = ts.visitNode(initializer, visitor, ts.isExpression);
90052             var statement = factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([
90053                 factory.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(factory.createAssignment(
90054                 // TODO(rbuckton): Does this need to be parented?
90055                 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 */))
90056             ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
90057             ts.startOnNewLine(statement);
90058             ts.setTextRange(statement, parameter);
90059             ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
90060             ts.insertStatementAfterCustomPrologue(statements, statement);
90061         }
90062         /**
90063          * Gets a value indicating whether we need to add statements to handle a rest parameter.
90064          *
90065          * @param node A ParameterDeclaration node.
90066          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
90067          *                                          part of a constructor declaration with a
90068          *                                          synthesized call to `super`
90069          */
90070         function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
90071             return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper);
90072         }
90073         /**
90074          * Adds statements to the body of a function-like node if it contains a rest parameter.
90075          *
90076          * @param statements The statements for the new function body.
90077          * @param node A function-like node.
90078          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
90079          *                                          part of a constructor declaration with a
90080          *                                          synthesized call to `super`
90081          */
90082         function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
90083             var prologueStatements = [];
90084             var parameter = ts.lastOrUndefined(node.parameters);
90085             if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
90086                 return false;
90087             }
90088             // `declarationName` is the name of the local declaration for the parameter.
90089             // TODO(rbuckton): Does this need to be parented?
90090             var declarationName = parameter.name.kind === 78 /* Identifier */ ? ts.setParent(ts.setTextRange(factory.cloneNode(parameter.name), parameter.name), parameter.name.parent) : factory.createTempVariable(/*recordTempVariable*/ undefined);
90091             ts.setEmitFlags(declarationName, 48 /* NoSourceMap */);
90092             // `expressionName` is the name of the parameter used in expressions.
90093             var expressionName = parameter.name.kind === 78 /* Identifier */ ? factory.cloneNode(parameter.name) : declarationName;
90094             var restIndex = node.parameters.length - 1;
90095             var temp = factory.createLoopVariable();
90096             // var param = [];
90097             prologueStatements.push(ts.setEmitFlags(ts.setTextRange(factory.createVariableStatement(
90098             /*modifiers*/ undefined, factory.createVariableDeclarationList([
90099                 factory.createVariableDeclaration(declarationName, 
90100                 /*exclamationToken*/ undefined, 
90101                 /*type*/ undefined, factory.createArrayLiteralExpression([]))
90102             ])), 
90103             /*location*/ parameter), 1048576 /* CustomPrologue */));
90104             // for (var _i = restIndex; _i < arguments.length; _i++) {
90105             //   param[_i - restIndex] = arguments[_i];
90106             // }
90107             var forStatement = factory.createForStatement(ts.setTextRange(factory.createVariableDeclarationList([
90108                 factory.createVariableDeclaration(temp, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createNumericLiteral(restIndex))
90109             ]), parameter), ts.setTextRange(factory.createLessThan(temp, factory.createPropertyAccessExpression(factory.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(factory.createPostfixIncrement(temp), parameter), factory.createBlock([
90110                 ts.startOnNewLine(ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(factory.createElementAccessExpression(expressionName, restIndex === 0
90111                     ? temp
90112                     : factory.createSubtract(temp, factory.createNumericLiteral(restIndex))), factory.createElementAccessExpression(factory.createIdentifier("arguments"), temp))), 
90113                 /*location*/ parameter))
90114             ]));
90115             ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
90116             ts.startOnNewLine(forStatement);
90117             prologueStatements.push(forStatement);
90118             if (parameter.name.kind !== 78 /* Identifier */) {
90119                 // do the actual destructuring of the rest parameter if necessary
90120                 prologueStatements.push(ts.setEmitFlags(ts.setTextRange(factory.createVariableStatement(
90121                 /*modifiers*/ undefined, factory.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
90122             }
90123             ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
90124             return true;
90125         }
90126         /**
90127          * Adds a statement to capture the `this` of a function declaration if it is needed.
90128          * NOTE: This must be executed *after* the subtree has been visited.
90129          *
90130          * @param statements The statements for the new function body.
90131          * @param node A node.
90132          */
90133         function insertCaptureThisForNodeIfNeeded(statements, node) {
90134             if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 209 /* ArrowFunction */) {
90135                 insertCaptureThisForNode(statements, node, factory.createThis());
90136                 return true;
90137             }
90138             return false;
90139         }
90140         function insertCaptureThisForNode(statements, node, initializer) {
90141             enableSubstitutionsForCapturedThis();
90142             var captureThisStatement = factory.createVariableStatement(
90143             /*modifiers*/ undefined, factory.createVariableDeclarationList([
90144                 factory.createVariableDeclaration(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), 
90145                 /*exclamationToken*/ undefined, 
90146                 /*type*/ undefined, initializer)
90147             ]));
90148             ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
90149             ts.setSourceMapRange(captureThisStatement, node);
90150             ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
90151         }
90152         function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
90153             if (hierarchyFacts & 16384 /* NewTarget */) {
90154                 var newTarget = void 0;
90155                 switch (node.kind) {
90156                     case 209 /* ArrowFunction */:
90157                         return statements;
90158                     case 165 /* MethodDeclaration */:
90159                     case 167 /* GetAccessor */:
90160                     case 168 /* SetAccessor */:
90161                         // Methods and accessors cannot be constructors, so 'new.target' will
90162                         // always return 'undefined'.
90163                         newTarget = factory.createVoidZero();
90164                         break;
90165                     case 166 /* Constructor */:
90166                         // Class constructors can only be called with `new`, so `this.constructor`
90167                         // should be relatively safe to use.
90168                         newTarget = factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), "constructor");
90169                         break;
90170                     case 251 /* FunctionDeclaration */:
90171                     case 208 /* FunctionExpression */:
90172                         // Functions can be called or constructed, and may have a `this` due to
90173                         // being a member or when calling an imported function via `other_1.f()`.
90174                         newTarget = factory.createConditionalExpression(factory.createLogicalAnd(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), factory.createBinaryExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), 101 /* InstanceOfKeyword */, factory.getLocalName(node))), 
90175                         /*questionToken*/ undefined, factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), "constructor"), 
90176                         /*colonToken*/ undefined, factory.createVoidZero());
90177                         break;
90178                     default:
90179                         return ts.Debug.failBadSyntaxKind(node);
90180                 }
90181                 var captureNewTargetStatement = factory.createVariableStatement(
90182                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
90183                     factory.createVariableDeclaration(factory.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */), 
90184                     /*exclamationToken*/ undefined, 
90185                     /*type*/ undefined, newTarget)
90186                 ]));
90187                 ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
90188                 if (copyOnWrite) {
90189                     statements = statements.slice();
90190                 }
90191                 ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
90192             }
90193             return statements;
90194         }
90195         /**
90196          * Adds statements to the class body function for a class to define the members of the
90197          * class.
90198          *
90199          * @param statements The statements for the class body function.
90200          * @param node The ClassExpression or ClassDeclaration node.
90201          */
90202         function addClassMembers(statements, node) {
90203             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
90204                 var member = _a[_i];
90205                 switch (member.kind) {
90206                     case 229 /* SemicolonClassElement */:
90207                         statements.push(transformSemicolonClassElementToStatement(member));
90208                         break;
90209                     case 165 /* MethodDeclaration */:
90210                         statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
90211                         break;
90212                     case 167 /* GetAccessor */:
90213                     case 168 /* SetAccessor */:
90214                         var accessors = ts.getAllAccessorDeclarations(node.members, member);
90215                         if (member === accessors.firstAccessor) {
90216                             statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
90217                         }
90218                         break;
90219                     case 166 /* Constructor */:
90220                         // Constructors are handled in visitClassExpression/visitClassDeclaration
90221                         break;
90222                     default:
90223                         ts.Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName);
90224                         break;
90225                 }
90226             }
90227         }
90228         /**
90229          * Transforms a SemicolonClassElement into a statement for a class body function.
90230          *
90231          * @param member The SemicolonClassElement node.
90232          */
90233         function transformSemicolonClassElementToStatement(member) {
90234             return ts.setTextRange(factory.createEmptyStatement(), member);
90235         }
90236         /**
90237          * Transforms a MethodDeclaration into a statement for a class body function.
90238          *
90239          * @param receiver The receiver for the member.
90240          * @param member The MethodDeclaration node.
90241          */
90242         function transformClassMethodDeclarationToStatement(receiver, member, container) {
90243             var commentRange = ts.getCommentRange(member);
90244             var sourceMapRange = ts.getSourceMapRange(member);
90245             var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container);
90246             var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName);
90247             var e;
90248             if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) {
90249                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
90250                     : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
90251                         : propertyName;
90252                 e = factory.createObjectDefinePropertyCall(receiver, name, factory.createPropertyDescriptor({ value: memberFunction, enumerable: false, writable: true, configurable: true }));
90253             }
90254             else {
90255                 var memberName = ts.createMemberAccessForPropertyName(factory, receiver, propertyName, /*location*/ member.name);
90256                 e = factory.createAssignment(memberName, memberFunction);
90257             }
90258             ts.setEmitFlags(memberFunction, 1536 /* NoComments */);
90259             ts.setSourceMapRange(memberFunction, sourceMapRange);
90260             var statement = ts.setTextRange(factory.createExpressionStatement(e), /*location*/ member);
90261             ts.setOriginalNode(statement, member);
90262             ts.setCommentRange(statement, commentRange);
90263             // The location for the statement is used to emit comments only.
90264             // No source map should be emitted for this statement to align with the
90265             // old emitter.
90266             ts.setEmitFlags(statement, 48 /* NoSourceMap */);
90267             return statement;
90268         }
90269         /**
90270          * Transforms a set of related of get/set accessors into a statement for a class body function.
90271          *
90272          * @param receiver The receiver for the member.
90273          * @param accessors The set of related get/set accessors.
90274          */
90275         function transformAccessorsToStatement(receiver, accessors, container) {
90276             var statement = factory.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false));
90277             // The location for the statement is used to emit source maps only.
90278             // No comments should be emitted for this statement to align with the
90279             // old emitter.
90280             ts.setEmitFlags(statement, 1536 /* NoComments */);
90281             ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor));
90282             return statement;
90283         }
90284         /**
90285          * Transforms a set of related get/set accessors into an expression for either a class
90286          * body function or an ObjectLiteralExpression with computed properties.
90287          *
90288          * @param receiver The receiver for the member.
90289          */
90290         function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
90291             var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
90292             // To align with source maps in the old emitter, the receiver and property name
90293             // arguments are both mapped contiguously to the accessor name.
90294             // TODO(rbuckton): Does this need to be parented?
90295             var target = ts.setParent(ts.setTextRange(factory.cloneNode(receiver), receiver), receiver.parent);
90296             ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */);
90297             ts.setSourceMapRange(target, firstAccessor.name);
90298             var visitedAccessorName = ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName);
90299             if (ts.isPrivateIdentifier(visitedAccessorName)) {
90300                 return ts.Debug.failBadSyntaxKind(visitedAccessorName, "Encountered unhandled private identifier while transforming ES2015.");
90301             }
90302             var propertyName = ts.createExpressionForPropertyName(factory, visitedAccessorName);
90303             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */);
90304             ts.setSourceMapRange(propertyName, firstAccessor.name);
90305             var properties = [];
90306             if (getAccessor) {
90307                 var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container);
90308                 ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor));
90309                 ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */);
90310                 var getter = factory.createPropertyAssignment("get", getterFunction);
90311                 ts.setCommentRange(getter, ts.getCommentRange(getAccessor));
90312                 properties.push(getter);
90313             }
90314             if (setAccessor) {
90315                 var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container);
90316                 ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor));
90317                 ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */);
90318                 var setter = factory.createPropertyAssignment("set", setterFunction);
90319                 ts.setCommentRange(setter, ts.getCommentRange(setAccessor));
90320                 properties.push(setter);
90321             }
90322             properties.push(factory.createPropertyAssignment("enumerable", getAccessor || setAccessor ? factory.createFalse() : factory.createTrue()), factory.createPropertyAssignment("configurable", factory.createTrue()));
90323             var call = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "defineProperty"), 
90324             /*typeArguments*/ undefined, [
90325                 target,
90326                 propertyName,
90327                 factory.createObjectLiteralExpression(properties, /*multiLine*/ true)
90328             ]);
90329             if (startsOnNewLine) {
90330                 ts.startOnNewLine(call);
90331             }
90332             return call;
90333         }
90334         /**
90335          * Visits an ArrowFunction and transforms it into a FunctionExpression.
90336          *
90337          * @param node An ArrowFunction node.
90338          */
90339         function visitArrowFunction(node) {
90340             if (node.transformFlags & 4096 /* ContainsLexicalThis */) {
90341                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
90342             }
90343             var savedConvertedLoopState = convertedLoopState;
90344             convertedLoopState = undefined;
90345             var ancestorFacts = enterSubtree(15232 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
90346             var func = factory.createFunctionExpression(
90347             /*modifiers*/ undefined, 
90348             /*asteriskToken*/ undefined, 
90349             /*name*/ undefined, 
90350             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
90351             /*type*/ undefined, transformFunctionBody(node));
90352             ts.setTextRange(func, node);
90353             ts.setOriginalNode(func, node);
90354             ts.setEmitFlags(func, 8 /* CapturesThis */);
90355             if (hierarchyFacts & 32768 /* CapturedLexicalThis */) {
90356                 enableSubstitutionsForCapturedThis();
90357             }
90358             // If an arrow function contains
90359             exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
90360             convertedLoopState = savedConvertedLoopState;
90361             return func;
90362         }
90363         /**
90364          * Visits a FunctionExpression node.
90365          *
90366          * @param node a FunctionExpression node.
90367          */
90368         function visitFunctionExpression(node) {
90369             var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
90370                 ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
90371                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
90372             var savedConvertedLoopState = convertedLoopState;
90373             convertedLoopState = undefined;
90374             var parameters = ts.visitParameterList(node.parameters, visitor, context);
90375             var body = transformFunctionBody(node);
90376             var name = hierarchyFacts & 16384 /* NewTarget */
90377                 ? factory.getLocalName(node)
90378                 : node.name;
90379             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
90380             convertedLoopState = savedConvertedLoopState;
90381             return factory.updateFunctionExpression(node, 
90382             /*modifiers*/ undefined, node.asteriskToken, name, 
90383             /*typeParameters*/ undefined, parameters, 
90384             /*type*/ undefined, body);
90385         }
90386         /**
90387          * Visits a FunctionDeclaration node.
90388          *
90389          * @param node a FunctionDeclaration node.
90390          */
90391         function visitFunctionDeclaration(node) {
90392             var savedConvertedLoopState = convertedLoopState;
90393             convertedLoopState = undefined;
90394             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
90395             var parameters = ts.visitParameterList(node.parameters, visitor, context);
90396             var body = transformFunctionBody(node);
90397             var name = hierarchyFacts & 16384 /* NewTarget */
90398                 ? factory.getLocalName(node)
90399                 : node.name;
90400             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
90401             convertedLoopState = savedConvertedLoopState;
90402             return factory.updateFunctionDeclaration(node, 
90403             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, 
90404             /*typeParameters*/ undefined, parameters, 
90405             /*type*/ undefined, body);
90406         }
90407         /**
90408          * Transforms a function-like node into a FunctionExpression.
90409          *
90410          * @param node The function-like node to transform.
90411          * @param location The source-map location for the new FunctionExpression.
90412          * @param name The name of the new FunctionExpression.
90413          */
90414         function transformFunctionLikeToExpression(node, location, name, container) {
90415             var savedConvertedLoopState = convertedLoopState;
90416             convertedLoopState = undefined;
90417             var ancestorFacts = container && ts.isClassLike(container) && !ts.hasSyntacticModifier(node, 32 /* Static */)
90418                 ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
90419                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
90420             var parameters = ts.visitParameterList(node.parameters, visitor, context);
90421             var body = transformFunctionBody(node);
90422             if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) {
90423                 name = factory.getGeneratedNameForNode(node);
90424             }
90425             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
90426             convertedLoopState = savedConvertedLoopState;
90427             return ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(
90428             /*modifiers*/ undefined, node.asteriskToken, name, 
90429             /*typeParameters*/ undefined, parameters, 
90430             /*type*/ undefined, body), location), 
90431             /*original*/ node);
90432         }
90433         /**
90434          * Transforms the body of a function-like node.
90435          *
90436          * @param node A function-like node.
90437          */
90438         function transformFunctionBody(node) {
90439             var multiLine = false; // indicates whether the block *must* be emitted as multiple lines
90440             var singleLine = false; // indicates whether the block *may* be emitted as a single line
90441             var statementsLocation;
90442             var closeBraceLocation;
90443             var prologue = [];
90444             var statements = [];
90445             var body = node.body;
90446             var statementOffset;
90447             resumeLexicalEnvironment();
90448             if (ts.isBlock(body)) {
90449                 // ensureUseStrict is false because no new prologue-directive should be added.
90450                 // addStandardPrologue will put already-existing directives at the beginning of the target statement-array
90451                 statementOffset = factory.copyStandardPrologue(body.statements, prologue, /*ensureUseStrict*/ false);
90452                 statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, ts.isHoistedFunction);
90453                 statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, ts.isHoistedVariableStatement);
90454             }
90455             multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
90456             multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
90457             if (ts.isBlock(body)) {
90458                 // addCustomPrologue puts already-existing directives at the beginning of the target statement-array
90459                 statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor);
90460                 statementsLocation = body.statements;
90461                 ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
90462                 // If the original body was a multi-line block, this must be a multi-line block.
90463                 if (!multiLine && body.multiLine) {
90464                     multiLine = true;
90465                 }
90466             }
90467             else {
90468                 ts.Debug.assert(node.kind === 209 /* ArrowFunction */);
90469                 // To align with the old emitter, we use a synthetic end position on the location
90470                 // for the statement list we synthesize when we down-level an arrow function with
90471                 // an expression function body. This prevents both comments and source maps from
90472                 // being emitted for the end position only.
90473                 statementsLocation = ts.moveRangeEnd(body, -1);
90474                 var equalsGreaterThanToken = node.equalsGreaterThanToken;
90475                 if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) {
90476                     if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
90477                         singleLine = true;
90478                     }
90479                     else {
90480                         multiLine = true;
90481                     }
90482                 }
90483                 var expression = ts.visitNode(body, visitor, ts.isExpression);
90484                 var returnStatement = factory.createReturnStatement(expression);
90485                 ts.setTextRange(returnStatement, body);
90486                 ts.moveSyntheticComments(returnStatement, body);
90487                 ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
90488                 statements.push(returnStatement);
90489                 // To align with the source map emit for the old emitter, we set a custom
90490                 // source map location for the close brace.
90491                 closeBraceLocation = body;
90492             }
90493             factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
90494             insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
90495             insertCaptureThisForNodeIfNeeded(prologue, node);
90496             // If we added any final generated statements, this must be a multi-line block
90497             if (ts.some(prologue)) {
90498                 multiLine = true;
90499             }
90500             statements.unshift.apply(statements, prologue);
90501             if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
90502                 // no changes were made, preserve the tree
90503                 return body;
90504             }
90505             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), multiLine);
90506             ts.setTextRange(block, node.body);
90507             if (!multiLine && singleLine) {
90508                 ts.setEmitFlags(block, 1 /* SingleLine */);
90509             }
90510             if (closeBraceLocation) {
90511                 ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation);
90512             }
90513             ts.setOriginalNode(block, node.body);
90514             return block;
90515         }
90516         function visitBlock(node, isFunctionBody) {
90517             if (isFunctionBody) {
90518                 // A function body is not a block scope.
90519                 return ts.visitEachChild(node, visitor, context);
90520             }
90521             var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */
90522                 ? enterSubtree(7104 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */)
90523                 : enterSubtree(6976 /* BlockExcludes */, 128 /* BlockIncludes */);
90524             var updated = ts.visitEachChild(node, visitor, context);
90525             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
90526             return updated;
90527         }
90528         /**
90529          * Visits an ExpressionStatement that contains a destructuring assignment.
90530          *
90531          * @param node An ExpressionStatement node.
90532          */
90533         function visitExpressionStatement(node) {
90534             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
90535         }
90536         /**
90537          * Visits a ParenthesizedExpression that may contain a destructuring assignment.
90538          *
90539          * @param node A ParenthesizedExpression node.
90540          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
90541          * expression of an `ExpressionStatement`).
90542          */
90543         function visitParenthesizedExpression(node, expressionResultIsUnused) {
90544             return ts.visitEachChild(node, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, context);
90545         }
90546         /**
90547          * Visits a BinaryExpression that contains a destructuring assignment.
90548          *
90549          * @param node A BinaryExpression node.
90550          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
90551          * expression of an `ExpressionStatement`).
90552          */
90553         function visitBinaryExpression(node, expressionResultIsUnused) {
90554             // If we are here it is because this is a destructuring assignment.
90555             if (ts.isDestructuringAssignment(node)) {
90556                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, !expressionResultIsUnused);
90557             }
90558             if (node.operatorToken.kind === 27 /* CommaToken */) {
90559                 return factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorWithUnusedExpressionResult, ts.isExpression), node.operatorToken, ts.visitNode(node.right, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, ts.isExpression));
90560             }
90561             return ts.visitEachChild(node, visitor, context);
90562         }
90563         /**
90564          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
90565          * expression of an `ExpressionStatement`).
90566          */
90567         function visitCommaListExpression(node, expressionResultIsUnused) {
90568             if (expressionResultIsUnused) {
90569                 return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
90570             }
90571             var result;
90572             for (var i = 0; i < node.elements.length; i++) {
90573                 var element = node.elements[i];
90574                 var visited = ts.visitNode(element, i < node.elements.length - 1 ? visitorWithUnusedExpressionResult : visitor, ts.isExpression);
90575                 if (result || visited !== element) {
90576                     result || (result = node.elements.slice(0, i));
90577                     result.push(visited);
90578                 }
90579             }
90580             var elements = result ? ts.setTextRange(factory.createNodeArray(result), node.elements) : node.elements;
90581             return factory.updateCommaListExpression(node, elements);
90582         }
90583         function isVariableStatementOfTypeScriptClassWrapper(node) {
90584             return node.declarationList.declarations.length === 1
90585                 && !!node.declarationList.declarations[0].initializer
90586                 && !!(ts.getEmitFlags(node.declarationList.declarations[0].initializer) & 33554432 /* TypeScriptClassWrapper */);
90587         }
90588         function visitVariableStatement(node) {
90589             var ancestorFacts = enterSubtree(0 /* None */, ts.hasSyntacticModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
90590             var updated;
90591             if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) {
90592                 // we are inside a converted loop - hoist variable declarations
90593                 var assignments = void 0;
90594                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
90595                     var decl = _a[_i];
90596                     hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
90597                     if (decl.initializer) {
90598                         var assignment = void 0;
90599                         if (ts.isBindingPattern(decl.name)) {
90600                             assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */);
90601                         }
90602                         else {
90603                             assignment = factory.createBinaryExpression(decl.name, 62 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression));
90604                             ts.setTextRange(assignment, decl);
90605                         }
90606                         assignments = ts.append(assignments, assignment);
90607                     }
90608                 }
90609                 if (assignments) {
90610                     updated = ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(assignments)), node);
90611                 }
90612                 else {
90613                     // none of declarations has initializer - the entire variable statement can be deleted
90614                     updated = undefined;
90615                 }
90616             }
90617             else {
90618                 updated = ts.visitEachChild(node, visitor, context);
90619             }
90620             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
90621             return updated;
90622         }
90623         /**
90624          * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`).
90625          *
90626          * @param node A VariableDeclarationList node.
90627          */
90628         function visitVariableDeclarationList(node) {
90629             if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) {
90630                 if (node.flags & 3 /* BlockScoped */) {
90631                     enableSubstitutionsForBlockScopedBindings();
90632                 }
90633                 var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */
90634                     ? visitVariableDeclarationInLetDeclarationList
90635                     : visitVariableDeclaration);
90636                 var declarationList = factory.createVariableDeclarationList(declarations);
90637                 ts.setOriginalNode(declarationList, node);
90638                 ts.setTextRange(declarationList, node);
90639                 ts.setCommentRange(declarationList, node);
90640                 // If the first or last declaration is a binding pattern, we need to modify
90641                 // the source map range for the declaration list.
90642                 if (node.transformFlags & 131072 /* ContainsBindingPattern */
90643                     && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
90644                     ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
90645                 }
90646                 return declarationList;
90647             }
90648             return ts.visitEachChild(node, visitor, context);
90649         }
90650         function getRangeUnion(declarations) {
90651             // declarations may not be sorted by position.
90652             // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes.
90653             var pos = -1, end = -1;
90654             for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
90655                 var node = declarations_10[_i];
90656                 pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
90657                 end = Math.max(end, node.end);
90658             }
90659             return ts.createRange(pos, end);
90660         }
90661         /**
90662          * Gets a value indicating whether we should emit an explicit initializer for a variable
90663          * declaration in a `let` declaration list.
90664          *
90665          * @param node A VariableDeclaration node.
90666          */
90667         function shouldEmitExplicitInitializerForLetDeclaration(node) {
90668             // Nested let bindings might need to be initialized explicitly to preserve
90669             // ES6 semantic:
90670             //
90671             //  { let x = 1; }
90672             //  { let x; } // x here should be undefined. not 1
90673             //
90674             // Top level bindings never collide with anything and thus don't require
90675             // explicit initialization. As for nested let bindings there are two cases:
90676             //
90677             // - Nested let bindings that were not renamed definitely should be
90678             //   initialized explicitly:
90679             //
90680             //    { let x = 1; }
90681             //    { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } }
90682             //
90683             //   Without explicit initialization code in /*1*/ can be executed even if
90684             //   some-condition is evaluated to false.
90685             //
90686             // - Renaming introduces fresh name that should not collide with any
90687             //   existing names, however renamed bindings sometimes also should be
90688             //   explicitly initialized. One particular case: non-captured binding
90689             //   declared inside loop body (but not in loop initializer):
90690             //
90691             //    let x;
90692             //    for (;;) {
90693             //        let x;
90694             //    }
90695             //
90696             //   In downlevel codegen inner 'x' will be renamed so it won't collide
90697             //   with outer 'x' however it will should be reset on every iteration as
90698             //   if it was declared anew.
90699             //
90700             //   * Why non-captured binding?
90701             //     - Because if loop contains block scoped binding captured in some
90702             //       function then loop body will be rewritten to have a fresh scope
90703             //       on every iteration so everything will just work.
90704             //
90705             //   * Why loop initializer is excluded?
90706             //     - Since we've introduced a fresh name it already will be undefined.
90707             var flags = resolver.getNodeCheckFlags(node);
90708             var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */;
90709             var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */;
90710             var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0
90711                 || (isCapturedInFunction
90712                     && isDeclaredInLoop
90713                     && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0);
90714             var emitExplicitInitializer = !emittedAsTopLevel
90715                 && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0
90716                 && (!resolver.isDeclarationWithCollidingName(node)
90717                     || (isDeclaredInLoop
90718                         && !isCapturedInFunction
90719                         && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0));
90720             return emitExplicitInitializer;
90721         }
90722         /**
90723          * Visits a VariableDeclaration in a `let` declaration list.
90724          *
90725          * @param node A VariableDeclaration node.
90726          */
90727         function visitVariableDeclarationInLetDeclarationList(node) {
90728             // For binding pattern names that lack initializers there is no point to emit
90729             // explicit initializer since downlevel codegen for destructuring will fail
90730             // in the absence of initializer so all binding elements will say uninitialized
90731             var name = node.name;
90732             if (ts.isBindingPattern(name)) {
90733                 return visitVariableDeclaration(node);
90734             }
90735             if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) {
90736                 return factory.updateVariableDeclaration(node, node.name, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createVoidZero());
90737             }
90738             return ts.visitEachChild(node, visitor, context);
90739         }
90740         /**
90741          * Visits a VariableDeclaration node with a binding pattern.
90742          *
90743          * @param node A VariableDeclaration node.
90744          */
90745         function visitVariableDeclaration(node) {
90746             var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
90747             var updated;
90748             if (ts.isBindingPattern(node.name)) {
90749                 updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, 
90750                 /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0);
90751             }
90752             else {
90753                 updated = ts.visitEachChild(node, visitor, context);
90754             }
90755             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
90756             return updated;
90757         }
90758         function recordLabel(node) {
90759             convertedLoopState.labels.set(ts.idText(node.label), true);
90760         }
90761         function resetLabel(node) {
90762             convertedLoopState.labels.set(ts.idText(node.label), false);
90763         }
90764         function visitLabeledStatement(node) {
90765             if (convertedLoopState && !convertedLoopState.labels) {
90766                 convertedLoopState.labels = new ts.Map();
90767             }
90768             var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
90769             return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false)
90770                 ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node)
90771                 : factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node, convertedLoopState && resetLabel);
90772         }
90773         function visitIterationStatement(node, outermostLabeledStatement) {
90774             switch (node.kind) {
90775                 case 235 /* DoStatement */:
90776                 case 236 /* WhileStatement */:
90777                     return visitDoOrWhileStatement(node, outermostLabeledStatement);
90778                 case 237 /* ForStatement */:
90779                     return visitForStatement(node, outermostLabeledStatement);
90780                 case 238 /* ForInStatement */:
90781                     return visitForInStatement(node, outermostLabeledStatement);
90782                 case 239 /* ForOfStatement */:
90783                     return visitForOfStatement(node, outermostLabeledStatement);
90784             }
90785         }
90786         function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
90787             var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
90788             var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert);
90789             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
90790             return updated;
90791         }
90792         function visitDoOrWhileStatement(node, outermostLabeledStatement) {
90793             return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 1280 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement);
90794         }
90795         function visitForStatement(node, outermostLabeledStatement) {
90796             return visitIterationStatementWithFacts(5056 /* ForStatementExcludes */, 3328 /* ForStatementIncludes */, node, outermostLabeledStatement);
90797         }
90798         function visitEachChildOfForStatement(node) {
90799             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));
90800         }
90801         function visitForInStatement(node, outermostLabeledStatement) {
90802             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement);
90803         }
90804         function visitForOfStatement(node, outermostLabeledStatement) {
90805             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray);
90806         }
90807         function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
90808             var statements = [];
90809             var initializer = node.initializer;
90810             if (ts.isVariableDeclarationList(initializer)) {
90811                 if (node.initializer.flags & 3 /* BlockScoped */) {
90812                     enableSubstitutionsForBlockScopedBindings();
90813                 }
90814                 var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations);
90815                 if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) {
90816                     // This works whether the declaration is a var, let, or const.
90817                     // It will use rhsIterationValue _a[_i] as the initializer.
90818                     var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue);
90819                     var declarationList = ts.setTextRange(factory.createVariableDeclarationList(declarations), node.initializer);
90820                     ts.setOriginalNode(declarationList, node.initializer);
90821                     // Adjust the source map range for the first declaration to align with the old
90822                     // emitter.
90823                     ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end));
90824                     statements.push(factory.createVariableStatement(
90825                     /*modifiers*/ undefined, declarationList));
90826                 }
90827                 else {
90828                     // The following call does not include the initializer, so we have
90829                     // to emit it separately.
90830                     statements.push(ts.setTextRange(factory.createVariableStatement(
90831                     /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(factory.createVariableDeclarationList([
90832                         factory.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : factory.createTempVariable(/*recordTempVariable*/ undefined), 
90833                         /*exclamationToken*/ undefined, 
90834                         /*type*/ undefined, boundValue)
90835                     ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1)));
90836                 }
90837             }
90838             else {
90839                 // Initializer is an expression. Emit the expression in the body, so that it's
90840                 // evaluated on every iteration.
90841                 var assignment = factory.createAssignment(initializer, boundValue);
90842                 if (ts.isDestructuringAssignment(assignment)) {
90843                     statements.push(factory.createExpressionStatement(visitBinaryExpression(assignment, /*expressionResultIsUnused*/ true)));
90844                 }
90845                 else {
90846                     ts.setTextRangeEnd(assignment, initializer.end);
90847                     statements.push(ts.setTextRange(factory.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1)));
90848                 }
90849             }
90850             if (convertedLoopBodyStatements) {
90851                 return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements));
90852             }
90853             else {
90854                 var statement = ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock);
90855                 if (ts.isBlock(statement)) {
90856                     return factory.updateBlock(statement, ts.setTextRange(factory.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements));
90857                 }
90858                 else {
90859                     statements.push(statement);
90860                     return createSyntheticBlockForConvertedStatements(statements);
90861                 }
90862             }
90863         }
90864         function createSyntheticBlockForConvertedStatements(statements) {
90865             return ts.setEmitFlags(factory.createBlock(factory.createNodeArray(statements), 
90866             /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
90867         }
90868         function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
90869             // The following ES6 code:
90870             //
90871             //    for (let v of expr) { }
90872             //
90873             // should be emitted as
90874             //
90875             //    for (var _i = 0, _a = expr; _i < _a.length; _i++) {
90876             //        var v = _a[_i];
90877             //    }
90878             //
90879             // where _a and _i are temps emitted to capture the RHS and the counter,
90880             // respectively.
90881             // When the left hand side is an expression instead of a let declaration,
90882             // the "let v" is not emitted.
90883             // When the left hand side is a let/const, the v is renamed if there is
90884             // another v in scope.
90885             // Note that all assignments to the LHS are emitted in the body, including
90886             // all destructuring.
90887             // Note also that because an extra statement is needed to assign to the LHS,
90888             // for-of bodies are always emitted as blocks.
90889             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
90890             // In the case where the user wrote an identifier as the RHS, like this:
90891             //
90892             //     for (let v of arr) { }
90893             //
90894             // we don't want to emit a temporary variable for the RHS, just use it directly.
90895             var counter = factory.createLoopVariable();
90896             var rhsReference = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
90897             // The old emitter does not emit source maps for the expression
90898             ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
90899             var forStatement = ts.setTextRange(factory.createForStatement(
90900             /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([
90901                 ts.setTextRange(factory.createVariableDeclaration(counter, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createNumericLiteral(0)), ts.moveRangePos(node.expression, -1)),
90902                 ts.setTextRange(factory.createVariableDeclaration(rhsReference, /*exclamationToken*/ undefined, /*type*/ undefined, expression), node.expression)
90903             ]), node.expression), 2097152 /* NoHoisting */), 
90904             /*condition*/ ts.setTextRange(factory.createLessThan(counter, factory.createPropertyAccessExpression(rhsReference, "length")), node.expression), 
90905             /*incrementor*/ ts.setTextRange(factory.createPostfixIncrement(counter), node.expression), 
90906             /*statement*/ convertForOfStatementHead(node, factory.createElementAccessExpression(rhsReference, counter), convertedLoopBodyStatements)), 
90907             /*location*/ node);
90908             // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
90909             ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */);
90910             ts.setTextRange(forStatement, node);
90911             return factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
90912         }
90913         function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements, ancestorFacts) {
90914             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
90915             var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
90916             var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined);
90917             var errorRecord = factory.createUniqueName("e");
90918             var catchVariable = factory.getGeneratedNameForNode(errorRecord);
90919             var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined);
90920             var values = ts.setTextRange(emitHelpers().createValuesHelper(expression), node.expression);
90921             var next = factory.createCallExpression(factory.createPropertyAccessExpression(iterator, "next"), /*typeArguments*/ undefined, []);
90922             hoistVariableDeclaration(errorRecord);
90923             hoistVariableDeclaration(returnMethod);
90924             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
90925             var initializer = ancestorFacts & 1024 /* IterationContainer */
90926                 ? factory.inlineExpressions([factory.createAssignment(errorRecord, factory.createVoidZero()), values])
90927                 : values;
90928             var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement(
90929             /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([
90930                 ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression),
90931                 factory.createVariableDeclaration(result, /*exclamationToken*/ undefined, /*type*/ undefined, next)
90932             ]), node.expression), 2097152 /* NoHoisting */), 
90933             /*condition*/ factory.createLogicalNot(factory.createPropertyAccessExpression(result, "done")), 
90934             /*incrementor*/ factory.createAssignment(result, next), 
90935             /*statement*/ convertForOfStatementHead(node, factory.createPropertyAccessExpression(result, "value"), convertedLoopBodyStatements)), 
90936             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
90937             return factory.createTryStatement(factory.createBlock([
90938                 factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)
90939             ]), factory.createCatchClause(factory.createVariableDeclaration(catchVariable), ts.setEmitFlags(factory.createBlock([
90940                 factory.createExpressionStatement(factory.createAssignment(errorRecord, factory.createObjectLiteralExpression([
90941                     factory.createPropertyAssignment("error", catchVariable)
90942                 ])))
90943             ]), 1 /* SingleLine */)), factory.createBlock([
90944                 factory.createTryStatement(
90945                 /*tryBlock*/ factory.createBlock([
90946                     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 */),
90947                 ]), 
90948                 /*catchClause*/ undefined, 
90949                 /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([
90950                     ts.setEmitFlags(factory.createIfStatement(errorRecord, factory.createThrowStatement(factory.createPropertyAccessExpression(errorRecord, "error"))), 1 /* SingleLine */)
90951                 ]), 1 /* SingleLine */))
90952             ]));
90953         }
90954         /**
90955          * Visits an ObjectLiteralExpression with computed property names.
90956          *
90957          * @param node An ObjectLiteralExpression node.
90958          */
90959         function visitObjectLiteralExpression(node) {
90960             var properties = node.properties;
90961             // Find the first computed property.
90962             // Everything until that point can be emitted as part of the initial object literal.
90963             var numInitialProperties = -1, hasComputed = false;
90964             for (var i = 0; i < properties.length; i++) {
90965                 var property = properties[i];
90966                 if ((property.transformFlags & 262144 /* ContainsYield */ &&
90967                     hierarchyFacts & 4 /* AsyncFunctionBody */)
90968                     || (hasComputed = ts.Debug.checkDefined(property.name).kind === 158 /* ComputedPropertyName */)) {
90969                     numInitialProperties = i;
90970                     break;
90971                 }
90972             }
90973             if (numInitialProperties < 0) {
90974                 return ts.visitEachChild(node, visitor, context);
90975             }
90976             // For computed properties, we need to create a unique handle to the object
90977             // literal so we can modify it without risking internal assignments tainting the object.
90978             var temp = factory.createTempVariable(hoistVariableDeclaration);
90979             // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
90980             var expressions = [];
90981             var assignment = factory.createAssignment(temp, ts.setEmitFlags(factory.createObjectLiteralExpression(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), hasComputed ? 65536 /* Indented */ : 0));
90982             if (node.multiLine) {
90983                 ts.startOnNewLine(assignment);
90984             }
90985             expressions.push(assignment);
90986             addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
90987             // We need to clone the temporary identifier so that we can write it on a
90988             // new line
90989             expressions.push(node.multiLine ? ts.startOnNewLine(ts.setParent(ts.setTextRange(factory.cloneNode(temp), temp), temp.parent)) : temp);
90990             return factory.inlineExpressions(expressions);
90991         }
90992         function shouldConvertPartOfIterationStatement(node) {
90993             return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0;
90994         }
90995         function shouldConvertInitializerOfForStatement(node) {
90996             return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer);
90997         }
90998         function shouldConvertConditionOfForStatement(node) {
90999             return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition);
91000         }
91001         function shouldConvertIncrementorOfForStatement(node) {
91002             return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
91003         }
91004         function shouldConvertIterationStatement(node) {
91005             return shouldConvertBodyOfIterationStatement(node)
91006                 || shouldConvertInitializerOfForStatement(node);
91007         }
91008         function shouldConvertBodyOfIterationStatement(node) {
91009             return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0;
91010         }
91011         /**
91012          * Records constituents of name for the given variable to be hoisted in the outer scope.
91013          */
91014         function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) {
91015             if (!state.hoistedLocalVariables) {
91016                 state.hoistedLocalVariables = [];
91017             }
91018             visit(node.name);
91019             function visit(node) {
91020                 if (node.kind === 78 /* Identifier */) {
91021                     state.hoistedLocalVariables.push(node);
91022                 }
91023                 else {
91024                     for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
91025                         var element = _a[_i];
91026                         if (!ts.isOmittedExpression(element)) {
91027                             visit(element.name);
91028                         }
91029                     }
91030                 }
91031             }
91032         }
91033         function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert) {
91034             if (!shouldConvertIterationStatement(node)) {
91035                 var saveAllowedNonLabeledJumps = void 0;
91036                 if (convertedLoopState) {
91037                     // we get here if we are trying to emit normal loop loop inside converted loop
91038                     // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is
91039                     saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
91040                     convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
91041                 }
91042                 var result = convert
91043                     ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined, ancestorFacts)
91044                     : factory.restoreEnclosingLabel(ts.isForStatement(node) ? visitEachChildOfForStatement(node) : ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
91045                 if (convertedLoopState) {
91046                     convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
91047                 }
91048                 return result;
91049             }
91050             var currentState = createConvertedLoopState(node);
91051             var statements = [];
91052             var outerConvertedLoopState = convertedLoopState;
91053             convertedLoopState = currentState;
91054             var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined;
91055             var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined;
91056             convertedLoopState = outerConvertedLoopState;
91057             if (initializerFunction)
91058                 statements.push(initializerFunction.functionDeclaration);
91059             if (bodyFunction)
91060                 statements.push(bodyFunction.functionDeclaration);
91061             addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState);
91062             if (initializerFunction) {
91063                 statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield));
91064             }
91065             var loop;
91066             if (bodyFunction) {
91067                 if (convert) {
91068                     loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts);
91069                 }
91070                 else {
91071                     var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true));
91072                     loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel);
91073                 }
91074             }
91075             else {
91076                 var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
91077                 loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel);
91078             }
91079             statements.push(loop);
91080             return statements;
91081         }
91082         function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) {
91083             switch (node.kind) {
91084                 case 237 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody);
91085                 case 238 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody);
91086                 case 239 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody);
91087                 case 235 /* DoStatement */: return convertDoStatement(node, convertedLoopBody);
91088                 case 236 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody);
91089                 default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected");
91090             }
91091         }
91092         function convertForStatement(node, initializerFunction, convertedLoopBody) {
91093             var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition);
91094             var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
91095             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);
91096         }
91097         function convertForOfStatement(node, convertedLoopBody) {
91098             return factory.updateForOfStatement(node, 
91099             /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
91100         }
91101         function convertForInStatement(node, convertedLoopBody) {
91102             return factory.updateForInStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
91103         }
91104         function convertDoStatement(node, convertedLoopBody) {
91105             return factory.updateDoStatement(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression));
91106         }
91107         function convertWhileStatement(node, convertedLoopBody) {
91108             return factory.updateWhileStatement(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
91109         }
91110         function createConvertedLoopState(node) {
91111             var loopInitializer;
91112             switch (node.kind) {
91113                 case 237 /* ForStatement */:
91114                 case 238 /* ForInStatement */:
91115                 case 239 /* ForOfStatement */:
91116                     var initializer = node.initializer;
91117                     if (initializer && initializer.kind === 250 /* VariableDeclarationList */) {
91118                         loopInitializer = initializer;
91119                     }
91120                     break;
91121             }
91122             // variables that will be passed to the loop as parameters
91123             var loopParameters = [];
91124             // variables declared in the loop initializer that will be changed inside the loop
91125             var loopOutParameters = [];
91126             if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) {
91127                 var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node);
91128                 for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) {
91129                     var decl = _a[_i];
91130                     processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
91131                 }
91132             }
91133             var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters };
91134             if (convertedLoopState) {
91135                 // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop.
91136                 // if outer converted loop has already accumulated some state - pass it through
91137                 if (convertedLoopState.argumentsName) {
91138                     // outer loop has already used 'arguments' so we've already have some name to alias it
91139                     // use the same name in all nested loops
91140                     currentState.argumentsName = convertedLoopState.argumentsName;
91141                 }
91142                 if (convertedLoopState.thisName) {
91143                     // outer loop has already used 'this' so we've already have some name to alias it
91144                     // use the same name in all nested loops
91145                     currentState.thisName = convertedLoopState.thisName;
91146                 }
91147                 if (convertedLoopState.hoistedLocalVariables) {
91148                     // we've already collected some non-block scoped variable declarations in enclosing loop
91149                     // use the same storage in nested loop
91150                     currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables;
91151                 }
91152             }
91153             return currentState;
91154         }
91155         function addExtraDeclarationsForConvertedLoop(statements, state, outerState) {
91156             var extraVariableDeclarations;
91157             // propagate state from the inner loop to the outer loop if necessary
91158             if (state.argumentsName) {
91159                 // if alias for arguments is set
91160                 if (outerState) {
91161                     // pass it to outer converted loop
91162                     outerState.argumentsName = state.argumentsName;
91163                 }
91164                 else {
91165                     // this is top level converted loop and we need to create an alias for 'arguments' object
91166                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(factory.createVariableDeclaration(state.argumentsName, 
91167                     /*exclamationToken*/ undefined, 
91168                     /*type*/ undefined, factory.createIdentifier("arguments")));
91169                 }
91170             }
91171             if (state.thisName) {
91172                 // if alias for this is set
91173                 if (outerState) {
91174                     // pass it to outer converted loop
91175                     outerState.thisName = state.thisName;
91176                 }
91177                 else {
91178                     // this is top level converted loop so we need to create an alias for 'this' here
91179                     // NOTE:
91180                     // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
91181                     // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
91182                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(factory.createVariableDeclaration(state.thisName, 
91183                     /*exclamationToken*/ undefined, 
91184                     /*type*/ undefined, factory.createIdentifier("this")));
91185                 }
91186             }
91187             if (state.hoistedLocalVariables) {
91188                 // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
91189                 if (outerState) {
91190                     // pass them to outer converted loop
91191                     outerState.hoistedLocalVariables = state.hoistedLocalVariables;
91192                 }
91193                 else {
91194                     if (!extraVariableDeclarations) {
91195                         extraVariableDeclarations = [];
91196                     }
91197                     // hoist collected variable declarations
91198                     for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) {
91199                         var identifier = _a[_i];
91200                         extraVariableDeclarations.push(factory.createVariableDeclaration(identifier));
91201                     }
91202                 }
91203             }
91204             // add extra variables to hold out parameters if necessary
91205             if (state.loopOutParameters.length) {
91206                 if (!extraVariableDeclarations) {
91207                     extraVariableDeclarations = [];
91208                 }
91209                 for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) {
91210                     var outParam = _c[_b];
91211                     extraVariableDeclarations.push(factory.createVariableDeclaration(outParam.outParamName));
91212                 }
91213             }
91214             if (state.conditionVariable) {
91215                 if (!extraVariableDeclarations) {
91216                     extraVariableDeclarations = [];
91217                 }
91218                 extraVariableDeclarations.push(factory.createVariableDeclaration(state.conditionVariable, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createFalse()));
91219             }
91220             // create variable statement to hold all introduced variable declarations
91221             if (extraVariableDeclarations) {
91222                 statements.push(factory.createVariableStatement(
91223                 /*modifiers*/ undefined, factory.createVariableDeclarationList(extraVariableDeclarations)));
91224             }
91225         }
91226         function createOutVariable(p) {
91227             return factory.createVariableDeclaration(p.originalName, /*exclamationToken*/ undefined, /*type*/ undefined, p.outParamName);
91228         }
91229         /**
91230          * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer
91231          * that is captured in a closure inside of the initializer. The `_loop_init` function is
91232          * used to preserve the per-iteration environment semantics of
91233          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
91234          */
91235         function createFunctionForInitializerOfForStatement(node, currentState) {
91236             var functionName = factory.createUniqueName("_loop_init");
91237             var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0;
91238             var emitFlags = 0 /* None */;
91239             if (currentState.containsLexicalThis)
91240                 emitFlags |= 8 /* CapturesThis */;
91241             if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */)
91242                 emitFlags |= 262144 /* AsyncFunctionBody */;
91243             var statements = [];
91244             statements.push(factory.createVariableStatement(/*modifiers*/ undefined, node.initializer));
91245             copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements);
91246             // This transforms the following ES2015 syntax:
91247             //
91248             //  for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) {
91249             //      // loop body
91250             //  }
91251             //
91252             // Into the following ES5 syntax:
91253             //
91254             //  var _loop_init_1 = function () {
91255             //      var i = (setImmediate(() => console.log(i)), 0);
91256             //      out_i_1 = i;
91257             //  };
91258             //  var out_i_1;
91259             //  _loop_init_1();
91260             //  for (var i = out_i_1; i < 2; i++) {
91261             //      // loop body
91262             //  }
91263             //
91264             // Which prevents mutations to `i` in the per-iteration environment of the body
91265             // from affecting the initial value for `i` outside of the per-iteration environment.
91266             var functionDeclaration = factory.createVariableStatement(
91267             /*modifiers*/ undefined, ts.setEmitFlags(factory.createVariableDeclarationList([
91268                 factory.createVariableDeclaration(functionName, 
91269                 /*exclamationToken*/ undefined, 
91270                 /*type*/ undefined, ts.setEmitFlags(factory.createFunctionExpression(
91271                 /*modifiers*/ undefined, containsYield ? factory.createToken(41 /* AsteriskToken */) : undefined, 
91272                 /*name*/ undefined, 
91273                 /*typeParameters*/ undefined, 
91274                 /*parameters*/ undefined, 
91275                 /*type*/ undefined, ts.visitNode(factory.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags))
91276             ]), 2097152 /* NoHoisting */));
91277             var part = factory.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable));
91278             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
91279         }
91280         /**
91281          * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer
91282          * that is captured in a closure inside of the loop body. The `_loop` function is used to
91283          * preserve the per-iteration environment semantics of
91284          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
91285          */
91286         function createFunctionForBodyOfIterationStatement(node, currentState, outerState) {
91287             var functionName = factory.createUniqueName("_loop");
91288             startLexicalEnvironment();
91289             var statement = ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock);
91290             var lexicalEnvironment = endLexicalEnvironment();
91291             var statements = [];
91292             if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) {
91293                 // If a block-scoped variable declared in the initializer of `node` is captured in
91294                 // the condition or incrementor, we must move the condition and incrementor into
91295                 // the body of the for loop.
91296                 //
91297                 // This transforms the following ES2015 syntax:
91298                 //
91299                 //  for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) {
91300                 //      // loop body
91301                 //  }
91302                 //
91303                 // Into the following ES5 syntax:
91304                 //
91305                 //  var _loop_1 = function (i) {
91306                 //      if (inc_1)
91307                 //          setImmediate(() => console.log(i)), i++;
91308                 //      else
91309                 //          inc_1 = true;
91310                 //      if (!(setImmediate(() => console.log(i)), i < 2))
91311                 //          return out_i_1 = i, "break";
91312                 //      // loop body
91313                 //      out_i_1 = i;
91314                 //  }
91315                 //  var out_i_1, inc_1 = false;
91316                 //  for (var i = 0;;) {
91317                 //      var state_1 = _loop_1(i);
91318                 //      i = out_i_1;
91319                 //      if (state_1 === "break")
91320                 //          break;
91321                 //  }
91322                 //
91323                 // Which prevents mutations to `i` in the per-iteration environment of the body
91324                 // from affecting the value of `i` in the previous per-iteration environment.
91325                 //
91326                 // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration
91327                 // environment that is carried over to the next iteration of the loop. As a result,
91328                 // we must indicate whether this is the first evaluation of the loop body so that
91329                 // we only evaluate the incrementor on subsequent evaluations.
91330                 currentState.conditionVariable = factory.createUniqueName("inc");
91331                 if (node.incrementor) {
91332                     statements.push(factory.createIfStatement(currentState.conditionVariable, factory.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), factory.createExpressionStatement(factory.createAssignment(currentState.conditionVariable, factory.createTrue()))));
91333                 }
91334                 else {
91335                     statements.push(factory.createIfStatement(factory.createLogicalNot(currentState.conditionVariable), factory.createExpressionStatement(factory.createAssignment(currentState.conditionVariable, factory.createTrue()))));
91336                 }
91337                 if (shouldConvertConditionOfForStatement(node)) {
91338                     statements.push(factory.createIfStatement(factory.createPrefixUnaryExpression(53 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(factory.createBreakStatement(), visitor, ts.isStatement)));
91339                 }
91340             }
91341             if (ts.isBlock(statement)) {
91342                 ts.addRange(statements, statement.statements);
91343             }
91344             else {
91345                 statements.push(statement);
91346             }
91347             copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
91348             ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
91349             var loopBody = factory.createBlock(statements, /*multiLine*/ true);
91350             if (ts.isBlock(statement))
91351                 ts.setOriginalNode(loopBody, statement);
91352             var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0;
91353             var emitFlags = 524288 /* ReuseTempVariableScope */;
91354             if (currentState.containsLexicalThis)
91355                 emitFlags |= 8 /* CapturesThis */;
91356             if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0)
91357                 emitFlags |= 262144 /* AsyncFunctionBody */;
91358             // This transforms the following ES2015 syntax (in addition to other variations):
91359             //
91360             //  for (let i = 0; i < 2; i++) {
91361             //      setImmediate(() => console.log(i));
91362             //  }
91363             //
91364             // Into the following ES5 syntax:
91365             //
91366             //  var _loop_1 = function (i) {
91367             //      setImmediate(() => console.log(i));
91368             //  };
91369             //  for (var i = 0; i < 2; i++) {
91370             //      _loop_1(i);
91371             //  }
91372             var functionDeclaration = factory.createVariableStatement(
91373             /*modifiers*/ undefined, ts.setEmitFlags(factory.createVariableDeclarationList([
91374                 factory.createVariableDeclaration(functionName, 
91375                 /*exclamationToken*/ undefined, 
91376                 /*type*/ undefined, ts.setEmitFlags(factory.createFunctionExpression(
91377                 /*modifiers*/ undefined, containsYield ? factory.createToken(41 /* AsteriskToken */) : undefined, 
91378                 /*name*/ undefined, 
91379                 /*typeParameters*/ undefined, currentState.loopParameters, 
91380                 /*type*/ undefined, loopBody), emitFlags))
91381             ]), 2097152 /* NoHoisting */));
91382             var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield);
91383             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
91384         }
91385         function copyOutParameter(outParam, copyDirection) {
91386             var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName;
91387             var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName;
91388             return factory.createBinaryExpression(target, 62 /* EqualsToken */, source);
91389         }
91390         function copyOutParameters(outParams, partFlags, copyDirection, statements) {
91391             for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) {
91392                 var outParam = outParams_1[_i];
91393                 if (outParam.flags & partFlags) {
91394                     statements.push(factory.createExpressionStatement(copyOutParameter(outParam, copyDirection)));
91395                 }
91396             }
91397         }
91398         function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) {
91399             var call = factory.createCallExpression(initFunctionExpressionName, /*typeArguments*/ undefined, []);
91400             var callResult = containsYield
91401                 ? factory.createYieldExpression(factory.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
91402                 : call;
91403             return factory.createExpressionStatement(callResult);
91404         }
91405         function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) {
91406             var statements = [];
91407             // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop
91408             // simple loops are emitted as just 'loop()';
91409             // NOTE: if loop uses only 'continue' it still will be emitted as simple loop
91410             var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) &&
91411                 !state.labeledNonLocalBreaks &&
91412                 !state.labeledNonLocalContinues;
91413             var call = factory.createCallExpression(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; }));
91414             var callResult = containsYield
91415                 ? factory.createYieldExpression(factory.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
91416                 : call;
91417             if (isSimpleLoop) {
91418                 statements.push(factory.createExpressionStatement(callResult));
91419                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
91420             }
91421             else {
91422                 var loopResultName = factory.createUniqueName("state");
91423                 var stateVariable = factory.createVariableStatement(
91424                 /*modifiers*/ undefined, factory.createVariableDeclarationList([factory.createVariableDeclaration(loopResultName, /*exclamationToken*/ undefined, /*type*/ undefined, callResult)]));
91425                 statements.push(stateVariable);
91426                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
91427                 if (state.nonLocalJumps & 8 /* Return */) {
91428                     var returnStatement = void 0;
91429                     if (outerState) {
91430                         outerState.nonLocalJumps |= 8 /* Return */;
91431                         returnStatement = factory.createReturnStatement(loopResultName);
91432                     }
91433                     else {
91434                         returnStatement = factory.createReturnStatement(factory.createPropertyAccessExpression(loopResultName, "value"));
91435                     }
91436                     statements.push(factory.createIfStatement(factory.createTypeCheck(loopResultName, "object"), returnStatement));
91437                 }
91438                 if (state.nonLocalJumps & 2 /* Break */) {
91439                     statements.push(factory.createIfStatement(factory.createStrictEquality(loopResultName, factory.createStringLiteral("break")), factory.createBreakStatement()));
91440                 }
91441                 if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
91442                     var caseClauses = [];
91443                     processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses);
91444                     processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses);
91445                     statements.push(factory.createSwitchStatement(loopResultName, factory.createCaseBlock(caseClauses)));
91446                 }
91447             }
91448             return statements;
91449         }
91450         function setLabeledJump(state, isBreak, labelText, labelMarker) {
91451             if (isBreak) {
91452                 if (!state.labeledNonLocalBreaks) {
91453                     state.labeledNonLocalBreaks = new ts.Map();
91454                 }
91455                 state.labeledNonLocalBreaks.set(labelText, labelMarker);
91456             }
91457             else {
91458                 if (!state.labeledNonLocalContinues) {
91459                     state.labeledNonLocalContinues = new ts.Map();
91460                 }
91461                 state.labeledNonLocalContinues.set(labelText, labelMarker);
91462             }
91463         }
91464         function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
91465             if (!table) {
91466                 return;
91467             }
91468             table.forEach(function (labelMarker, labelText) {
91469                 var statements = [];
91470                 // if there are no outer converted loop or outer label in question is located inside outer converted loop
91471                 // then emit labeled break\continue
91472                 // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
91473                 if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) {
91474                     var label = factory.createIdentifier(labelText);
91475                     statements.push(isBreak ? factory.createBreakStatement(label) : factory.createContinueStatement(label));
91476                 }
91477                 else {
91478                     setLabeledJump(outerLoop, isBreak, labelText, labelMarker);
91479                     statements.push(factory.createReturnStatement(loopResultName));
91480                 }
91481                 caseClauses.push(factory.createCaseClause(factory.createStringLiteral(labelMarker), statements));
91482             });
91483         }
91484         function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) {
91485             var name = decl.name;
91486             if (ts.isBindingPattern(name)) {
91487                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
91488                     var element = _a[_i];
91489                     if (!ts.isOmittedExpression(element)) {
91490                         processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
91491                     }
91492                 }
91493             }
91494             else {
91495                 loopParameters.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
91496                 var checkFlags = resolver.getNodeCheckFlags(decl);
91497                 if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) {
91498                     var outParamName = factory.createUniqueName("out_" + ts.idText(name));
91499                     var flags = 0;
91500                     if (checkFlags & 4194304 /* NeedsLoopOutParameter */) {
91501                         flags |= 1 /* Body */;
91502                     }
91503                     if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
91504                         flags |= 2 /* Initializer */;
91505                     }
91506                     loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName });
91507                 }
91508             }
91509         }
91510         /**
91511          * Adds the members of an object literal to an array of expressions.
91512          *
91513          * @param expressions An array of expressions.
91514          * @param node An ObjectLiteralExpression node.
91515          * @param receiver The receiver for members of the ObjectLiteralExpression.
91516          * @param numInitialNonComputedProperties The number of initial properties without
91517          *                                        computed property names.
91518          */
91519         function addObjectLiteralMembers(expressions, node, receiver, start) {
91520             var properties = node.properties;
91521             var numProperties = properties.length;
91522             for (var i = start; i < numProperties; i++) {
91523                 var property = properties[i];
91524                 switch (property.kind) {
91525                     case 167 /* GetAccessor */:
91526                     case 168 /* SetAccessor */:
91527                         var accessors = ts.getAllAccessorDeclarations(node.properties, property);
91528                         if (property === accessors.firstAccessor) {
91529                             expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
91530                         }
91531                         break;
91532                     case 165 /* MethodDeclaration */:
91533                         expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
91534                         break;
91535                     case 288 /* PropertyAssignment */:
91536                         expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
91537                         break;
91538                     case 289 /* ShorthandPropertyAssignment */:
91539                         expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
91540                         break;
91541                     default:
91542                         ts.Debug.failBadSyntaxKind(node);
91543                         break;
91544                 }
91545             }
91546         }
91547         /**
91548          * Transforms a PropertyAssignment node into an expression.
91549          *
91550          * @param node The ObjectLiteralExpression that contains the PropertyAssignment.
91551          * @param property The PropertyAssignment node.
91552          * @param receiver The receiver for the assignment.
91553          */
91554         function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
91555             var expression = factory.createAssignment(ts.createMemberAccessForPropertyName(factory, receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression));
91556             ts.setTextRange(expression, property);
91557             if (startsOnNewLine) {
91558                 ts.startOnNewLine(expression);
91559             }
91560             return expression;
91561         }
91562         /**
91563          * Transforms a ShorthandPropertyAssignment node into an expression.
91564          *
91565          * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment.
91566          * @param property The ShorthandPropertyAssignment node.
91567          * @param receiver The receiver for the assignment.
91568          */
91569         function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
91570             var expression = factory.createAssignment(ts.createMemberAccessForPropertyName(factory, receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), factory.cloneNode(property.name));
91571             ts.setTextRange(expression, property);
91572             if (startsOnNewLine) {
91573                 ts.startOnNewLine(expression);
91574             }
91575             return expression;
91576         }
91577         /**
91578          * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression.
91579          *
91580          * @param node The ObjectLiteralExpression that contains the MethodDeclaration.
91581          * @param method The MethodDeclaration node.
91582          * @param receiver The receiver for the assignment.
91583          */
91584         function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
91585             var expression = factory.createAssignment(ts.createMemberAccessForPropertyName(factory, receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
91586             ts.setTextRange(expression, method);
91587             if (startsOnNewLine) {
91588                 ts.startOnNewLine(expression);
91589             }
91590             return expression;
91591         }
91592         function visitCatchClause(node) {
91593             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
91594             var updated;
91595             ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
91596             if (ts.isBindingPattern(node.variableDeclaration.name)) {
91597                 var temp = factory.createTempVariable(/*recordTempVariable*/ undefined);
91598                 var newVariableDeclaration = factory.createVariableDeclaration(temp);
91599                 ts.setTextRange(newVariableDeclaration, node.variableDeclaration);
91600                 var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
91601                 var list = factory.createVariableDeclarationList(vars);
91602                 ts.setTextRange(list, node.variableDeclaration);
91603                 var destructure = factory.createVariableStatement(/*modifiers*/ undefined, list);
91604                 updated = factory.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
91605             }
91606             else {
91607                 updated = ts.visitEachChild(node, visitor, context);
91608             }
91609             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
91610             return updated;
91611         }
91612         function addStatementToStartOfBlock(block, statement) {
91613             var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
91614             return factory.updateBlock(block, __spreadArray([statement], transformedStatements));
91615         }
91616         /**
91617          * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
91618          * PropertyAssignment.
91619          *
91620          * @param node A MethodDeclaration node.
91621          */
91622         function visitMethodDeclaration(node) {
91623             // We should only get here for methods on an object literal with regular identifier names.
91624             // Methods on classes are handled in visitClassDeclaration/visitClassExpression.
91625             // Methods with computed property names are handled in visitObjectLiteralExpression.
91626             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
91627             var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined);
91628             ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression));
91629             return ts.setTextRange(factory.createPropertyAssignment(node.name, functionExpression), 
91630             /*location*/ node);
91631         }
91632         /**
91633          * Visits an AccessorDeclaration of an ObjectLiteralExpression.
91634          *
91635          * @param node An AccessorDeclaration node.
91636          */
91637         function visitAccessorDeclaration(node) {
91638             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
91639             var savedConvertedLoopState = convertedLoopState;
91640             convertedLoopState = undefined;
91641             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
91642             var updated;
91643             var parameters = ts.visitParameterList(node.parameters, visitor, context);
91644             var body = transformFunctionBody(node);
91645             if (node.kind === 167 /* GetAccessor */) {
91646                 updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
91647             }
91648             else {
91649                 updated = factory.updateSetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, body);
91650             }
91651             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
91652             convertedLoopState = savedConvertedLoopState;
91653             return updated;
91654         }
91655         /**
91656          * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment.
91657          *
91658          * @param node A ShorthandPropertyAssignment node.
91659          */
91660         function visitShorthandPropertyAssignment(node) {
91661             return ts.setTextRange(factory.createPropertyAssignment(node.name, visitIdentifier(factory.cloneNode(node.name))), 
91662             /*location*/ node);
91663         }
91664         function visitComputedPropertyName(node) {
91665             return ts.visitEachChild(node, visitor, context);
91666         }
91667         /**
91668          * Visits a YieldExpression node.
91669          *
91670          * @param node A YieldExpression node.
91671          */
91672         function visitYieldExpression(node) {
91673             // `yield` expressions are transformed using the generators transformer.
91674             return ts.visitEachChild(node, visitor, context);
91675         }
91676         /**
91677          * Visits an ArrayLiteralExpression that contains a spread element.
91678          *
91679          * @param node An ArrayLiteralExpression node.
91680          */
91681         function visitArrayLiteralExpression(node) {
91682             if (ts.some(node.elements, ts.isSpreadElement)) {
91683                 // We are here because we contain a SpreadElementExpression.
91684                 return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
91685             }
91686             return ts.visitEachChild(node, visitor, context);
91687         }
91688         /**
91689          * Visits a CallExpression that contains either a spread element or `super`.
91690          *
91691          * @param node a CallExpression.
91692          */
91693         function visitCallExpression(node) {
91694             if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
91695                 return visitTypeScriptClassWrapper(node);
91696             }
91697             var expression = ts.skipOuterExpressions(node.expression);
91698             if (expression.kind === 105 /* SuperKeyword */ ||
91699                 ts.isSuperProperty(expression) ||
91700                 ts.some(node.arguments, ts.isSpreadElement)) {
91701                 return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
91702             }
91703             return factory.updateCallExpression(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), 
91704             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
91705         }
91706         function visitTypeScriptClassWrapper(node) {
91707             // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer.
91708             // The wrapper has a form similar to:
91709             //
91710             //  (function() {
91711             //      class C { // 1
91712             //      }
91713             //      C.x = 1; // 2
91714             //      return C;
91715             //  }())
91716             //
91717             // When we transform the class, we end up with something like this:
91718             //
91719             //  (function () {
91720             //      var C = (function () { // 3
91721             //          function C() {
91722             //          }
91723             //          return C; // 4
91724             //      }());
91725             //      C.x = 1;
91726             //      return C;
91727             //  }())
91728             //
91729             // We want to simplify the two nested IIFEs to end up with something like this:
91730             //
91731             //  (function () {
91732             //      function C() {
91733             //      }
91734             //      C.x = 1;
91735             //      return C;
91736             //  }())
91737             // We skip any outer expressions in a number of places to get to the innermost
91738             // expression, but we will restore them later to preserve comments and source maps.
91739             var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
91740             // The class statements are the statements generated by visiting the first statement with initializer of the
91741             // body (1), while all other statements are added to remainingStatements (2)
91742             var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; };
91743             // visit the class body statements outside of any converted loop body.
91744             var savedConvertedLoopState = convertedLoopState;
91745             convertedLoopState = undefined;
91746             var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
91747             convertedLoopState = savedConvertedLoopState;
91748             var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
91749             var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
91750             var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement);
91751             // We know there is only one variable declaration here as we verified this in an
91752             // earlier call to isTypeScriptClassWrapper
91753             var variable = varStatement.declarationList.declarations[0];
91754             var initializer = ts.skipOuterExpressions(variable.initializer);
91755             // Under certain conditions, the 'ts' transformer may introduce a class alias, which
91756             // we see as an assignment, for example:
91757             //
91758             //  (function () {
91759             //      var C_1;
91760             //      var C = C_1 = (function () {
91761             //          function C() {
91762             //          }
91763             //          C.x = function () { return C_1; }
91764             //          return C;
91765             //      }());
91766             //      C = C_1 = __decorate([dec], C);
91767             //      return C;
91768             //  }())
91769             //
91770             var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
91771             // The underlying call (3) is another IIFE that may contain a '_super' argument.
91772             var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression);
91773             var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression);
91774             var funcStatements = func.body.statements;
91775             var classBodyStart = 0;
91776             var classBodyEnd = -1;
91777             var statements = [];
91778             if (aliasAssignment) {
91779                 // If we have a class alias assignment, we need to move it to the down-level constructor
91780                 // function we generated for the class.
91781                 var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement);
91782                 if (extendsCall) {
91783                     statements.push(extendsCall);
91784                     classBodyStart++;
91785                 }
91786                 // The next statement is the function declaration.
91787                 statements.push(funcStatements[classBodyStart]);
91788                 classBodyStart++;
91789                 // Add the class alias following the declaration.
91790                 statements.push(factory.createExpressionStatement(factory.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier))));
91791             }
91792             // Find the trailing 'return' statement (4)
91793             while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) {
91794                 classBodyEnd--;
91795             }
91796             // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4)
91797             // as we already have one that has been introduced by the 'ts' transformer.
91798             ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd);
91799             if (classBodyEnd < -1) {
91800                 // If there were any hoisted declarations following the return statement, we should
91801                 // append them.
91802                 ts.addRange(statements, funcStatements, classBodyEnd + 1);
91803             }
91804             // Add the remaining statements of the outer wrapper.
91805             ts.addRange(statements, remainingStatements);
91806             // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it
91807             // after the remaining statements from the 'ts' transformer.
91808             ts.addRange(statements, classStatements, /*start*/ 1);
91809             // Recreate any outer parentheses or partially-emitted expressions to preserve source map
91810             // and comment locations.
91811             return factory.restoreOuterExpressions(node.expression, factory.restoreOuterExpressions(variable.initializer, factory.restoreOuterExpressions(aliasAssignment && aliasAssignment.right, factory.updateCallExpression(call, factory.restoreOuterExpressions(call.expression, factory.updateFunctionExpression(func, 
91812             /*modifiers*/ undefined, 
91813             /*asteriskToken*/ undefined, 
91814             /*name*/ undefined, 
91815             /*typeParameters*/ undefined, func.parameters, 
91816             /*type*/ undefined, factory.updateBlock(func.body, statements))), 
91817             /*typeArguments*/ undefined, call.arguments))));
91818         }
91819         function visitImmediateSuperCallInBody(node) {
91820             return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
91821         }
91822         function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
91823             // We are here either because SuperKeyword was used somewhere in the expression, or
91824             // because we contain a SpreadElementExpression.
91825             if (node.transformFlags & 8192 /* ContainsRestOrSpread */ ||
91826                 node.expression.kind === 105 /* SuperKeyword */ ||
91827                 ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
91828                 var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
91829                 if (node.expression.kind === 105 /* SuperKeyword */) {
91830                     ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
91831                 }
91832                 var resultingCall = void 0;
91833                 if (node.transformFlags & 8192 /* ContainsRestOrSpread */) {
91834                     // [source]
91835                     //      f(...a, b)
91836                     //      x.m(...a, b)
91837                     //      super(...a, b)
91838                     //      super.m(...a, b) // in static
91839                     //      super.m(...a, b) // in instance
91840                     //
91841                     // [output]
91842                     //      f.apply(void 0, a.concat([b]))
91843                     //      (_a = x).m.apply(_a, a.concat([b]))
91844                     //      _super.apply(this, a.concat([b]))
91845                     //      _super.m.apply(this, a.concat([b]))
91846                     //      _super.prototype.m.apply(this, a.concat([b]))
91847                     resultingCall = factory.createFunctionApplyCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 105 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
91848                 }
91849                 else {
91850                     // [source]
91851                     //      super(a)
91852                     //      super.m(a) // in static
91853                     //      super.m(a) // in instance
91854                     //
91855                     // [output]
91856                     //      _super.call(this, a)
91857                     //      _super.m.call(this, a)
91858                     //      _super.prototype.m.call(this, a)
91859                     resultingCall = ts.setTextRange(factory.createFunctionCallCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 105 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression)), node);
91860                 }
91861                 if (node.expression.kind === 105 /* SuperKeyword */) {
91862                     var initializer = factory.createLogicalOr(resultingCall, createActualThis());
91863                     resultingCall = assignToCapturedThis
91864                         ? factory.createAssignment(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), initializer)
91865                         : initializer;
91866                 }
91867                 return ts.setOriginalNode(resultingCall, node);
91868             }
91869             return ts.visitEachChild(node, visitor, context);
91870         }
91871         /**
91872          * Visits a NewExpression that contains a spread element.
91873          *
91874          * @param node A NewExpression node.
91875          */
91876         function visitNewExpression(node) {
91877             if (ts.some(node.arguments, ts.isSpreadElement)) {
91878                 // We are here because we contain a SpreadElementExpression.
91879                 // [source]
91880                 //      new C(...a)
91881                 //
91882                 // [output]
91883                 //      new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
91884                 var _a = factory.createCallBinding(factory.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
91885                 return factory.createNewExpression(factory.createFunctionApplyCall(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(factory.createNodeArray(__spreadArray([factory.createVoidZero()], node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), 
91886                 /*typeArguments*/ undefined, []);
91887             }
91888             return ts.visitEachChild(node, visitor, context);
91889         }
91890         /**
91891          * Transforms an array of Expression nodes that contains a SpreadExpression.
91892          *
91893          * @param elements The array of Expression nodes.
91894          * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
91895          * This should be `true` when spreading into an `ArrayLiteral`, and `false` when spreading into an
91896          * argument list.
91897          * @param multiLine A value indicating whether the result should be emitted on multiple lines.
91898          */
91899         function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) {
91900             // When there is no leading SpreadElement:
91901             //
91902             // [source]
91903             //      [a, ...b, c]
91904             //
91905             // [output (downlevelIteration)]
91906             //      __spreadArray(__spreadArray([a], __read(b)), [c])
91907             //
91908             // [output]
91909             //      __spreadArray(__spreadArray([a], b), [c])
91910             //
91911             // When there *is* a leading SpreadElement:
91912             //
91913             // [source]
91914             //      [...a, b]
91915             //
91916             // [output (downlevelIteration)]
91917             //      __spreadArray(__spreadArray([], __read(a)), [b])
91918             //
91919             // [output]
91920             //      __spreadArray(__spreadArray([], a), [b])
91921             //
91922             // NOTE: We use `isPackedArrayLiteral` below rather than just `isArrayLiteral`
91923             // because ES2015 spread will replace _missing_ array elements with `undefined`,
91924             // so we cannot just use an array as is. For example:
91925             //
91926             // `[1, ...[2, , 3]]` becomes `[1, 2, undefined, 3]`
91927             //
91928             // However, for packed array literals (i.e., an array literal with no OmittedExpression
91929             // elements), we can use the array as-is.
91930             // Map spans of spread expressions into their expressions and spans of other
91931             // expressions into an array literal.
91932             var numElements = elements.length;
91933             var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
91934                 return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
91935             }));
91936             if (segments.length === 1) {
91937                 var firstSegment = segments[0];
91938                 // If we don't need a unique copy, then we are spreading into an argument list for
91939                 // a CallExpression or NewExpression. When using `--downlevelIteration`, we need
91940                 // to coerce this into an array for use with `apply`, so we will use the code path
91941                 // that follows instead.
91942                 if (!needsUniqueCopy && !compilerOptions.downlevelIteration
91943                     || ts.isPackedArrayLiteral(firstSegment) // see NOTE (above)
91944                     || ts.isCallToHelper(firstSegment, "___spreadArray")) {
91945                     return segments[0];
91946                 }
91947             }
91948             var helpers = emitHelpers();
91949             var startsWithSpread = ts.isSpreadElement(elements[0]);
91950             var expression = startsWithSpread ? factory.createArrayLiteralExpression() :
91951                 segments[0];
91952             for (var i = startsWithSpread ? 0 : 1; i < segments.length; i++) {
91953                 expression = helpers.createSpreadArrayHelper(expression, compilerOptions.downlevelIteration && !ts.isPackedArrayLiteral(segments[i]) ? // see NOTE (above)
91954                     helpers.createReadHelper(segments[i], /*count*/ undefined) :
91955                     segments[i]);
91956             }
91957             return expression;
91958         }
91959         function partitionSpread(node) {
91960             return ts.isSpreadElement(node)
91961                 ? visitSpanOfSpreads
91962                 : visitSpanOfNonSpreads;
91963         }
91964         function visitSpanOfSpreads(chunk) {
91965             return ts.map(chunk, visitExpressionOfSpread);
91966         }
91967         function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
91968             return factory.createArrayLiteralExpression(ts.visitNodes(factory.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine);
91969         }
91970         function visitSpreadElement(node) {
91971             return ts.visitNode(node.expression, visitor, ts.isExpression);
91972         }
91973         /**
91974          * Transforms the expression of a SpreadExpression node.
91975          *
91976          * @param node A SpreadExpression node.
91977          */
91978         function visitExpressionOfSpread(node) {
91979             return ts.visitNode(node.expression, visitor, ts.isExpression);
91980         }
91981         /**
91982          * Visits a template literal.
91983          *
91984          * @param node A template literal.
91985          */
91986         function visitTemplateLiteral(node) {
91987             return ts.setTextRange(factory.createStringLiteral(node.text), node);
91988         }
91989         /**
91990          * Visits a string literal with an extended unicode escape.
91991          *
91992          * @param node A string literal.
91993          */
91994         function visitStringLiteral(node) {
91995             if (node.hasExtendedUnicodeEscape) {
91996                 return ts.setTextRange(factory.createStringLiteral(node.text), node);
91997             }
91998             return node;
91999         }
92000         /**
92001          * Visits a binary or octal (ES6) numeric literal.
92002          *
92003          * @param node A string literal.
92004          */
92005         function visitNumericLiteral(node) {
92006             if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
92007                 return ts.setTextRange(factory.createNumericLiteral(node.text), node);
92008             }
92009             return node;
92010         }
92011         /**
92012          * Visits a TaggedTemplateExpression node.
92013          *
92014          * @param node A TaggedTemplateExpression node.
92015          */
92016         function visitTaggedTemplateExpression(node) {
92017             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.All);
92018         }
92019         /**
92020          * Visits a TemplateExpression node.
92021          *
92022          * @param node A TemplateExpression node.
92023          */
92024         function visitTemplateExpression(node) {
92025             var expressions = [];
92026             addTemplateHead(expressions, node);
92027             addTemplateSpans(expressions, node);
92028             // createAdd will check if each expression binds less closely than binary '+'.
92029             // If it does, it wraps the expression in parentheses. Otherwise, something like
92030             //    `abc${ 1 << 2 }`
92031             // becomes
92032             //    "abc" + 1 << 2 + ""
92033             // which is really
92034             //    ("abc" + 1) << (2 + "")
92035             // rather than
92036             //    "abc" + (1 << 2) + ""
92037             var expression = ts.reduceLeft(expressions, factory.createAdd);
92038             if (ts.nodeIsSynthesized(expression)) {
92039                 ts.setTextRange(expression, node);
92040             }
92041             return expression;
92042         }
92043         /**
92044          * Gets a value indicating whether we need to include the head of a TemplateExpression.
92045          *
92046          * @param node A TemplateExpression node.
92047          */
92048         function shouldAddTemplateHead(node) {
92049             // If this expression has an empty head literal and the first template span has a non-empty
92050             // literal, then emitting the empty head literal is not necessary.
92051             //     `${ foo } and ${ bar }`
92052             // can be emitted as
92053             //     foo + " and " + bar
92054             // This is because it is only required that one of the first two operands in the emit
92055             // output must be a string literal, so that the other operand and all following operands
92056             // are forced into strings.
92057             //
92058             // If the first template span has an empty literal, then the head must still be emitted.
92059             //     `${ foo }${ bar }`
92060             // must still be emitted as
92061             //     "" + foo + bar
92062             // There is always atleast one templateSpan in this code path, since
92063             // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()
92064             ts.Debug.assert(node.templateSpans.length !== 0);
92065             return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;
92066         }
92067         /**
92068          * Adds the head of a TemplateExpression to an array of expressions.
92069          *
92070          * @param expressions An array of expressions.
92071          * @param node A TemplateExpression node.
92072          */
92073         function addTemplateHead(expressions, node) {
92074             if (!shouldAddTemplateHead(node)) {
92075                 return;
92076             }
92077             expressions.push(factory.createStringLiteral(node.head.text));
92078         }
92079         /**
92080          * Visits and adds the template spans of a TemplateExpression to an array of expressions.
92081          *
92082          * @param expressions An array of expressions.
92083          * @param node A TemplateExpression node.
92084          */
92085         function addTemplateSpans(expressions, node) {
92086             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
92087                 var span = _a[_i];
92088                 expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression));
92089                 // Only emit if the literal is non-empty.
92090                 // The binary '+' operator is left-associative, so the first string concatenation
92091                 // with the head will force the result up to this point to be a string.
92092                 // Emitting a '+ ""' has no semantic effect for middles and tails.
92093                 if (span.literal.text.length !== 0) {
92094                     expressions.push(factory.createStringLiteral(span.literal.text));
92095                 }
92096             }
92097         }
92098         /**
92099          * Visits the `super` keyword
92100          */
92101         function visitSuperKeyword(isExpressionOfCall) {
92102             return hierarchyFacts & 8 /* NonStaticClassElement */
92103                 && !isExpressionOfCall
92104                 ? factory.createPropertyAccessExpression(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), "prototype")
92105                 : factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */);
92106         }
92107         function visitMetaProperty(node) {
92108             if (node.keywordToken === 102 /* NewKeyword */ && node.name.escapedText === "target") {
92109                 hierarchyFacts |= 16384 /* NewTarget */;
92110                 return factory.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */);
92111             }
92112             return node;
92113         }
92114         /**
92115          * Called by the printer just before a node is printed.
92116          *
92117          * @param hint A hint as to the intended usage of the node.
92118          * @param node The node to be printed.
92119          * @param emitCallback The callback used to emit the node.
92120          */
92121         function onEmitNode(hint, node, emitCallback) {
92122             if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
92123                 // If we are tracking a captured `this`, keep track of the enclosing function.
92124                 var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
92125                     ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
92126                     : 65 /* FunctionIncludes */);
92127                 previousOnEmitNode(hint, node, emitCallback);
92128                 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
92129                 return;
92130             }
92131             previousOnEmitNode(hint, node, emitCallback);
92132         }
92133         /**
92134          * Enables a more costly code path for substitutions when we determine a source file
92135          * contains block-scoped bindings (e.g. `let` or `const`).
92136          */
92137         function enableSubstitutionsForBlockScopedBindings() {
92138             if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) {
92139                 enabledSubstitutions |= 2 /* BlockScopedBindings */;
92140                 context.enableSubstitution(78 /* Identifier */);
92141             }
92142         }
92143         /**
92144          * Enables a more costly code path for substitutions when we determine a source file
92145          * contains a captured `this`.
92146          */
92147         function enableSubstitutionsForCapturedThis() {
92148             if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
92149                 enabledSubstitutions |= 1 /* CapturedThis */;
92150                 context.enableSubstitution(107 /* ThisKeyword */);
92151                 context.enableEmitNotification(166 /* Constructor */);
92152                 context.enableEmitNotification(165 /* MethodDeclaration */);
92153                 context.enableEmitNotification(167 /* GetAccessor */);
92154                 context.enableEmitNotification(168 /* SetAccessor */);
92155                 context.enableEmitNotification(209 /* ArrowFunction */);
92156                 context.enableEmitNotification(208 /* FunctionExpression */);
92157                 context.enableEmitNotification(251 /* FunctionDeclaration */);
92158             }
92159         }
92160         /**
92161          * Hooks node substitutions.
92162          *
92163          * @param hint The context for the emitter.
92164          * @param node The node to substitute.
92165          */
92166         function onSubstituteNode(hint, node) {
92167             node = previousOnSubstituteNode(hint, node);
92168             if (hint === 1 /* Expression */) {
92169                 return substituteExpression(node);
92170             }
92171             if (ts.isIdentifier(node)) {
92172                 return substituteIdentifier(node);
92173             }
92174             return node;
92175         }
92176         /**
92177          * Hooks substitutions for non-expression identifiers.
92178          */
92179         function substituteIdentifier(node) {
92180             // Only substitute the identifier if we have enabled substitutions for block-scoped
92181             // bindings.
92182             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
92183                 var original = ts.getParseTreeNode(node, ts.isIdentifier);
92184                 if (original && isNameOfDeclarationWithCollidingName(original)) {
92185                     return ts.setTextRange(factory.getGeneratedNameForNode(original), node);
92186                 }
92187             }
92188             return node;
92189         }
92190         /**
92191          * Determines whether a name is the name of a declaration with a colliding name.
92192          * NOTE: This function expects to be called with an original source tree node.
92193          *
92194          * @param node An original source tree node.
92195          */
92196         function isNameOfDeclarationWithCollidingName(node) {
92197             switch (node.parent.kind) {
92198                 case 198 /* BindingElement */:
92199                 case 252 /* ClassDeclaration */:
92200                 case 255 /* EnumDeclaration */:
92201                 case 249 /* VariableDeclaration */:
92202                     return node.parent.name === node
92203                         && resolver.isDeclarationWithCollidingName(node.parent);
92204             }
92205             return false;
92206         }
92207         /**
92208          * Substitutes an expression.
92209          *
92210          * @param node An Expression node.
92211          */
92212         function substituteExpression(node) {
92213             switch (node.kind) {
92214                 case 78 /* Identifier */:
92215                     return substituteExpressionIdentifier(node);
92216                 case 107 /* ThisKeyword */:
92217                     return substituteThisKeyword(node);
92218             }
92219             return node;
92220         }
92221         /**
92222          * Substitutes an expression identifier.
92223          *
92224          * @param node An Identifier node.
92225          */
92226         function substituteExpressionIdentifier(node) {
92227             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
92228                 var declaration = resolver.getReferencedDeclarationWithCollidingName(node);
92229                 if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
92230                     return ts.setTextRange(factory.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node);
92231                 }
92232             }
92233             return node;
92234         }
92235         function isPartOfClassBody(declaration, node) {
92236             var currentNode = ts.getParseTreeNode(node);
92237             if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
92238                 // if the node has no correlation to a parse tree node, its definitely not
92239                 // part of the body.
92240                 // if the node is outside of the document range of the declaration, its
92241                 // definitely not part of the body.
92242                 return false;
92243             }
92244             var blockScope = ts.getEnclosingBlockScopeContainer(declaration);
92245             while (currentNode) {
92246                 if (currentNode === blockScope || currentNode === declaration) {
92247                     // if we are in the enclosing block scope of the declaration, we are definitely
92248                     // not inside the class body.
92249                     return false;
92250                 }
92251                 if (ts.isClassElement(currentNode) && currentNode.parent === declaration) {
92252                     return true;
92253                 }
92254                 currentNode = currentNode.parent;
92255             }
92256             return false;
92257         }
92258         /**
92259          * Substitutes `this` when contained within an arrow function.
92260          *
92261          * @param node The ThisKeyword node.
92262          */
92263         function substituteThisKeyword(node) {
92264             if (enabledSubstitutions & 1 /* CapturedThis */
92265                 && hierarchyFacts & 16 /* CapturesThis */) {
92266                 return ts.setTextRange(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), node);
92267             }
92268             return node;
92269         }
92270         function getClassMemberPrefix(node, member) {
92271             return ts.hasSyntacticModifier(member, 32 /* Static */)
92272                 ? factory.getInternalName(node)
92273                 : factory.createPropertyAccessExpression(factory.getInternalName(node), "prototype");
92274         }
92275         function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) {
92276             if (!constructor || !hasExtendsClause) {
92277                 return false;
92278             }
92279             if (ts.some(constructor.parameters)) {
92280                 return false;
92281             }
92282             var statement = ts.firstOrUndefined(constructor.body.statements);
92283             if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 233 /* ExpressionStatement */) {
92284                 return false;
92285             }
92286             var statementExpression = statement.expression;
92287             if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 203 /* CallExpression */) {
92288                 return false;
92289             }
92290             var callTarget = statementExpression.expression;
92291             if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 105 /* SuperKeyword */) {
92292                 return false;
92293             }
92294             var callArgument = ts.singleOrUndefined(statementExpression.arguments);
92295             if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 220 /* SpreadElement */) {
92296                 return false;
92297             }
92298             var expression = callArgument.expression;
92299             return ts.isIdentifier(expression) && expression.escapedText === "arguments";
92300         }
92301     }
92302     ts.transformES2015 = transformES2015;
92303 })(ts || (ts = {}));
92304 /*@internal*/
92305 var ts;
92306 (function (ts) {
92307     /**
92308      * Transforms ES5 syntax into ES3 syntax.
92309      *
92310      * @param context Context and state information for the transformation.
92311      */
92312     function transformES5(context) {
92313         var factory = context.factory;
92314         var compilerOptions = context.getCompilerOptions();
92315         // enable emit notification only if using --jsx preserve or react-native
92316         var previousOnEmitNode;
92317         var noSubstitution;
92318         if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
92319             previousOnEmitNode = context.onEmitNode;
92320             context.onEmitNode = onEmitNode;
92321             context.enableEmitNotification(275 /* JsxOpeningElement */);
92322             context.enableEmitNotification(276 /* JsxClosingElement */);
92323             context.enableEmitNotification(274 /* JsxSelfClosingElement */);
92324             noSubstitution = [];
92325         }
92326         var previousOnSubstituteNode = context.onSubstituteNode;
92327         context.onSubstituteNode = onSubstituteNode;
92328         context.enableSubstitution(201 /* PropertyAccessExpression */);
92329         context.enableSubstitution(288 /* PropertyAssignment */);
92330         return ts.chainBundle(context, transformSourceFile);
92331         /**
92332          * Transforms an ES5 source file to ES3.
92333          *
92334          * @param node A SourceFile
92335          */
92336         function transformSourceFile(node) {
92337             return node;
92338         }
92339         /**
92340          * Called by the printer just before a node is printed.
92341          *
92342          * @param hint A hint as to the intended usage of the node.
92343          * @param node The node to emit.
92344          * @param emitCallback A callback used to emit the node.
92345          */
92346         function onEmitNode(hint, node, emitCallback) {
92347             switch (node.kind) {
92348                 case 275 /* JsxOpeningElement */:
92349                 case 276 /* JsxClosingElement */:
92350                 case 274 /* JsxSelfClosingElement */:
92351                     var tagName = node.tagName;
92352                     noSubstitution[ts.getOriginalNodeId(tagName)] = true;
92353                     break;
92354             }
92355             previousOnEmitNode(hint, node, emitCallback);
92356         }
92357         /**
92358          * Hooks node substitutions.
92359          *
92360          * @param hint A hint as to the intended usage of the node.
92361          * @param node The node to substitute.
92362          */
92363         function onSubstituteNode(hint, node) {
92364             if (node.id && noSubstitution && noSubstitution[node.id]) {
92365                 return previousOnSubstituteNode(hint, node);
92366             }
92367             node = previousOnSubstituteNode(hint, node);
92368             if (ts.isPropertyAccessExpression(node)) {
92369                 return substitutePropertyAccessExpression(node);
92370             }
92371             else if (ts.isPropertyAssignment(node)) {
92372                 return substitutePropertyAssignment(node);
92373             }
92374             return node;
92375         }
92376         /**
92377          * Substitutes a PropertyAccessExpression whose name is a reserved word.
92378          *
92379          * @param node A PropertyAccessExpression
92380          */
92381         function substitutePropertyAccessExpression(node) {
92382             if (ts.isPrivateIdentifier(node.name)) {
92383                 return node;
92384             }
92385             var literalName = trySubstituteReservedName(node.name);
92386             if (literalName) {
92387                 return ts.setTextRange(factory.createElementAccessExpression(node.expression, literalName), node);
92388             }
92389             return node;
92390         }
92391         /**
92392          * Substitutes a PropertyAssignment whose name is a reserved word.
92393          *
92394          * @param node A PropertyAssignment
92395          */
92396         function substitutePropertyAssignment(node) {
92397             var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
92398             if (literalName) {
92399                 return factory.updatePropertyAssignment(node, literalName, node.initializer);
92400             }
92401             return node;
92402         }
92403         /**
92404          * If an identifier name is a reserved word, returns a string literal for the name.
92405          *
92406          * @param name An Identifier
92407          */
92408         function trySubstituteReservedName(name) {
92409             var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined);
92410             if (token !== undefined && token >= 80 /* FirstReservedWord */ && token <= 115 /* LastReservedWord */) {
92411                 return ts.setTextRange(factory.createStringLiteralFromNode(name), name);
92412             }
92413             return undefined;
92414         }
92415     }
92416     ts.transformES5 = transformES5;
92417 })(ts || (ts = {}));
92418 // Transforms generator functions into a compatible ES5 representation with similar runtime
92419 // semantics. This is accomplished by first transforming the body of each generator
92420 // function into an intermediate representation that is the compiled into a JavaScript
92421 // switch statement.
92422 //
92423 // Many functions in this transformer will contain comments indicating the expected
92424 // intermediate representation. For illustrative purposes, the following intermediate
92425 // language is used to define this intermediate representation:
92426 //
92427 //  .nop                            - Performs no operation.
92428 //  .local NAME, ...                - Define local variable declarations.
92429 //  .mark LABEL                     - Mark the location of a label.
92430 //  .br LABEL                       - Jump to a label. If jumping out of a protected
92431 //                                    region, all .finally blocks are executed.
92432 //  .brtrue LABEL, (x)              - Jump to a label IIF the expression `x` is truthy.
92433 //                                    If jumping out of a protected region, all .finally
92434 //                                    blocks are executed.
92435 //  .brfalse LABEL, (x)             - Jump to a label IIF the expression `x` is falsey.
92436 //                                    If jumping out of a protected region, all .finally
92437 //                                    blocks are executed.
92438 //  .yield (x)                      - Yield the value of the optional expression `x`.
92439 //                                    Resume at the next label.
92440 //  .yieldstar (x)                  - Delegate yield to the value of the optional
92441 //                                    expression `x`. Resume at the next label.
92442 //                                    NOTE: `x` must be an Iterator, not an Iterable.
92443 //  .loop CONTINUE, BREAK           - Marks the beginning of a loop. Any "continue" or
92444 //                                    "break" abrupt completions jump to the CONTINUE or
92445 //                                    BREAK labels, respectively.
92446 //  .endloop                        - Marks the end of a loop.
92447 //  .with (x)                       - Marks the beginning of a WithStatement block, using
92448 //                                    the supplied expression.
92449 //  .endwith                        - Marks the end of a WithStatement.
92450 //  .switch                         - Marks the beginning of a SwitchStatement.
92451 //  .endswitch                      - Marks the end of a SwitchStatement.
92452 //  .labeled NAME                   - Marks the beginning of a LabeledStatement with the
92453 //                                    supplied name.
92454 //  .endlabeled                     - Marks the end of a LabeledStatement.
92455 //  .try TRY, CATCH, FINALLY, END   - Marks the beginning of a protected region, and the
92456 //                                    labels for each block.
92457 //  .catch (x)                      - Marks the beginning of a catch block.
92458 //  .finally                        - Marks the beginning of a finally block.
92459 //  .endfinally                     - Marks the end of a finally block.
92460 //  .endtry                         - Marks the end of a protected region.
92461 //  .throw (x)                      - Throws the value of the expression `x`.
92462 //  .return (x)                     - Returns the value of the expression `x`.
92463 //
92464 // In addition, the illustrative intermediate representation introduces some special
92465 // variables:
92466 //
92467 //  %sent%                          - Either returns the next value sent to the generator,
92468 //                                    returns the result of a delegated yield, or throws
92469 //                                    the exception sent to the generator.
92470 //  %error%                         - Returns the value of the current exception in a
92471 //                                    catch block.
92472 //
92473 // This intermediate representation is then compiled into JavaScript syntax. The resulting
92474 // compilation output looks something like the following:
92475 //
92476 //  function f() {
92477 //      var /*locals*/;
92478 //      /*functions*/
92479 //      return __generator(function (state) {
92480 //          switch (state.label) {
92481 //              /*cases per label*/
92482 //          }
92483 //      });
92484 //  }
92485 //
92486 // Each of the above instructions corresponds to JavaScript emit similar to the following:
92487 //
92488 //  .local NAME                   | var NAME;
92489 // -------------------------------|----------------------------------------------
92490 //  .mark LABEL                   | case LABEL:
92491 // -------------------------------|----------------------------------------------
92492 //  .br LABEL                     |     return [3 /*break*/, LABEL];
92493 // -------------------------------|----------------------------------------------
92494 //  .brtrue LABEL, (x)            |     if (x) return [3 /*break*/, LABEL];
92495 // -------------------------------|----------------------------------------------
92496 //  .brfalse LABEL, (x)           |     if (!(x)) return [3, /*break*/, LABEL];
92497 // -------------------------------|----------------------------------------------
92498 //  .yield (x)                    |     return [4 /*yield*/, x];
92499 //  .mark RESUME                  | case RESUME:
92500 //      a = %sent%;               |     a = state.sent();
92501 // -------------------------------|----------------------------------------------
92502 //  .yieldstar (x)                |     return [5 /*yield**/, x];
92503 //  .mark RESUME                  | case RESUME:
92504 //      a = %sent%;               |     a = state.sent();
92505 // -------------------------------|----------------------------------------------
92506 //  .with (_a)                    |     with (_a) {
92507 //      a();                      |         a();
92508 //                                |     }
92509 //                                |     state.label = LABEL;
92510 //  .mark LABEL                   | case LABEL:
92511 //                                |     with (_a) {
92512 //      b();                      |         b();
92513 //                                |     }
92514 //  .endwith                      |
92515 // -------------------------------|----------------------------------------------
92516 //                                | case 0:
92517 //                                |     state.trys = [];
92518 //                                | ...
92519 //  .try TRY, CATCH, FINALLY, END |
92520 //  .mark TRY                     | case TRY:
92521 //                                |     state.trys.push([TRY, CATCH, FINALLY, END]);
92522 //  .nop                          |
92523 //      a();                      |     a();
92524 //  .br END                       |     return [3 /*break*/, END];
92525 //  .catch (e)                    |
92526 //  .mark CATCH                   | case CATCH:
92527 //                                |     e = state.sent();
92528 //      b();                      |     b();
92529 //  .br END                       |     return [3 /*break*/, END];
92530 //  .finally                      |
92531 //  .mark FINALLY                 | case FINALLY:
92532 //      c();                      |     c();
92533 //  .endfinally                   |     return [7 /*endfinally*/];
92534 //  .endtry                       |
92535 //  .mark END                     | case END:
92536 /*@internal*/
92537 var ts;
92538 (function (ts) {
92539     var OpCode;
92540     (function (OpCode) {
92541         OpCode[OpCode["Nop"] = 0] = "Nop";
92542         OpCode[OpCode["Statement"] = 1] = "Statement";
92543         OpCode[OpCode["Assign"] = 2] = "Assign";
92544         OpCode[OpCode["Break"] = 3] = "Break";
92545         OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue";
92546         OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse";
92547         OpCode[OpCode["Yield"] = 6] = "Yield";
92548         OpCode[OpCode["YieldStar"] = 7] = "YieldStar";
92549         OpCode[OpCode["Return"] = 8] = "Return";
92550         OpCode[OpCode["Throw"] = 9] = "Throw";
92551         OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block
92552     })(OpCode || (OpCode = {}));
92553     // whether a generated code block is opening or closing at the current operation for a FunctionBuilder
92554     var BlockAction;
92555     (function (BlockAction) {
92556         BlockAction[BlockAction["Open"] = 0] = "Open";
92557         BlockAction[BlockAction["Close"] = 1] = "Close";
92558     })(BlockAction || (BlockAction = {}));
92559     // the kind for a generated code block in a FunctionBuilder
92560     var CodeBlockKind;
92561     (function (CodeBlockKind) {
92562         CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception";
92563         CodeBlockKind[CodeBlockKind["With"] = 1] = "With";
92564         CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch";
92565         CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop";
92566         CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled";
92567     })(CodeBlockKind || (CodeBlockKind = {}));
92568     // the state for a generated code exception block
92569     var ExceptionBlockState;
92570     (function (ExceptionBlockState) {
92571         ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try";
92572         ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch";
92573         ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally";
92574         ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done";
92575     })(ExceptionBlockState || (ExceptionBlockState = {}));
92576     // NOTE: changes to this enum should be reflected in the __generator helper.
92577     var Instruction;
92578     (function (Instruction) {
92579         Instruction[Instruction["Next"] = 0] = "Next";
92580         Instruction[Instruction["Throw"] = 1] = "Throw";
92581         Instruction[Instruction["Return"] = 2] = "Return";
92582         Instruction[Instruction["Break"] = 3] = "Break";
92583         Instruction[Instruction["Yield"] = 4] = "Yield";
92584         Instruction[Instruction["YieldStar"] = 5] = "YieldStar";
92585         Instruction[Instruction["Catch"] = 6] = "Catch";
92586         Instruction[Instruction["Endfinally"] = 7] = "Endfinally";
92587     })(Instruction || (Instruction = {}));
92588     function getInstructionName(instruction) {
92589         switch (instruction) {
92590             case 2 /* Return */: return "return";
92591             case 3 /* Break */: return "break";
92592             case 4 /* Yield */: return "yield";
92593             case 5 /* YieldStar */: return "yield*";
92594             case 7 /* Endfinally */: return "endfinally";
92595             default: return undefined; // TODO: GH#18217
92596         }
92597     }
92598     function transformGenerators(context) {
92599         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
92600         var compilerOptions = context.getCompilerOptions();
92601         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
92602         var resolver = context.getEmitResolver();
92603         var previousOnSubstituteNode = context.onSubstituteNode;
92604         context.onSubstituteNode = onSubstituteNode;
92605         var renamedCatchVariables;
92606         var renamedCatchVariableDeclarations;
92607         var inGeneratorFunctionBody;
92608         var inStatementContainingYield;
92609         // The following three arrays store information about generated code blocks.
92610         // All three arrays are correlated by their index. This approach is used over allocating
92611         // objects to store the same information to avoid GC overhead.
92612         //
92613         var blocks; // Information about the code block
92614         var blockOffsets; // The operation offset at which a code block begins or ends
92615         var blockActions; // Whether the code block is opened or closed
92616         var blockStack; // A stack of currently open code blocks
92617         // Labels are used to mark locations in the code that can be the target of a Break (jump)
92618         // operation. These are translated into case clauses in a switch statement.
92619         // The following two arrays are correlated by their index. This approach is used over
92620         // allocating objects to store the same information to avoid GC overhead.
92621         //
92622         var labelOffsets; // The operation offset at which the label is defined.
92623         var labelExpressions; // The NumericLiteral nodes bound to each label.
92624         var nextLabelId = 1; // The next label id to use.
92625         // Operations store information about generated code for the function body. This
92626         // Includes things like statements, assignments, breaks (jumps), and yields.
92627         // The following three arrays are correlated by their index. This approach is used over
92628         // allocating objects to store the same information to avoid GC overhead.
92629         //
92630         var operations; // The operation to perform.
92631         var operationArguments; // The arguments to the operation.
92632         var operationLocations; // The source map location for the operation.
92633         var state; // The name of the state object used by the generator at runtime.
92634         // The following variables store information used by the `build` function:
92635         //
92636         var blockIndex = 0; // The index of the current block.
92637         var labelNumber = 0; // The current label number.
92638         var labelNumbers;
92639         var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue).
92640         var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw).
92641         var clauses; // The case clauses generated for labels.
92642         var statements; // The statements for the current label.
92643         var exceptionBlockStack; // A stack of containing exception blocks.
92644         var currentExceptionBlock; // The current exception block.
92645         var withBlockStack; // A stack containing `with` blocks.
92646         return ts.chainBundle(context, transformSourceFile);
92647         function transformSourceFile(node) {
92648             if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
92649                 return node;
92650             }
92651             var visited = ts.visitEachChild(node, visitor, context);
92652             ts.addEmitHelpers(visited, context.readEmitHelpers());
92653             return visited;
92654         }
92655         /**
92656          * Visits a node.
92657          *
92658          * @param node The node to visit.
92659          */
92660         function visitor(node) {
92661             var transformFlags = node.transformFlags;
92662             if (inStatementContainingYield) {
92663                 return visitJavaScriptInStatementContainingYield(node);
92664             }
92665             else if (inGeneratorFunctionBody) {
92666                 return visitJavaScriptInGeneratorFunctionBody(node);
92667             }
92668             else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
92669                 return visitGenerator(node);
92670             }
92671             else if (transformFlags & 512 /* ContainsGenerator */) {
92672                 return ts.visitEachChild(node, visitor, context);
92673             }
92674             else {
92675                 return node;
92676             }
92677         }
92678         /**
92679          * Visits a node that is contained within a statement that contains yield.
92680          *
92681          * @param node The node to visit.
92682          */
92683         function visitJavaScriptInStatementContainingYield(node) {
92684             switch (node.kind) {
92685                 case 235 /* DoStatement */:
92686                     return visitDoStatement(node);
92687                 case 236 /* WhileStatement */:
92688                     return visitWhileStatement(node);
92689                 case 244 /* SwitchStatement */:
92690                     return visitSwitchStatement(node);
92691                 case 245 /* LabeledStatement */:
92692                     return visitLabeledStatement(node);
92693                 default:
92694                     return visitJavaScriptInGeneratorFunctionBody(node);
92695             }
92696         }
92697         /**
92698          * Visits a node that is contained within a generator function.
92699          *
92700          * @param node The node to visit.
92701          */
92702         function visitJavaScriptInGeneratorFunctionBody(node) {
92703             switch (node.kind) {
92704                 case 251 /* FunctionDeclaration */:
92705                     return visitFunctionDeclaration(node);
92706                 case 208 /* FunctionExpression */:
92707                     return visitFunctionExpression(node);
92708                 case 167 /* GetAccessor */:
92709                 case 168 /* SetAccessor */:
92710                     return visitAccessorDeclaration(node);
92711                 case 232 /* VariableStatement */:
92712                     return visitVariableStatement(node);
92713                 case 237 /* ForStatement */:
92714                     return visitForStatement(node);
92715                 case 238 /* ForInStatement */:
92716                     return visitForInStatement(node);
92717                 case 241 /* BreakStatement */:
92718                     return visitBreakStatement(node);
92719                 case 240 /* ContinueStatement */:
92720                     return visitContinueStatement(node);
92721                 case 242 /* ReturnStatement */:
92722                     return visitReturnStatement(node);
92723                 default:
92724                     if (node.transformFlags & 262144 /* ContainsYield */) {
92725                         return visitJavaScriptContainingYield(node);
92726                     }
92727                     else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) {
92728                         return ts.visitEachChild(node, visitor, context);
92729                     }
92730                     else {
92731                         return node;
92732                     }
92733             }
92734         }
92735         /**
92736          * Visits a node that contains a YieldExpression.
92737          *
92738          * @param node The node to visit.
92739          */
92740         function visitJavaScriptContainingYield(node) {
92741             switch (node.kind) {
92742                 case 216 /* BinaryExpression */:
92743                     return visitBinaryExpression(node);
92744                 case 337 /* CommaListExpression */:
92745                     return visitCommaListExpression(node);
92746                 case 217 /* ConditionalExpression */:
92747                     return visitConditionalExpression(node);
92748                 case 219 /* YieldExpression */:
92749                     return visitYieldExpression(node);
92750                 case 199 /* ArrayLiteralExpression */:
92751                     return visitArrayLiteralExpression(node);
92752                 case 200 /* ObjectLiteralExpression */:
92753                     return visitObjectLiteralExpression(node);
92754                 case 202 /* ElementAccessExpression */:
92755                     return visitElementAccessExpression(node);
92756                 case 203 /* CallExpression */:
92757                     return visitCallExpression(node);
92758                 case 204 /* NewExpression */:
92759                     return visitNewExpression(node);
92760                 default:
92761                     return ts.visitEachChild(node, visitor, context);
92762             }
92763         }
92764         /**
92765          * Visits a generator function.
92766          *
92767          * @param node The node to visit.
92768          */
92769         function visitGenerator(node) {
92770             switch (node.kind) {
92771                 case 251 /* FunctionDeclaration */:
92772                     return visitFunctionDeclaration(node);
92773                 case 208 /* FunctionExpression */:
92774                     return visitFunctionExpression(node);
92775                 default:
92776                     return ts.Debug.failBadSyntaxKind(node);
92777             }
92778         }
92779         /**
92780          * Visits a function declaration.
92781          *
92782          * This will be called when one of the following conditions are met:
92783          * - The function declaration is a generator function.
92784          * - The function declaration is contained within the body of a generator function.
92785          *
92786          * @param node The node to visit.
92787          */
92788         function visitFunctionDeclaration(node) {
92789             // Currently, we only support generators that were originally async functions.
92790             if (node.asteriskToken) {
92791                 node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(
92792                 /*decorators*/ undefined, node.modifiers, 
92793                 /*asteriskToken*/ undefined, node.name, 
92794                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
92795                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
92796                 /*location*/ node), node);
92797             }
92798             else {
92799                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
92800                 var savedInStatementContainingYield = inStatementContainingYield;
92801                 inGeneratorFunctionBody = false;
92802                 inStatementContainingYield = false;
92803                 node = ts.visitEachChild(node, visitor, context);
92804                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
92805                 inStatementContainingYield = savedInStatementContainingYield;
92806             }
92807             if (inGeneratorFunctionBody) {
92808                 // Function declarations in a generator function body are hoisted
92809                 // to the top of the lexical scope and elided from the current statement.
92810                 hoistFunctionDeclaration(node);
92811                 return undefined;
92812             }
92813             else {
92814                 return node;
92815             }
92816         }
92817         /**
92818          * Visits a function expression.
92819          *
92820          * This will be called when one of the following conditions are met:
92821          * - The function expression is a generator function.
92822          * - The function expression is contained within the body of a generator function.
92823          *
92824          * @param node The node to visit.
92825          */
92826         function visitFunctionExpression(node) {
92827             // Currently, we only support generators that were originally async functions.
92828             if (node.asteriskToken) {
92829                 node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(
92830                 /*modifiers*/ undefined, 
92831                 /*asteriskToken*/ undefined, node.name, 
92832                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
92833                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
92834                 /*location*/ node), node);
92835             }
92836             else {
92837                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
92838                 var savedInStatementContainingYield = inStatementContainingYield;
92839                 inGeneratorFunctionBody = false;
92840                 inStatementContainingYield = false;
92841                 node = ts.visitEachChild(node, visitor, context);
92842                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
92843                 inStatementContainingYield = savedInStatementContainingYield;
92844             }
92845             return node;
92846         }
92847         /**
92848          * Visits a get or set accessor declaration.
92849          *
92850          * This will be called when one of the following conditions are met:
92851          * - The accessor is contained within the body of a generator function.
92852          *
92853          * @param node The node to visit.
92854          */
92855         function visitAccessorDeclaration(node) {
92856             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
92857             var savedInStatementContainingYield = inStatementContainingYield;
92858             inGeneratorFunctionBody = false;
92859             inStatementContainingYield = false;
92860             node = ts.visitEachChild(node, visitor, context);
92861             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
92862             inStatementContainingYield = savedInStatementContainingYield;
92863             return node;
92864         }
92865         /**
92866          * Transforms the body of a generator function declaration.
92867          *
92868          * @param node The function body to transform.
92869          */
92870         function transformGeneratorFunctionBody(body) {
92871             // Save existing generator state
92872             var statements = [];
92873             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
92874             var savedInStatementContainingYield = inStatementContainingYield;
92875             var savedBlocks = blocks;
92876             var savedBlockOffsets = blockOffsets;
92877             var savedBlockActions = blockActions;
92878             var savedBlockStack = blockStack;
92879             var savedLabelOffsets = labelOffsets;
92880             var savedLabelExpressions = labelExpressions;
92881             var savedNextLabelId = nextLabelId;
92882             var savedOperations = operations;
92883             var savedOperationArguments = operationArguments;
92884             var savedOperationLocations = operationLocations;
92885             var savedState = state;
92886             // Initialize generator state
92887             inGeneratorFunctionBody = true;
92888             inStatementContainingYield = false;
92889             blocks = undefined;
92890             blockOffsets = undefined;
92891             blockActions = undefined;
92892             blockStack = undefined;
92893             labelOffsets = undefined;
92894             labelExpressions = undefined;
92895             nextLabelId = 1;
92896             operations = undefined;
92897             operationArguments = undefined;
92898             operationLocations = undefined;
92899             state = factory.createTempVariable(/*recordTempVariable*/ undefined);
92900             // Build the generator
92901             resumeLexicalEnvironment();
92902             var statementOffset = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor);
92903             transformAndEmitStatements(body.statements, statementOffset);
92904             var buildResult = build();
92905             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
92906             statements.push(factory.createReturnStatement(buildResult));
92907             // Restore previous generator state
92908             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
92909             inStatementContainingYield = savedInStatementContainingYield;
92910             blocks = savedBlocks;
92911             blockOffsets = savedBlockOffsets;
92912             blockActions = savedBlockActions;
92913             blockStack = savedBlockStack;
92914             labelOffsets = savedLabelOffsets;
92915             labelExpressions = savedLabelExpressions;
92916             nextLabelId = savedNextLabelId;
92917             operations = savedOperations;
92918             operationArguments = savedOperationArguments;
92919             operationLocations = savedOperationLocations;
92920             state = savedState;
92921             return ts.setTextRange(factory.createBlock(statements, body.multiLine), body);
92922         }
92923         /**
92924          * Visits a variable statement.
92925          *
92926          * This will be called when one of the following conditions are met:
92927          * - The variable statement is contained within the body of a generator function.
92928          *
92929          * @param node The node to visit.
92930          */
92931         function visitVariableStatement(node) {
92932             if (node.transformFlags & 262144 /* ContainsYield */) {
92933                 transformAndEmitVariableDeclarationList(node.declarationList);
92934                 return undefined;
92935             }
92936             else {
92937                 // Do not hoist custom prologues.
92938                 if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) {
92939                     return node;
92940                 }
92941                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
92942                     var variable = _a[_i];
92943                     hoistVariableDeclaration(variable.name);
92944                 }
92945                 var variables = ts.getInitializedVariables(node.declarationList);
92946                 if (variables.length === 0) {
92947                     return undefined;
92948                 }
92949                 return ts.setSourceMapRange(factory.createExpressionStatement(factory.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
92950             }
92951         }
92952         /**
92953          * Visits a binary expression.
92954          *
92955          * This will be called when one of the following conditions are met:
92956          * - The node contains a YieldExpression.
92957          *
92958          * @param node The node to visit.
92959          */
92960         function visitBinaryExpression(node) {
92961             var assoc = ts.getExpressionAssociativity(node);
92962             switch (assoc) {
92963                 case 0 /* Left */:
92964                     return visitLeftAssociativeBinaryExpression(node);
92965                 case 1 /* Right */:
92966                     return visitRightAssociativeBinaryExpression(node);
92967                 default:
92968                     return ts.Debug.assertNever(assoc);
92969             }
92970         }
92971         /**
92972          * Visits a right-associative binary expression containing `yield`.
92973          *
92974          * @param node The node to visit.
92975          */
92976         function visitRightAssociativeBinaryExpression(node) {
92977             var left = node.left, right = node.right;
92978             if (containsYield(right)) {
92979                 var target = void 0;
92980                 switch (left.kind) {
92981                     case 201 /* PropertyAccessExpression */:
92982                         // [source]
92983                         //      a.b = yield;
92984                         //
92985                         // [intermediate]
92986                         //  .local _a
92987                         //      _a = a;
92988                         //  .yield resumeLabel
92989                         //  .mark resumeLabel
92990                         //      _a.b = %sent%;
92991                         target = factory.updatePropertyAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name);
92992                         break;
92993                     case 202 /* ElementAccessExpression */:
92994                         // [source]
92995                         //      a[b] = yield;
92996                         //
92997                         // [intermediate]
92998                         //  .local _a, _b
92999                         //      _a = a;
93000                         //      _b = b;
93001                         //  .yield resumeLabel
93002                         //  .mark resumeLabel
93003                         //      _a[_b] = %sent%;
93004                         target = factory.updateElementAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression)));
93005                         break;
93006                     default:
93007                         target = ts.visitNode(left, visitor, ts.isExpression);
93008                         break;
93009                 }
93010                 var operator = node.operatorToken.kind;
93011                 if (ts.isCompoundAssignment(operator)) {
93012                     return ts.setTextRange(factory.createAssignment(target, ts.setTextRange(factory.createBinaryExpression(cacheExpression(target), ts.getNonAssignmentOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node);
93013                 }
93014                 else {
93015                     return factory.updateBinaryExpression(node, target, node.operatorToken, ts.visitNode(right, visitor, ts.isExpression));
93016                 }
93017             }
93018             return ts.visitEachChild(node, visitor, context);
93019         }
93020         function visitLeftAssociativeBinaryExpression(node) {
93021             if (containsYield(node.right)) {
93022                 if (ts.isLogicalOperator(node.operatorToken.kind)) {
93023                     return visitLogicalBinaryExpression(node);
93024                 }
93025                 else if (node.operatorToken.kind === 27 /* CommaToken */) {
93026                     return visitCommaExpression(node);
93027                 }
93028                 // [source]
93029                 //      a() + (yield) + c()
93030                 //
93031                 // [intermediate]
93032                 //  .local _a
93033                 //      _a = a();
93034                 //  .yield resumeLabel
93035                 //      _a + %sent% + c()
93036                 return factory.updateBinaryExpression(node, cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)), node.operatorToken, ts.visitNode(node.right, visitor, ts.isExpression));
93037             }
93038             return ts.visitEachChild(node, visitor, context);
93039         }
93040         /**
93041          * Visits a comma expression containing `yield`.
93042          *
93043          * @param node The node to visit.
93044          */
93045         function visitCommaExpression(node) {
93046             // [source]
93047             //      x = a(), yield, b();
93048             //
93049             // [intermediate]
93050             //      a();
93051             //  .yield resumeLabel
93052             //  .mark resumeLabel
93053             //      x = %sent%, b();
93054             var pendingExpressions = [];
93055             visit(node.left);
93056             visit(node.right);
93057             return factory.inlineExpressions(pendingExpressions);
93058             function visit(node) {
93059                 if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
93060                     visit(node.left);
93061                     visit(node.right);
93062                 }
93063                 else {
93064                     if (containsYield(node) && pendingExpressions.length > 0) {
93065                         emitWorker(1 /* Statement */, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]);
93066                         pendingExpressions = [];
93067                     }
93068                     pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression));
93069                 }
93070             }
93071         }
93072         /**
93073          * Visits a comma-list expression.
93074          *
93075          * @param node The node to visit.
93076          */
93077         function visitCommaListExpression(node) {
93078             // flattened version of `visitCommaExpression`
93079             var pendingExpressions = [];
93080             for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
93081                 var elem = _a[_i];
93082                 if (ts.isBinaryExpression(elem) && elem.operatorToken.kind === 27 /* CommaToken */) {
93083                     pendingExpressions.push(visitCommaExpression(elem));
93084                 }
93085                 else {
93086                     if (containsYield(elem) && pendingExpressions.length > 0) {
93087                         emitWorker(1 /* Statement */, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]);
93088                         pendingExpressions = [];
93089                     }
93090                     pendingExpressions.push(ts.visitNode(elem, visitor, ts.isExpression));
93091                 }
93092             }
93093             return factory.inlineExpressions(pendingExpressions);
93094         }
93095         /**
93096          * Visits a logical binary expression containing `yield`.
93097          *
93098          * @param node A node to visit.
93099          */
93100         function visitLogicalBinaryExpression(node) {
93101             // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need
93102             // to be transformed as such:
93103             //
93104             // [source]
93105             //      x = a() && yield;
93106             //
93107             // [intermediate]
93108             //  .local _a
93109             //      _a = a();
93110             //  .brfalse resultLabel, (_a)
93111             //  .yield resumeLabel
93112             //  .mark resumeLabel
93113             //      _a = %sent%;
93114             //  .mark resultLabel
93115             //      x = _a;
93116             //
93117             // [source]
93118             //      x = a() || yield;
93119             //
93120             // [intermediate]
93121             //  .local _a
93122             //      _a = a();
93123             //  .brtrue resultLabel, (_a)
93124             //  .yield resumeLabel
93125             //  .mark resumeLabel
93126             //      _a = %sent%;
93127             //  .mark resultLabel
93128             //      x = _a;
93129             var resultLabel = defineLabel();
93130             var resultLocal = declareLocal();
93131             emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left);
93132             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
93133                 // Logical `&&` shortcuts when the left-hand operand is falsey.
93134                 emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left);
93135             }
93136             else {
93137                 // Logical `||` shortcuts when the left-hand operand is truthy.
93138                 emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left);
93139             }
93140             emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right);
93141             markLabel(resultLabel);
93142             return resultLocal;
93143         }
93144         /**
93145          * Visits a conditional expression containing `yield`.
93146          *
93147          * @param node The node to visit.
93148          */
93149         function visitConditionalExpression(node) {
93150             // [source]
93151             //      x = a() ? yield : b();
93152             //
93153             // [intermediate]
93154             //  .local _a
93155             //  .brfalse whenFalseLabel, (a())
93156             //  .yield resumeLabel
93157             //  .mark resumeLabel
93158             //      _a = %sent%;
93159             //  .br resultLabel
93160             //  .mark whenFalseLabel
93161             //      _a = b();
93162             //  .mark resultLabel
93163             //      x = _a;
93164             // We only need to perform a specific transformation if a `yield` expression exists
93165             // in either the `whenTrue` or `whenFalse` branches.
93166             // A `yield` in the condition will be handled by the normal visitor.
93167             if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
93168                 var whenFalseLabel = defineLabel();
93169                 var resultLabel = defineLabel();
93170                 var resultLocal = declareLocal();
93171                 emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition);
93172                 emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue);
93173                 emitBreak(resultLabel);
93174                 markLabel(whenFalseLabel);
93175                 emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse);
93176                 markLabel(resultLabel);
93177                 return resultLocal;
93178             }
93179             return ts.visitEachChild(node, visitor, context);
93180         }
93181         /**
93182          * Visits a `yield` expression.
93183          *
93184          * @param node The node to visit.
93185          */
93186         function visitYieldExpression(node) {
93187             // [source]
93188             //      x = yield a();
93189             //
93190             // [intermediate]
93191             //  .yield resumeLabel, (a())
93192             //  .mark resumeLabel
93193             //      x = %sent%;
93194             var resumeLabel = defineLabel();
93195             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
93196             if (node.asteriskToken) {
93197                 // NOTE: `expression` must be defined for `yield*`.
93198                 var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0
93199                     ? ts.setTextRange(emitHelpers().createValuesHelper(expression), node)
93200                     : expression;
93201                 emitYieldStar(iterator, /*location*/ node);
93202             }
93203             else {
93204                 emitYield(expression, /*location*/ node);
93205             }
93206             markLabel(resumeLabel);
93207             return createGeneratorResume(/*location*/ node);
93208         }
93209         /**
93210          * Visits an ArrayLiteralExpression that contains a YieldExpression.
93211          *
93212          * @param node The node to visit.
93213          */
93214         function visitArrayLiteralExpression(node) {
93215             return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
93216         }
93217         /**
93218          * Visits an array of expressions containing one or more YieldExpression nodes
93219          * and returns an expression for the resulting value.
93220          *
93221          * @param elements The elements to visit.
93222          * @param multiLine Whether array literals created should be emitted on multiple lines.
93223          */
93224         function visitElements(elements, leadingElement, location, multiLine) {
93225             // [source]
93226             //      ar = [1, yield, 2];
93227             //
93228             // [intermediate]
93229             //  .local _a
93230             //      _a = [1];
93231             //  .yield resumeLabel
93232             //  .mark resumeLabel
93233             //      ar = _a.concat([%sent%, 2]);
93234             var numInitialElements = countInitialNodesWithoutYield(elements);
93235             var temp;
93236             if (numInitialElements > 0) {
93237                 temp = declareLocal();
93238                 var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
93239                 emitAssignment(temp, factory.createArrayLiteralExpression(leadingElement
93240                     ? __spreadArray([leadingElement], initialElements) : initialElements));
93241                 leadingElement = undefined;
93242             }
93243             var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
93244             return temp
93245                 ? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)])
93246                 : ts.setTextRange(factory.createArrayLiteralExpression(leadingElement ? __spreadArray([leadingElement], expressions) : expressions, multiLine), location);
93247             function reduceElement(expressions, element) {
93248                 if (containsYield(element) && expressions.length > 0) {
93249                     var hasAssignedTemp = temp !== undefined;
93250                     if (!temp) {
93251                         temp = declareLocal();
93252                     }
93253                     emitAssignment(temp, hasAssignedTemp
93254                         ? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)])
93255                         : factory.createArrayLiteralExpression(leadingElement ? __spreadArray([leadingElement], expressions) : expressions, multiLine));
93256                     leadingElement = undefined;
93257                     expressions = [];
93258                 }
93259                 expressions.push(ts.visitNode(element, visitor, ts.isExpression));
93260                 return expressions;
93261             }
93262         }
93263         function visitObjectLiteralExpression(node) {
93264             // [source]
93265             //      o = {
93266             //          a: 1,
93267             //          b: yield,
93268             //          c: 2
93269             //      };
93270             //
93271             // [intermediate]
93272             //  .local _a
93273             //      _a = {
93274             //          a: 1
93275             //      };
93276             //  .yield resumeLabel
93277             //  .mark resumeLabel
93278             //      o = (_a.b = %sent%,
93279             //          _a.c = 2,
93280             //          _a);
93281             var properties = node.properties;
93282             var multiLine = node.multiLine;
93283             var numInitialProperties = countInitialNodesWithoutYield(properties);
93284             var temp = declareLocal();
93285             emitAssignment(temp, factory.createObjectLiteralExpression(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine));
93286             var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties);
93287             // TODO(rbuckton): Does this need to be parented?
93288             expressions.push(multiLine ? ts.startOnNewLine(ts.setParent(ts.setTextRange(factory.cloneNode(temp), temp), temp.parent)) : temp);
93289             return factory.inlineExpressions(expressions);
93290             function reduceProperty(expressions, property) {
93291                 if (containsYield(property) && expressions.length > 0) {
93292                     emitStatement(factory.createExpressionStatement(factory.inlineExpressions(expressions)));
93293                     expressions = [];
93294                 }
93295                 var expression = ts.createExpressionForObjectLiteralElementLike(factory, node, property, temp);
93296                 var visited = ts.visitNode(expression, visitor, ts.isExpression);
93297                 if (visited) {
93298                     if (multiLine) {
93299                         ts.startOnNewLine(visited);
93300                     }
93301                     expressions.push(visited);
93302                 }
93303                 return expressions;
93304             }
93305         }
93306         /**
93307          * Visits an ElementAccessExpression that contains a YieldExpression.
93308          *
93309          * @param node The node to visit.
93310          */
93311         function visitElementAccessExpression(node) {
93312             if (containsYield(node.argumentExpression)) {
93313                 // [source]
93314                 //      a = x[yield];
93315                 //
93316                 // [intermediate]
93317                 //  .local _a
93318                 //      _a = x;
93319                 //  .yield resumeLabel
93320                 //  .mark resumeLabel
93321                 //      a = _a[%sent%]
93322                 return factory.updateElementAccessExpression(node, cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)), ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
93323             }
93324             return ts.visitEachChild(node, visitor, context);
93325         }
93326         function visitCallExpression(node) {
93327             if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) {
93328                 // [source]
93329                 //      a.b(1, yield, 2);
93330                 //
93331                 // [intermediate]
93332                 //  .local _a, _b, _c
93333                 //      _b = (_a = a).b;
93334                 //      _c = [1];
93335                 //  .yield resumeLabel
93336                 //  .mark resumeLabel
93337                 //      _b.apply(_a, _c.concat([%sent%, 2]));
93338                 var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg;
93339                 return ts.setOriginalNode(ts.setTextRange(factory.createFunctionApplyCall(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments)), node), node);
93340             }
93341             return ts.visitEachChild(node, visitor, context);
93342         }
93343         function visitNewExpression(node) {
93344             if (ts.forEach(node.arguments, containsYield)) {
93345                 // [source]
93346                 //      new a.b(1, yield, 2);
93347                 //
93348                 // [intermediate]
93349                 //  .local _a, _b, _c
93350                 //      _b = (_a = a.b).bind;
93351                 //      _c = [1];
93352                 //  .yield resumeLabel
93353                 //  .mark resumeLabel
93354                 //      new (_b.apply(_a, _c.concat([%sent%, 2])));
93355                 var _a = factory.createCallBinding(factory.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
93356                 return ts.setOriginalNode(ts.setTextRange(factory.createNewExpression(factory.createFunctionApplyCall(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, 
93357                 /*leadingElement*/ factory.createVoidZero())), 
93358                 /*typeArguments*/ undefined, []), node), node);
93359             }
93360             return ts.visitEachChild(node, visitor, context);
93361         }
93362         function transformAndEmitStatements(statements, start) {
93363             if (start === void 0) { start = 0; }
93364             var numStatements = statements.length;
93365             for (var i = start; i < numStatements; i++) {
93366                 transformAndEmitStatement(statements[i]);
93367             }
93368         }
93369         function transformAndEmitEmbeddedStatement(node) {
93370             if (ts.isBlock(node)) {
93371                 transformAndEmitStatements(node.statements);
93372             }
93373             else {
93374                 transformAndEmitStatement(node);
93375             }
93376         }
93377         function transformAndEmitStatement(node) {
93378             var savedInStatementContainingYield = inStatementContainingYield;
93379             if (!inStatementContainingYield) {
93380                 inStatementContainingYield = containsYield(node);
93381             }
93382             transformAndEmitStatementWorker(node);
93383             inStatementContainingYield = savedInStatementContainingYield;
93384         }
93385         function transformAndEmitStatementWorker(node) {
93386             switch (node.kind) {
93387                 case 230 /* Block */:
93388                     return transformAndEmitBlock(node);
93389                 case 233 /* ExpressionStatement */:
93390                     return transformAndEmitExpressionStatement(node);
93391                 case 234 /* IfStatement */:
93392                     return transformAndEmitIfStatement(node);
93393                 case 235 /* DoStatement */:
93394                     return transformAndEmitDoStatement(node);
93395                 case 236 /* WhileStatement */:
93396                     return transformAndEmitWhileStatement(node);
93397                 case 237 /* ForStatement */:
93398                     return transformAndEmitForStatement(node);
93399                 case 238 /* ForInStatement */:
93400                     return transformAndEmitForInStatement(node);
93401                 case 240 /* ContinueStatement */:
93402                     return transformAndEmitContinueStatement(node);
93403                 case 241 /* BreakStatement */:
93404                     return transformAndEmitBreakStatement(node);
93405                 case 242 /* ReturnStatement */:
93406                     return transformAndEmitReturnStatement(node);
93407                 case 243 /* WithStatement */:
93408                     return transformAndEmitWithStatement(node);
93409                 case 244 /* SwitchStatement */:
93410                     return transformAndEmitSwitchStatement(node);
93411                 case 245 /* LabeledStatement */:
93412                     return transformAndEmitLabeledStatement(node);
93413                 case 246 /* ThrowStatement */:
93414                     return transformAndEmitThrowStatement(node);
93415                 case 247 /* TryStatement */:
93416                     return transformAndEmitTryStatement(node);
93417                 default:
93418                     return emitStatement(ts.visitNode(node, visitor, ts.isStatement));
93419             }
93420         }
93421         function transformAndEmitBlock(node) {
93422             if (containsYield(node)) {
93423                 transformAndEmitStatements(node.statements);
93424             }
93425             else {
93426                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
93427             }
93428         }
93429         function transformAndEmitExpressionStatement(node) {
93430             emitStatement(ts.visitNode(node, visitor, ts.isStatement));
93431         }
93432         function transformAndEmitVariableDeclarationList(node) {
93433             for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
93434                 var variable = _a[_i];
93435                 var name = factory.cloneNode(variable.name);
93436                 ts.setCommentRange(name, variable.name);
93437                 hoistVariableDeclaration(name);
93438             }
93439             var variables = ts.getInitializedVariables(node);
93440             var numVariables = variables.length;
93441             var variablesWritten = 0;
93442             var pendingExpressions = [];
93443             while (variablesWritten < numVariables) {
93444                 for (var i = variablesWritten; i < numVariables; i++) {
93445                     var variable = variables[i];
93446                     if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
93447                         break;
93448                     }
93449                     pendingExpressions.push(transformInitializedVariable(variable));
93450                 }
93451                 if (pendingExpressions.length) {
93452                     emitStatement(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
93453                     variablesWritten += pendingExpressions.length;
93454                     pendingExpressions = [];
93455                 }
93456             }
93457             return undefined;
93458         }
93459         function transformInitializedVariable(node) {
93460             return ts.setSourceMapRange(factory.createAssignment(ts.setSourceMapRange(factory.cloneNode(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node);
93461         }
93462         function transformAndEmitIfStatement(node) {
93463             if (containsYield(node)) {
93464                 // [source]
93465                 //      if (x)
93466                 //          /*thenStatement*/
93467                 //      else
93468                 //          /*elseStatement*/
93469                 //
93470                 // [intermediate]
93471                 //  .brfalse elseLabel, (x)
93472                 //      /*thenStatement*/
93473                 //  .br endLabel
93474                 //  .mark elseLabel
93475                 //      /*elseStatement*/
93476                 //  .mark endLabel
93477                 if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
93478                     var endLabel = defineLabel();
93479                     var elseLabel = node.elseStatement ? defineLabel() : undefined;
93480                     emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression);
93481                     transformAndEmitEmbeddedStatement(node.thenStatement);
93482                     if (node.elseStatement) {
93483                         emitBreak(endLabel);
93484                         markLabel(elseLabel);
93485                         transformAndEmitEmbeddedStatement(node.elseStatement);
93486                     }
93487                     markLabel(endLabel);
93488                 }
93489                 else {
93490                     emitStatement(ts.visitNode(node, visitor, ts.isStatement));
93491                 }
93492             }
93493             else {
93494                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
93495             }
93496         }
93497         function transformAndEmitDoStatement(node) {
93498             if (containsYield(node)) {
93499                 // [source]
93500                 //      do {
93501                 //          /*body*/
93502                 //      }
93503                 //      while (i < 10);
93504                 //
93505                 // [intermediate]
93506                 //  .loop conditionLabel, endLabel
93507                 //  .mark loopLabel
93508                 //      /*body*/
93509                 //  .mark conditionLabel
93510                 //  .brtrue loopLabel, (i < 10)
93511                 //  .endloop
93512                 //  .mark endLabel
93513                 var conditionLabel = defineLabel();
93514                 var loopLabel = defineLabel();
93515                 beginLoopBlock(/*continueLabel*/ conditionLabel);
93516                 markLabel(loopLabel);
93517                 transformAndEmitEmbeddedStatement(node.statement);
93518                 markLabel(conditionLabel);
93519                 emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
93520                 endLoopBlock();
93521             }
93522             else {
93523                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
93524             }
93525         }
93526         function visitDoStatement(node) {
93527             if (inStatementContainingYield) {
93528                 beginScriptLoopBlock();
93529                 node = ts.visitEachChild(node, visitor, context);
93530                 endLoopBlock();
93531                 return node;
93532             }
93533             else {
93534                 return ts.visitEachChild(node, visitor, context);
93535             }
93536         }
93537         function transformAndEmitWhileStatement(node) {
93538             if (containsYield(node)) {
93539                 // [source]
93540                 //      while (i < 10) {
93541                 //          /*body*/
93542                 //      }
93543                 //
93544                 // [intermediate]
93545                 //  .loop loopLabel, endLabel
93546                 //  .mark loopLabel
93547                 //  .brfalse endLabel, (i < 10)
93548                 //      /*body*/
93549                 //  .br loopLabel
93550                 //  .endloop
93551                 //  .mark endLabel
93552                 var loopLabel = defineLabel();
93553                 var endLabel = beginLoopBlock(loopLabel);
93554                 markLabel(loopLabel);
93555                 emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
93556                 transformAndEmitEmbeddedStatement(node.statement);
93557                 emitBreak(loopLabel);
93558                 endLoopBlock();
93559             }
93560             else {
93561                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
93562             }
93563         }
93564         function visitWhileStatement(node) {
93565             if (inStatementContainingYield) {
93566                 beginScriptLoopBlock();
93567                 node = ts.visitEachChild(node, visitor, context);
93568                 endLoopBlock();
93569                 return node;
93570             }
93571             else {
93572                 return ts.visitEachChild(node, visitor, context);
93573             }
93574         }
93575         function transformAndEmitForStatement(node) {
93576             if (containsYield(node)) {
93577                 // [source]
93578                 //      for (var i = 0; i < 10; i++) {
93579                 //          /*body*/
93580                 //      }
93581                 //
93582                 // [intermediate]
93583                 //  .local i
93584                 //      i = 0;
93585                 //  .loop incrementLabel, endLoopLabel
93586                 //  .mark conditionLabel
93587                 //  .brfalse endLoopLabel, (i < 10)
93588                 //      /*body*/
93589                 //  .mark incrementLabel
93590                 //      i++;
93591                 //  .br conditionLabel
93592                 //  .endloop
93593                 //  .mark endLoopLabel
93594                 var conditionLabel = defineLabel();
93595                 var incrementLabel = defineLabel();
93596                 var endLabel = beginLoopBlock(incrementLabel);
93597                 if (node.initializer) {
93598                     var initializer = node.initializer;
93599                     if (ts.isVariableDeclarationList(initializer)) {
93600                         transformAndEmitVariableDeclarationList(initializer);
93601                     }
93602                     else {
93603                         emitStatement(ts.setTextRange(factory.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer));
93604                     }
93605                 }
93606                 markLabel(conditionLabel);
93607                 if (node.condition) {
93608                     emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression));
93609                 }
93610                 transformAndEmitEmbeddedStatement(node.statement);
93611                 markLabel(incrementLabel);
93612                 if (node.incrementor) {
93613                     emitStatement(ts.setTextRange(factory.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor));
93614                 }
93615                 emitBreak(conditionLabel);
93616                 endLoopBlock();
93617             }
93618             else {
93619                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
93620             }
93621         }
93622         function visitForStatement(node) {
93623             if (inStatementContainingYield) {
93624                 beginScriptLoopBlock();
93625             }
93626             var initializer = node.initializer;
93627             if (initializer && ts.isVariableDeclarationList(initializer)) {
93628                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
93629                     var variable = _a[_i];
93630                     hoistVariableDeclaration(variable.name);
93631                 }
93632                 var variables = ts.getInitializedVariables(initializer);
93633                 node = factory.updateForStatement(node, variables.length > 0
93634                     ? factory.inlineExpressions(ts.map(variables, transformInitializedVariable))
93635                     : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
93636             }
93637             else {
93638                 node = ts.visitEachChild(node, visitor, context);
93639             }
93640             if (inStatementContainingYield) {
93641                 endLoopBlock();
93642             }
93643             return node;
93644         }
93645         function transformAndEmitForInStatement(node) {
93646             // TODO(rbuckton): Source map locations
93647             if (containsYield(node)) {
93648                 // [source]
93649                 //      for (var p in o) {
93650                 //          /*body*/
93651                 //      }
93652                 //
93653                 // [intermediate]
93654                 //  .local _a, _b, _i
93655                 //      _a = [];
93656                 //      for (_b in o) _a.push(_b);
93657                 //      _i = 0;
93658                 //  .loop incrementLabel, endLoopLabel
93659                 //  .mark conditionLabel
93660                 //  .brfalse endLoopLabel, (_i < _a.length)
93661                 //      p = _a[_i];
93662                 //      /*body*/
93663                 //  .mark incrementLabel
93664                 //      _b++;
93665                 //  .br conditionLabel
93666                 //  .endloop
93667                 //  .mark endLoopLabel
93668                 var keysArray = declareLocal(); // _a
93669                 var key = declareLocal(); // _b
93670                 var keysIndex = factory.createLoopVariable(); // _i
93671                 var initializer = node.initializer;
93672                 hoistVariableDeclaration(keysIndex);
93673                 emitAssignment(keysArray, factory.createArrayLiteralExpression());
93674                 emitStatement(factory.createForInStatement(key, ts.visitNode(node.expression, visitor, ts.isExpression), factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), 
93675                 /*typeArguments*/ undefined, [key]))));
93676                 emitAssignment(keysIndex, factory.createNumericLiteral(0));
93677                 var conditionLabel = defineLabel();
93678                 var incrementLabel = defineLabel();
93679                 var endLabel = beginLoopBlock(incrementLabel);
93680                 markLabel(conditionLabel);
93681                 emitBreakWhenFalse(endLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length")));
93682                 var variable = void 0;
93683                 if (ts.isVariableDeclarationList(initializer)) {
93684                     for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
93685                         var variable_1 = _a[_i];
93686                         hoistVariableDeclaration(variable_1.name);
93687                     }
93688                     variable = factory.cloneNode(initializer.declarations[0].name);
93689                 }
93690                 else {
93691                     variable = ts.visitNode(initializer, visitor, ts.isExpression);
93692                     ts.Debug.assert(ts.isLeftHandSideExpression(variable));
93693                 }
93694                 emitAssignment(variable, factory.createElementAccessExpression(keysArray, keysIndex));
93695                 transformAndEmitEmbeddedStatement(node.statement);
93696                 markLabel(incrementLabel);
93697                 emitStatement(factory.createExpressionStatement(factory.createPostfixIncrement(keysIndex)));
93698                 emitBreak(conditionLabel);
93699                 endLoopBlock();
93700             }
93701             else {
93702                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
93703             }
93704         }
93705         function visitForInStatement(node) {
93706             // [source]
93707             //      for (var x in a) {
93708             //          /*body*/
93709             //      }
93710             //
93711             // [intermediate]
93712             //  .local x
93713             //  .loop
93714             //      for (x in a) {
93715             //          /*body*/
93716             //      }
93717             //  .endloop
93718             if (inStatementContainingYield) {
93719                 beginScriptLoopBlock();
93720             }
93721             var initializer = node.initializer;
93722             if (ts.isVariableDeclarationList(initializer)) {
93723                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
93724                     var variable = _a[_i];
93725                     hoistVariableDeclaration(variable.name);
93726                 }
93727                 node = factory.updateForInStatement(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
93728             }
93729             else {
93730                 node = ts.visitEachChild(node, visitor, context);
93731             }
93732             if (inStatementContainingYield) {
93733                 endLoopBlock();
93734             }
93735             return node;
93736         }
93737         function transformAndEmitContinueStatement(node) {
93738             var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined);
93739             if (label > 0) {
93740                 emitBreak(label, /*location*/ node);
93741             }
93742             else {
93743                 // invalid continue without a containing loop. Leave the node as is, per #17875.
93744                 emitStatement(node);
93745             }
93746         }
93747         function visitContinueStatement(node) {
93748             if (inStatementContainingYield) {
93749                 var label = findContinueTarget(node.label && ts.idText(node.label));
93750                 if (label > 0) {
93751                     return createInlineBreak(label, /*location*/ node);
93752                 }
93753             }
93754             return ts.visitEachChild(node, visitor, context);
93755         }
93756         function transformAndEmitBreakStatement(node) {
93757             var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined);
93758             if (label > 0) {
93759                 emitBreak(label, /*location*/ node);
93760             }
93761             else {
93762                 // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875.
93763                 emitStatement(node);
93764             }
93765         }
93766         function visitBreakStatement(node) {
93767             if (inStatementContainingYield) {
93768                 var label = findBreakTarget(node.label && ts.idText(node.label));
93769                 if (label > 0) {
93770                     return createInlineBreak(label, /*location*/ node);
93771                 }
93772             }
93773             return ts.visitEachChild(node, visitor, context);
93774         }
93775         function transformAndEmitReturnStatement(node) {
93776             emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
93777             /*location*/ node);
93778         }
93779         function visitReturnStatement(node) {
93780             return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
93781             /*location*/ node);
93782         }
93783         function transformAndEmitWithStatement(node) {
93784             if (containsYield(node)) {
93785                 // [source]
93786                 //      with (x) {
93787                 //          /*body*/
93788                 //      }
93789                 //
93790                 // [intermediate]
93791                 //  .with (x)
93792                 //      /*body*/
93793                 //  .endwith
93794                 beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)));
93795                 transformAndEmitEmbeddedStatement(node.statement);
93796                 endWithBlock();
93797             }
93798             else {
93799                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
93800             }
93801         }
93802         function transformAndEmitSwitchStatement(node) {
93803             if (containsYield(node.caseBlock)) {
93804                 // [source]
93805                 //      switch (x) {
93806                 //          case a:
93807                 //              /*caseStatements*/
93808                 //          case b:
93809                 //              /*caseStatements*/
93810                 //          default:
93811                 //              /*defaultStatements*/
93812                 //      }
93813                 //
93814                 // [intermediate]
93815                 //  .local _a
93816                 //  .switch endLabel
93817                 //      _a = x;
93818                 //      switch (_a) {
93819                 //          case a:
93820                 //  .br clauseLabels[0]
93821                 //      }
93822                 //      switch (_a) {
93823                 //          case b:
93824                 //  .br clauseLabels[1]
93825                 //      }
93826                 //  .br clauseLabels[2]
93827                 //  .mark clauseLabels[0]
93828                 //      /*caseStatements*/
93829                 //  .mark clauseLabels[1]
93830                 //      /*caseStatements*/
93831                 //  .mark clauseLabels[2]
93832                 //      /*caseStatements*/
93833                 //  .endswitch
93834                 //  .mark endLabel
93835                 var caseBlock = node.caseBlock;
93836                 var numClauses = caseBlock.clauses.length;
93837                 var endLabel = beginSwitchBlock();
93838                 var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression));
93839                 // Create labels for each clause and find the index of the first default clause.
93840                 var clauseLabels = [];
93841                 var defaultClauseIndex = -1;
93842                 for (var i = 0; i < numClauses; i++) {
93843                     var clause = caseBlock.clauses[i];
93844                     clauseLabels.push(defineLabel());
93845                     if (clause.kind === 285 /* DefaultClause */ && defaultClauseIndex === -1) {
93846                         defaultClauseIndex = i;
93847                     }
93848                 }
93849                 // Emit switch statements for each run of case clauses either from the first case
93850                 // clause or the next case clause with a `yield` in its expression, up to the next
93851                 // case clause with a `yield` in its expression.
93852                 var clausesWritten = 0;
93853                 var pendingClauses = [];
93854                 while (clausesWritten < numClauses) {
93855                     var defaultClausesSkipped = 0;
93856                     for (var i = clausesWritten; i < numClauses; i++) {
93857                         var clause = caseBlock.clauses[i];
93858                         if (clause.kind === 284 /* CaseClause */) {
93859                             if (containsYield(clause.expression) && pendingClauses.length > 0) {
93860                                 break;
93861                             }
93862                             pendingClauses.push(factory.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [
93863                                 createInlineBreak(clauseLabels[i], /*location*/ clause.expression)
93864                             ]));
93865                         }
93866                         else {
93867                             defaultClausesSkipped++;
93868                         }
93869                     }
93870                     if (pendingClauses.length) {
93871                         emitStatement(factory.createSwitchStatement(expression, factory.createCaseBlock(pendingClauses)));
93872                         clausesWritten += pendingClauses.length;
93873                         pendingClauses = [];
93874                     }
93875                     if (defaultClausesSkipped > 0) {
93876                         clausesWritten += defaultClausesSkipped;
93877                         defaultClausesSkipped = 0;
93878                     }
93879                 }
93880                 if (defaultClauseIndex >= 0) {
93881                     emitBreak(clauseLabels[defaultClauseIndex]);
93882                 }
93883                 else {
93884                     emitBreak(endLabel);
93885                 }
93886                 for (var i = 0; i < numClauses; i++) {
93887                     markLabel(clauseLabels[i]);
93888                     transformAndEmitStatements(caseBlock.clauses[i].statements);
93889                 }
93890                 endSwitchBlock();
93891             }
93892             else {
93893                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
93894             }
93895         }
93896         function visitSwitchStatement(node) {
93897             if (inStatementContainingYield) {
93898                 beginScriptSwitchBlock();
93899             }
93900             node = ts.visitEachChild(node, visitor, context);
93901             if (inStatementContainingYield) {
93902                 endSwitchBlock();
93903             }
93904             return node;
93905         }
93906         function transformAndEmitLabeledStatement(node) {
93907             if (containsYield(node)) {
93908                 // [source]
93909                 //      x: {
93910                 //          /*body*/
93911                 //      }
93912                 //
93913                 // [intermediate]
93914                 //  .labeled "x", endLabel
93915                 //      /*body*/
93916                 //  .endlabeled
93917                 //  .mark endLabel
93918                 beginLabeledBlock(ts.idText(node.label));
93919                 transformAndEmitEmbeddedStatement(node.statement);
93920                 endLabeledBlock();
93921             }
93922             else {
93923                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
93924             }
93925         }
93926         function visitLabeledStatement(node) {
93927             if (inStatementContainingYield) {
93928                 beginScriptLabeledBlock(ts.idText(node.label));
93929             }
93930             node = ts.visitEachChild(node, visitor, context);
93931             if (inStatementContainingYield) {
93932                 endLabeledBlock();
93933             }
93934             return node;
93935         }
93936         function transformAndEmitThrowStatement(node) {
93937             var _a;
93938             // TODO(rbuckton): `expression` should be required on `throw`.
93939             emitThrow(ts.visitNode((_a = node.expression) !== null && _a !== void 0 ? _a : factory.createVoidZero(), visitor, ts.isExpression), 
93940             /*location*/ node);
93941         }
93942         function transformAndEmitTryStatement(node) {
93943             if (containsYield(node)) {
93944                 // [source]
93945                 //      try {
93946                 //          /*tryBlock*/
93947                 //      }
93948                 //      catch (e) {
93949                 //          /*catchBlock*/
93950                 //      }
93951                 //      finally {
93952                 //          /*finallyBlock*/
93953                 //      }
93954                 //
93955                 // [intermediate]
93956                 //  .local _a
93957                 //  .try tryLabel, catchLabel, finallyLabel, endLabel
93958                 //  .mark tryLabel
93959                 //  .nop
93960                 //      /*tryBlock*/
93961                 //  .br endLabel
93962                 //  .catch
93963                 //  .mark catchLabel
93964                 //      _a = %error%;
93965                 //      /*catchBlock*/
93966                 //  .br endLabel
93967                 //  .finally
93968                 //  .mark finallyLabel
93969                 //      /*finallyBlock*/
93970                 //  .endfinally
93971                 //  .endtry
93972                 //  .mark endLabel
93973                 beginExceptionBlock();
93974                 transformAndEmitEmbeddedStatement(node.tryBlock);
93975                 if (node.catchClause) {
93976                     beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217
93977                     transformAndEmitEmbeddedStatement(node.catchClause.block);
93978                 }
93979                 if (node.finallyBlock) {
93980                     beginFinallyBlock();
93981                     transformAndEmitEmbeddedStatement(node.finallyBlock);
93982                 }
93983                 endExceptionBlock();
93984             }
93985             else {
93986                 emitStatement(ts.visitEachChild(node, visitor, context));
93987             }
93988         }
93989         function containsYield(node) {
93990             return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0;
93991         }
93992         function countInitialNodesWithoutYield(nodes) {
93993             var numNodes = nodes.length;
93994             for (var i = 0; i < numNodes; i++) {
93995                 if (containsYield(nodes[i])) {
93996                     return i;
93997                 }
93998             }
93999             return -1;
94000         }
94001         function onSubstituteNode(hint, node) {
94002             node = previousOnSubstituteNode(hint, node);
94003             if (hint === 1 /* Expression */) {
94004                 return substituteExpression(node);
94005             }
94006             return node;
94007         }
94008         function substituteExpression(node) {
94009             if (ts.isIdentifier(node)) {
94010                 return substituteExpressionIdentifier(node);
94011             }
94012             return node;
94013         }
94014         function substituteExpressionIdentifier(node) {
94015             if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) {
94016                 var original = ts.getOriginalNode(node);
94017                 if (ts.isIdentifier(original) && original.parent) {
94018                     var declaration = resolver.getReferencedValueDeclaration(original);
94019                     if (declaration) {
94020                         var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)];
94021                         if (name) {
94022                             // TODO(rbuckton): Does this need to be parented?
94023                             var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent);
94024                             ts.setSourceMapRange(clone_5, node);
94025                             ts.setCommentRange(clone_5, node);
94026                             return clone_5;
94027                         }
94028                     }
94029                 }
94030             }
94031             return node;
94032         }
94033         function cacheExpression(node) {
94034             if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) {
94035                 return node;
94036             }
94037             var temp = factory.createTempVariable(hoistVariableDeclaration);
94038             emitAssignment(temp, node, /*location*/ node);
94039             return temp;
94040         }
94041         function declareLocal(name) {
94042             var temp = name
94043                 ? factory.createUniqueName(name)
94044                 : factory.createTempVariable(/*recordTempVariable*/ undefined);
94045             hoistVariableDeclaration(temp);
94046             return temp;
94047         }
94048         /**
94049          * Defines a label, uses as the target of a Break operation.
94050          */
94051         function defineLabel() {
94052             if (!labelOffsets) {
94053                 labelOffsets = [];
94054             }
94055             var label = nextLabelId;
94056             nextLabelId++;
94057             labelOffsets[label] = -1;
94058             return label;
94059         }
94060         /**
94061          * Marks the current operation with the specified label.
94062          */
94063         function markLabel(label) {
94064             ts.Debug.assert(labelOffsets !== undefined, "No labels were defined.");
94065             labelOffsets[label] = operations ? operations.length : 0;
94066         }
94067         /**
94068          * Begins a block operation (With, Break/Continue, Try/Catch/Finally)
94069          *
94070          * @param block Information about the block.
94071          */
94072         function beginBlock(block) {
94073             if (!blocks) {
94074                 blocks = [];
94075                 blockActions = [];
94076                 blockOffsets = [];
94077                 blockStack = [];
94078             }
94079             var index = blockActions.length;
94080             blockActions[index] = 0 /* Open */;
94081             blockOffsets[index] = operations ? operations.length : 0;
94082             blocks[index] = block;
94083             blockStack.push(block);
94084             return index;
94085         }
94086         /**
94087          * Ends the current block operation.
94088          */
94089         function endBlock() {
94090             var block = peekBlock();
94091             if (block === undefined)
94092                 return ts.Debug.fail("beginBlock was never called.");
94093             var index = blockActions.length;
94094             blockActions[index] = 1 /* Close */;
94095             blockOffsets[index] = operations ? operations.length : 0;
94096             blocks[index] = block;
94097             blockStack.pop();
94098             return block;
94099         }
94100         /**
94101          * Gets the current open block.
94102          */
94103         function peekBlock() {
94104             return ts.lastOrUndefined(blockStack);
94105         }
94106         /**
94107          * Gets the kind of the current open block.
94108          */
94109         function peekBlockKind() {
94110             var block = peekBlock();
94111             return block && block.kind;
94112         }
94113         /**
94114          * Begins a code block for a generated `with` statement.
94115          *
94116          * @param expression An identifier representing expression for the `with` block.
94117          */
94118         function beginWithBlock(expression) {
94119             var startLabel = defineLabel();
94120             var endLabel = defineLabel();
94121             markLabel(startLabel);
94122             beginBlock({
94123                 kind: 1 /* With */,
94124                 expression: expression,
94125                 startLabel: startLabel,
94126                 endLabel: endLabel
94127             });
94128         }
94129         /**
94130          * Ends a code block for a generated `with` statement.
94131          */
94132         function endWithBlock() {
94133             ts.Debug.assert(peekBlockKind() === 1 /* With */);
94134             var block = endBlock();
94135             markLabel(block.endLabel);
94136         }
94137         /**
94138          * Begins a code block for a generated `try` statement.
94139          */
94140         function beginExceptionBlock() {
94141             var startLabel = defineLabel();
94142             var endLabel = defineLabel();
94143             markLabel(startLabel);
94144             beginBlock({
94145                 kind: 0 /* Exception */,
94146                 state: 0 /* Try */,
94147                 startLabel: startLabel,
94148                 endLabel: endLabel
94149             });
94150             emitNop();
94151             return endLabel;
94152         }
94153         /**
94154          * Enters the `catch` clause of a generated `try` statement.
94155          *
94156          * @param variable The catch variable.
94157          */
94158         function beginCatchBlock(variable) {
94159             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
94160             // generated identifiers should already be unique within a file
94161             var name;
94162             if (ts.isGeneratedIdentifier(variable.name)) {
94163                 name = variable.name;
94164                 hoistVariableDeclaration(variable.name);
94165             }
94166             else {
94167                 var text = ts.idText(variable.name);
94168                 name = declareLocal(text);
94169                 if (!renamedCatchVariables) {
94170                     renamedCatchVariables = new ts.Map();
94171                     renamedCatchVariableDeclarations = [];
94172                     context.enableSubstitution(78 /* Identifier */);
94173                 }
94174                 renamedCatchVariables.set(text, true);
94175                 renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
94176             }
94177             var exception = peekBlock();
94178             ts.Debug.assert(exception.state < 1 /* Catch */);
94179             var endLabel = exception.endLabel;
94180             emitBreak(endLabel);
94181             var catchLabel = defineLabel();
94182             markLabel(catchLabel);
94183             exception.state = 1 /* Catch */;
94184             exception.catchVariable = name;
94185             exception.catchLabel = catchLabel;
94186             emitAssignment(name, factory.createCallExpression(factory.createPropertyAccessExpression(state, "sent"), /*typeArguments*/ undefined, []));
94187             emitNop();
94188         }
94189         /**
94190          * Enters the `finally` block of a generated `try` statement.
94191          */
94192         function beginFinallyBlock() {
94193             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
94194             var exception = peekBlock();
94195             ts.Debug.assert(exception.state < 2 /* Finally */);
94196             var endLabel = exception.endLabel;
94197             emitBreak(endLabel);
94198             var finallyLabel = defineLabel();
94199             markLabel(finallyLabel);
94200             exception.state = 2 /* Finally */;
94201             exception.finallyLabel = finallyLabel;
94202         }
94203         /**
94204          * Ends the code block for a generated `try` statement.
94205          */
94206         function endExceptionBlock() {
94207             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
94208             var exception = endBlock();
94209             var state = exception.state;
94210             if (state < 2 /* Finally */) {
94211                 emitBreak(exception.endLabel);
94212             }
94213             else {
94214                 emitEndfinally();
94215             }
94216             markLabel(exception.endLabel);
94217             emitNop();
94218             exception.state = 3 /* Done */;
94219         }
94220         /**
94221          * Begins a code block that supports `break` or `continue` statements that are defined in
94222          * the source tree and not from generated code.
94223          *
94224          * @param labelText Names from containing labeled statements.
94225          */
94226         function beginScriptLoopBlock() {
94227             beginBlock({
94228                 kind: 3 /* Loop */,
94229                 isScript: true,
94230                 breakLabel: -1,
94231                 continueLabel: -1
94232             });
94233         }
94234         /**
94235          * Begins a code block that supports `break` or `continue` statements that are defined in
94236          * generated code. Returns a label used to mark the operation to which to jump when a
94237          * `break` statement targets this block.
94238          *
94239          * @param continueLabel A Label used to mark the operation to which to jump when a
94240          *                      `continue` statement targets this block.
94241          */
94242         function beginLoopBlock(continueLabel) {
94243             var breakLabel = defineLabel();
94244             beginBlock({
94245                 kind: 3 /* Loop */,
94246                 isScript: false,
94247                 breakLabel: breakLabel,
94248                 continueLabel: continueLabel,
94249             });
94250             return breakLabel;
94251         }
94252         /**
94253          * Ends a code block that supports `break` or `continue` statements that are defined in
94254          * generated code or in the source tree.
94255          */
94256         function endLoopBlock() {
94257             ts.Debug.assert(peekBlockKind() === 3 /* Loop */);
94258             var block = endBlock();
94259             var breakLabel = block.breakLabel;
94260             if (!block.isScript) {
94261                 markLabel(breakLabel);
94262             }
94263         }
94264         /**
94265          * Begins a code block that supports `break` statements that are defined in the source
94266          * tree and not from generated code.
94267          *
94268          */
94269         function beginScriptSwitchBlock() {
94270             beginBlock({
94271                 kind: 2 /* Switch */,
94272                 isScript: true,
94273                 breakLabel: -1
94274             });
94275         }
94276         /**
94277          * Begins a code block that supports `break` statements that are defined in generated code.
94278          * Returns a label used to mark the operation to which to jump when a `break` statement
94279          * targets this block.
94280          */
94281         function beginSwitchBlock() {
94282             var breakLabel = defineLabel();
94283             beginBlock({
94284                 kind: 2 /* Switch */,
94285                 isScript: false,
94286                 breakLabel: breakLabel,
94287             });
94288             return breakLabel;
94289         }
94290         /**
94291          * Ends a code block that supports `break` statements that are defined in generated code.
94292          */
94293         function endSwitchBlock() {
94294             ts.Debug.assert(peekBlockKind() === 2 /* Switch */);
94295             var block = endBlock();
94296             var breakLabel = block.breakLabel;
94297             if (!block.isScript) {
94298                 markLabel(breakLabel);
94299             }
94300         }
94301         function beginScriptLabeledBlock(labelText) {
94302             beginBlock({
94303                 kind: 4 /* Labeled */,
94304                 isScript: true,
94305                 labelText: labelText,
94306                 breakLabel: -1
94307             });
94308         }
94309         function beginLabeledBlock(labelText) {
94310             var breakLabel = defineLabel();
94311             beginBlock({
94312                 kind: 4 /* Labeled */,
94313                 isScript: false,
94314                 labelText: labelText,
94315                 breakLabel: breakLabel
94316             });
94317         }
94318         function endLabeledBlock() {
94319             ts.Debug.assert(peekBlockKind() === 4 /* Labeled */);
94320             var block = endBlock();
94321             if (!block.isScript) {
94322                 markLabel(block.breakLabel);
94323             }
94324         }
94325         /**
94326          * Indicates whether the provided block supports `break` statements.
94327          *
94328          * @param block A code block.
94329          */
94330         function supportsUnlabeledBreak(block) {
94331             return block.kind === 2 /* Switch */
94332                 || block.kind === 3 /* Loop */;
94333         }
94334         /**
94335          * Indicates whether the provided block supports `break` statements with labels.
94336          *
94337          * @param block A code block.
94338          */
94339         function supportsLabeledBreakOrContinue(block) {
94340             return block.kind === 4 /* Labeled */;
94341         }
94342         /**
94343          * Indicates whether the provided block supports `continue` statements.
94344          *
94345          * @param block A code block.
94346          */
94347         function supportsUnlabeledContinue(block) {
94348             return block.kind === 3 /* Loop */;
94349         }
94350         function hasImmediateContainingLabeledBlock(labelText, start) {
94351             for (var j = start; j >= 0; j--) {
94352                 var containingBlock = blockStack[j];
94353                 if (supportsLabeledBreakOrContinue(containingBlock)) {
94354                     if (containingBlock.labelText === labelText) {
94355                         return true;
94356                     }
94357                 }
94358                 else {
94359                     break;
94360                 }
94361             }
94362             return false;
94363         }
94364         /**
94365          * Finds the label that is the target for a `break` statement.
94366          *
94367          * @param labelText An optional name of a containing labeled statement.
94368          */
94369         function findBreakTarget(labelText) {
94370             if (blockStack) {
94371                 if (labelText) {
94372                     for (var i = blockStack.length - 1; i >= 0; i--) {
94373                         var block = blockStack[i];
94374                         if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) {
94375                             return block.breakLabel;
94376                         }
94377                         else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
94378                             return block.breakLabel;
94379                         }
94380                     }
94381                 }
94382                 else {
94383                     for (var i = blockStack.length - 1; i >= 0; i--) {
94384                         var block = blockStack[i];
94385                         if (supportsUnlabeledBreak(block)) {
94386                             return block.breakLabel;
94387                         }
94388                     }
94389                 }
94390             }
94391             return 0;
94392         }
94393         /**
94394          * Finds the label that is the target for a `continue` statement.
94395          *
94396          * @param labelText An optional name of a containing labeled statement.
94397          */
94398         function findContinueTarget(labelText) {
94399             if (blockStack) {
94400                 if (labelText) {
94401                     for (var i = blockStack.length - 1; i >= 0; i--) {
94402                         var block = blockStack[i];
94403                         if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
94404                             return block.continueLabel;
94405                         }
94406                     }
94407                 }
94408                 else {
94409                     for (var i = blockStack.length - 1; i >= 0; i--) {
94410                         var block = blockStack[i];
94411                         if (supportsUnlabeledContinue(block)) {
94412                             return block.continueLabel;
94413                         }
94414                     }
94415                 }
94416             }
94417             return 0;
94418         }
94419         /**
94420          * Creates an expression that can be used to indicate the value for a label.
94421          *
94422          * @param label A label.
94423          */
94424         function createLabel(label) {
94425             if (label !== undefined && label > 0) {
94426                 if (labelExpressions === undefined) {
94427                     labelExpressions = [];
94428                 }
94429                 var expression = factory.createNumericLiteral(-1);
94430                 if (labelExpressions[label] === undefined) {
94431                     labelExpressions[label] = [expression];
94432                 }
94433                 else {
94434                     labelExpressions[label].push(expression);
94435                 }
94436                 return expression;
94437             }
94438             return factory.createOmittedExpression();
94439         }
94440         /**
94441          * Creates a numeric literal for the provided instruction.
94442          */
94443         function createInstruction(instruction) {
94444             var literal = factory.createNumericLiteral(instruction);
94445             ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
94446             return literal;
94447         }
94448         /**
94449          * Creates a statement that can be used indicate a Break operation to the provided label.
94450          *
94451          * @param label A label.
94452          * @param location An optional source map location for the statement.
94453          */
94454         function createInlineBreak(label, location) {
94455             ts.Debug.assertLessThan(0, label, "Invalid label");
94456             return ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
94457                 createInstruction(3 /* Break */),
94458                 createLabel(label)
94459             ])), location);
94460         }
94461         /**
94462          * Creates a statement that can be used indicate a Return operation.
94463          *
94464          * @param expression The expression for the return statement.
94465          * @param location An optional source map location for the statement.
94466          */
94467         function createInlineReturn(expression, location) {
94468             return ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression(expression
94469                 ? [createInstruction(2 /* Return */), expression]
94470                 : [createInstruction(2 /* Return */)])), location);
94471         }
94472         /**
94473          * Creates an expression that can be used to resume from a Yield operation.
94474          */
94475         function createGeneratorResume(location) {
94476             return ts.setTextRange(factory.createCallExpression(factory.createPropertyAccessExpression(state, "sent"), 
94477             /*typeArguments*/ undefined, []), location);
94478         }
94479         /**
94480          * Emits an empty instruction.
94481          */
94482         function emitNop() {
94483             emitWorker(0 /* Nop */);
94484         }
94485         /**
94486          * Emits a Statement.
94487          *
94488          * @param node A statement.
94489          */
94490         function emitStatement(node) {
94491             if (node) {
94492                 emitWorker(1 /* Statement */, [node]);
94493             }
94494             else {
94495                 emitNop();
94496             }
94497         }
94498         /**
94499          * Emits an Assignment operation.
94500          *
94501          * @param left The left-hand side of the assignment.
94502          * @param right The right-hand side of the assignment.
94503          * @param location An optional source map location for the assignment.
94504          */
94505         function emitAssignment(left, right, location) {
94506             emitWorker(2 /* Assign */, [left, right], location);
94507         }
94508         /**
94509          * Emits a Break operation to the specified label.
94510          *
94511          * @param label A label.
94512          * @param location An optional source map location for the assignment.
94513          */
94514         function emitBreak(label, location) {
94515             emitWorker(3 /* Break */, [label], location);
94516         }
94517         /**
94518          * Emits a Break operation to the specified label when a condition evaluates to a truthy
94519          * value at runtime.
94520          *
94521          * @param label A label.
94522          * @param condition The condition.
94523          * @param location An optional source map location for the assignment.
94524          */
94525         function emitBreakWhenTrue(label, condition, location) {
94526             emitWorker(4 /* BreakWhenTrue */, [label, condition], location);
94527         }
94528         /**
94529          * Emits a Break to the specified label when a condition evaluates to a falsey value at
94530          * runtime.
94531          *
94532          * @param label A label.
94533          * @param condition The condition.
94534          * @param location An optional source map location for the assignment.
94535          */
94536         function emitBreakWhenFalse(label, condition, location) {
94537             emitWorker(5 /* BreakWhenFalse */, [label, condition], location);
94538         }
94539         /**
94540          * Emits a YieldStar operation for the provided expression.
94541          *
94542          * @param expression An optional value for the yield operation.
94543          * @param location An optional source map location for the assignment.
94544          */
94545         function emitYieldStar(expression, location) {
94546             emitWorker(7 /* YieldStar */, [expression], location);
94547         }
94548         /**
94549          * Emits a Yield operation for the provided expression.
94550          *
94551          * @param expression An optional value for the yield operation.
94552          * @param location An optional source map location for the assignment.
94553          */
94554         function emitYield(expression, location) {
94555             emitWorker(6 /* Yield */, [expression], location);
94556         }
94557         /**
94558          * Emits a Return operation for the provided expression.
94559          *
94560          * @param expression An optional value for the operation.
94561          * @param location An optional source map location for the assignment.
94562          */
94563         function emitReturn(expression, location) {
94564             emitWorker(8 /* Return */, [expression], location);
94565         }
94566         /**
94567          * Emits a Throw operation for the provided expression.
94568          *
94569          * @param expression A value for the operation.
94570          * @param location An optional source map location for the assignment.
94571          */
94572         function emitThrow(expression, location) {
94573             emitWorker(9 /* Throw */, [expression], location);
94574         }
94575         /**
94576          * Emits an Endfinally operation. This is used to handle `finally` block semantics.
94577          */
94578         function emitEndfinally() {
94579             emitWorker(10 /* Endfinally */);
94580         }
94581         /**
94582          * Emits an operation.
94583          *
94584          * @param code The OpCode for the operation.
94585          * @param args The optional arguments for the operation.
94586          */
94587         function emitWorker(code, args, location) {
94588             if (operations === undefined) {
94589                 operations = [];
94590                 operationArguments = [];
94591                 operationLocations = [];
94592             }
94593             if (labelOffsets === undefined) {
94594                 // mark entry point
94595                 markLabel(defineLabel());
94596             }
94597             var operationIndex = operations.length;
94598             operations[operationIndex] = code;
94599             operationArguments[operationIndex] = args;
94600             operationLocations[operationIndex] = location;
94601         }
94602         /**
94603          * Builds the generator function body.
94604          */
94605         function build() {
94606             blockIndex = 0;
94607             labelNumber = 0;
94608             labelNumbers = undefined;
94609             lastOperationWasAbrupt = false;
94610             lastOperationWasCompletion = false;
94611             clauses = undefined;
94612             statements = undefined;
94613             exceptionBlockStack = undefined;
94614             currentExceptionBlock = undefined;
94615             withBlockStack = undefined;
94616             var buildResult = buildStatements();
94617             return emitHelpers().createGeneratorHelper(ts.setEmitFlags(factory.createFunctionExpression(
94618             /*modifiers*/ undefined, 
94619             /*asteriskToken*/ undefined, 
94620             /*name*/ undefined, 
94621             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], 
94622             /*type*/ undefined, factory.createBlock(buildResult, 
94623             /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */));
94624         }
94625         /**
94626          * Builds the statements for the generator function body.
94627          */
94628         function buildStatements() {
94629             if (operations) {
94630                 for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) {
94631                     writeOperation(operationIndex);
94632                 }
94633                 flushFinalLabel(operations.length);
94634             }
94635             else {
94636                 flushFinalLabel(0);
94637             }
94638             if (clauses) {
94639                 var labelExpression = factory.createPropertyAccessExpression(state, "label");
94640                 var switchStatement = factory.createSwitchStatement(labelExpression, factory.createCaseBlock(clauses));
94641                 return [ts.startOnNewLine(switchStatement)];
94642             }
94643             if (statements) {
94644                 return statements;
94645             }
94646             return [];
94647         }
94648         /**
94649          * Flush the current label and advance to a new label.
94650          */
94651         function flushLabel() {
94652             if (!statements) {
94653                 return;
94654             }
94655             appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt);
94656             lastOperationWasAbrupt = false;
94657             lastOperationWasCompletion = false;
94658             labelNumber++;
94659         }
94660         /**
94661          * Flush the final label of the generator function body.
94662          */
94663         function flushFinalLabel(operationIndex) {
94664             if (isFinalLabelReachable(operationIndex)) {
94665                 tryEnterLabel(operationIndex);
94666                 withBlockStack = undefined;
94667                 writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined);
94668             }
94669             if (statements && clauses) {
94670                 appendLabel(/*markLabelEnd*/ false);
94671             }
94672             updateLabelExpressions();
94673         }
94674         /**
94675          * Tests whether the final label of the generator function body
94676          * is reachable by user code.
94677          */
94678         function isFinalLabelReachable(operationIndex) {
94679             // if the last operation was *not* a completion (return/throw) then
94680             // the final label is reachable.
94681             if (!lastOperationWasCompletion) {
94682                 return true;
94683             }
94684             // if there are no labels defined or referenced, then the final label is
94685             // not reachable.
94686             if (!labelOffsets || !labelExpressions) {
94687                 return false;
94688             }
94689             // if the label for this offset is referenced, then the final label
94690             // is reachable.
94691             for (var label = 0; label < labelOffsets.length; label++) {
94692                 if (labelOffsets[label] === operationIndex && labelExpressions[label]) {
94693                     return true;
94694                 }
94695             }
94696             return false;
94697         }
94698         /**
94699          * Appends a case clause for the last label and sets the new label.
94700          *
94701          * @param markLabelEnd Indicates that the transition between labels was a fall-through
94702          *                     from a previous case clause and the change in labels should be
94703          *                     reflected on the `state` object.
94704          */
94705         function appendLabel(markLabelEnd) {
94706             if (!clauses) {
94707                 clauses = [];
94708             }
94709             if (statements) {
94710                 if (withBlockStack) {
94711                     // The previous label was nested inside one or more `with` blocks, so we
94712                     // surround the statements in generated `with` blocks to create the same environment.
94713                     for (var i = withBlockStack.length - 1; i >= 0; i--) {
94714                         var withBlock = withBlockStack[i];
94715                         statements = [factory.createWithStatement(withBlock.expression, factory.createBlock(statements))];
94716                     }
94717                 }
94718                 if (currentExceptionBlock) {
94719                     // The previous label was nested inside of an exception block, so we must
94720                     // indicate entry into a protected region by pushing the label numbers
94721                     // for each block in the protected region.
94722                     var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel;
94723                     statements.unshift(factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createPropertyAccessExpression(state, "trys"), "push"), 
94724                     /*typeArguments*/ undefined, [
94725                         factory.createArrayLiteralExpression([
94726                             createLabel(startLabel),
94727                             createLabel(catchLabel),
94728                             createLabel(finallyLabel),
94729                             createLabel(endLabel)
94730                         ])
94731                     ])));
94732                     currentExceptionBlock = undefined;
94733                 }
94734                 if (markLabelEnd) {
94735                     // The case clause for the last label falls through to this label, so we
94736                     // add an assignment statement to reflect the change in labels.
94737                     statements.push(factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(state, "label"), factory.createNumericLiteral(labelNumber + 1))));
94738                 }
94739             }
94740             clauses.push(factory.createCaseClause(factory.createNumericLiteral(labelNumber), statements || []));
94741             statements = undefined;
94742         }
94743         /**
94744          * Tries to enter into a new label at the current operation index.
94745          */
94746         function tryEnterLabel(operationIndex) {
94747             if (!labelOffsets) {
94748                 return;
94749             }
94750             for (var label = 0; label < labelOffsets.length; label++) {
94751                 if (labelOffsets[label] === operationIndex) {
94752                     flushLabel();
94753                     if (labelNumbers === undefined) {
94754                         labelNumbers = [];
94755                     }
94756                     if (labelNumbers[labelNumber] === undefined) {
94757                         labelNumbers[labelNumber] = [label];
94758                     }
94759                     else {
94760                         labelNumbers[labelNumber].push(label);
94761                     }
94762                 }
94763             }
94764         }
94765         /**
94766          * Updates literal expressions for labels with actual label numbers.
94767          */
94768         function updateLabelExpressions() {
94769             if (labelExpressions !== undefined && labelNumbers !== undefined) {
94770                 for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) {
94771                     var labels = labelNumbers[labelNumber_1];
94772                     if (labels !== undefined) {
94773                         for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) {
94774                             var label = labels_1[_i];
94775                             var expressions = labelExpressions[label];
94776                             if (expressions !== undefined) {
94777                                 for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) {
94778                                     var expression = expressions_1[_a];
94779                                     expression.text = String(labelNumber_1);
94780                                 }
94781                             }
94782                         }
94783                     }
94784                 }
94785             }
94786         }
94787         /**
94788          * Tries to enter or leave a code block.
94789          */
94790         function tryEnterOrLeaveBlock(operationIndex) {
94791             if (blocks) {
94792                 for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
94793                     var block = blocks[blockIndex];
94794                     var blockAction = blockActions[blockIndex];
94795                     switch (block.kind) {
94796                         case 0 /* Exception */:
94797                             if (blockAction === 0 /* Open */) {
94798                                 if (!exceptionBlockStack) {
94799                                     exceptionBlockStack = [];
94800                                 }
94801                                 if (!statements) {
94802                                     statements = [];
94803                                 }
94804                                 exceptionBlockStack.push(currentExceptionBlock);
94805                                 currentExceptionBlock = block;
94806                             }
94807                             else if (blockAction === 1 /* Close */) {
94808                                 currentExceptionBlock = exceptionBlockStack.pop();
94809                             }
94810                             break;
94811                         case 1 /* With */:
94812                             if (blockAction === 0 /* Open */) {
94813                                 if (!withBlockStack) {
94814                                     withBlockStack = [];
94815                                 }
94816                                 withBlockStack.push(block);
94817                             }
94818                             else if (blockAction === 1 /* Close */) {
94819                                 withBlockStack.pop();
94820                             }
94821                             break;
94822                         // default: do nothing
94823                     }
94824                 }
94825             }
94826         }
94827         /**
94828          * Writes an operation as a statement to the current label's statement list.
94829          *
94830          * @param operation The OpCode of the operation
94831          */
94832         function writeOperation(operationIndex) {
94833             tryEnterLabel(operationIndex);
94834             tryEnterOrLeaveBlock(operationIndex);
94835             // early termination, nothing else to process in this label
94836             if (lastOperationWasAbrupt) {
94837                 return;
94838             }
94839             lastOperationWasAbrupt = false;
94840             lastOperationWasCompletion = false;
94841             var opcode = operations[operationIndex];
94842             if (opcode === 0 /* Nop */) {
94843                 return;
94844             }
94845             else if (opcode === 10 /* Endfinally */) {
94846                 return writeEndfinally();
94847             }
94848             var args = operationArguments[operationIndex];
94849             if (opcode === 1 /* Statement */) {
94850                 return writeStatement(args[0]);
94851             }
94852             var location = operationLocations[operationIndex];
94853             switch (opcode) {
94854                 case 2 /* Assign */:
94855                     return writeAssign(args[0], args[1], location);
94856                 case 3 /* Break */:
94857                     return writeBreak(args[0], location);
94858                 case 4 /* BreakWhenTrue */:
94859                     return writeBreakWhenTrue(args[0], args[1], location);
94860                 case 5 /* BreakWhenFalse */:
94861                     return writeBreakWhenFalse(args[0], args[1], location);
94862                 case 6 /* Yield */:
94863                     return writeYield(args[0], location);
94864                 case 7 /* YieldStar */:
94865                     return writeYieldStar(args[0], location);
94866                 case 8 /* Return */:
94867                     return writeReturn(args[0], location);
94868                 case 9 /* Throw */:
94869                     return writeThrow(args[0], location);
94870             }
94871         }
94872         /**
94873          * Writes a statement to the current label's statement list.
94874          *
94875          * @param statement A statement to write.
94876          */
94877         function writeStatement(statement) {
94878             if (statement) {
94879                 if (!statements) {
94880                     statements = [statement];
94881                 }
94882                 else {
94883                     statements.push(statement);
94884                 }
94885             }
94886         }
94887         /**
94888          * Writes an Assign operation to the current label's statement list.
94889          *
94890          * @param left The left-hand side of the assignment.
94891          * @param right The right-hand side of the assignment.
94892          * @param operationLocation The source map location for the operation.
94893          */
94894         function writeAssign(left, right, operationLocation) {
94895             writeStatement(ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(left, right)), operationLocation));
94896         }
94897         /**
94898          * Writes a Throw operation to the current label's statement list.
94899          *
94900          * @param expression The value to throw.
94901          * @param operationLocation The source map location for the operation.
94902          */
94903         function writeThrow(expression, operationLocation) {
94904             lastOperationWasAbrupt = true;
94905             lastOperationWasCompletion = true;
94906             writeStatement(ts.setTextRange(factory.createThrowStatement(expression), operationLocation));
94907         }
94908         /**
94909          * Writes a Return operation to the current label's statement list.
94910          *
94911          * @param expression The value to return.
94912          * @param operationLocation The source map location for the operation.
94913          */
94914         function writeReturn(expression, operationLocation) {
94915             lastOperationWasAbrupt = true;
94916             lastOperationWasCompletion = true;
94917             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression(expression
94918                 ? [createInstruction(2 /* Return */), expression]
94919                 : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */));
94920         }
94921         /**
94922          * Writes a Break operation to the current label's statement list.
94923          *
94924          * @param label The label for the Break.
94925          * @param operationLocation The source map location for the operation.
94926          */
94927         function writeBreak(label, operationLocation) {
94928             lastOperationWasAbrupt = true;
94929             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
94930                 createInstruction(3 /* Break */),
94931                 createLabel(label)
94932             ])), operationLocation), 384 /* NoTokenSourceMaps */));
94933         }
94934         /**
94935          * Writes a BreakWhenTrue operation to the current label's statement list.
94936          *
94937          * @param label The label for the Break.
94938          * @param condition The condition for the Break.
94939          * @param operationLocation The source map location for the operation.
94940          */
94941         function writeBreakWhenTrue(label, condition, operationLocation) {
94942             writeStatement(ts.setEmitFlags(factory.createIfStatement(condition, ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
94943                 createInstruction(3 /* Break */),
94944                 createLabel(label)
94945             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
94946         }
94947         /**
94948          * Writes a BreakWhenFalse operation to the current label's statement list.
94949          *
94950          * @param label The label for the Break.
94951          * @param condition The condition for the Break.
94952          * @param operationLocation The source map location for the operation.
94953          */
94954         function writeBreakWhenFalse(label, condition, operationLocation) {
94955             writeStatement(ts.setEmitFlags(factory.createIfStatement(factory.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
94956                 createInstruction(3 /* Break */),
94957                 createLabel(label)
94958             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
94959         }
94960         /**
94961          * Writes a Yield operation to the current label's statement list.
94962          *
94963          * @param expression The expression to yield.
94964          * @param operationLocation The source map location for the operation.
94965          */
94966         function writeYield(expression, operationLocation) {
94967             lastOperationWasAbrupt = true;
94968             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression(expression
94969                 ? [createInstruction(4 /* Yield */), expression]
94970                 : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */));
94971         }
94972         /**
94973          * Writes a YieldStar instruction to the current label's statement list.
94974          *
94975          * @param expression The expression to yield.
94976          * @param operationLocation The source map location for the operation.
94977          */
94978         function writeYieldStar(expression, operationLocation) {
94979             lastOperationWasAbrupt = true;
94980             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
94981                 createInstruction(5 /* YieldStar */),
94982                 expression
94983             ])), operationLocation), 384 /* NoTokenSourceMaps */));
94984         }
94985         /**
94986          * Writes an Endfinally instruction to the current label's statement list.
94987          */
94988         function writeEndfinally() {
94989             lastOperationWasAbrupt = true;
94990             writeStatement(factory.createReturnStatement(factory.createArrayLiteralExpression([
94991                 createInstruction(7 /* Endfinally */)
94992             ])));
94993         }
94994     }
94995     ts.transformGenerators = transformGenerators;
94996 })(ts || (ts = {}));
94997 /*@internal*/
94998 var ts;
94999 (function (ts) {
95000     function transformModule(context) {
95001         function getTransformModuleDelegate(moduleKind) {
95002             switch (moduleKind) {
95003                 case ts.ModuleKind.AMD: return transformAMDModule;
95004                 case ts.ModuleKind.UMD: return transformUMDModule;
95005                 default: return transformCommonJSModule;
95006             }
95007         }
95008         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
95009         var compilerOptions = context.getCompilerOptions();
95010         var resolver = context.getEmitResolver();
95011         var host = context.getEmitHost();
95012         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
95013         var moduleKind = ts.getEmitModuleKind(compilerOptions);
95014         var previousOnSubstituteNode = context.onSubstituteNode;
95015         var previousOnEmitNode = context.onEmitNode;
95016         context.onSubstituteNode = onSubstituteNode;
95017         context.onEmitNode = onEmitNode;
95018         context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
95019         context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols.
95020         context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
95021         context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
95022         context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
95023         context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file.
95024         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
95025         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
95026         var currentSourceFile; // The current file.
95027         var currentModuleInfo; // The ExternalModuleInfo for the current file.
95028         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
95029         var needUMDDynamicImportHelper;
95030         return ts.chainBundle(context, transformSourceFile);
95031         /**
95032          * Transforms the module aspects of a SourceFile.
95033          *
95034          * @param node The SourceFile node.
95035          */
95036         function transformSourceFile(node) {
95037             if (node.isDeclarationFile ||
95038                 !(ts.isEffectiveExternalModule(node, compilerOptions) ||
95039                     node.transformFlags & 2097152 /* ContainsDynamicImport */ ||
95040                     (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) {
95041                 return node;
95042             }
95043             currentSourceFile = node;
95044             currentModuleInfo = ts.collectExternalModuleInfo(context, node, resolver, compilerOptions);
95045             moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
95046             // Perform the transformation.
95047             var transformModule = getTransformModuleDelegate(moduleKind);
95048             var updated = transformModule(node);
95049             currentSourceFile = undefined;
95050             currentModuleInfo = undefined;
95051             needUMDDynamicImportHelper = false;
95052             return updated;
95053         }
95054         function shouldEmitUnderscoreUnderscoreESModule() {
95055             if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) {
95056                 return true;
95057             }
95058             return false;
95059         }
95060         /**
95061          * Transforms a SourceFile into a CommonJS module.
95062          *
95063          * @param node The SourceFile node.
95064          */
95065         function transformCommonJSModule(node) {
95066             startLexicalEnvironment();
95067             var statements = [];
95068             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
95069             var statementOffset = factory.copyPrologue(node.statements, statements, ensureUseStrict && !ts.isJsonSourceFile(node), sourceElementVisitor);
95070             if (shouldEmitUnderscoreUnderscoreESModule()) {
95071                 ts.append(statements, createUnderscoreUnderscoreESModule());
95072             }
95073             if (ts.length(currentModuleInfo.exportedNames)) {
95074                 var chunkSize = 50;
95075                 for (var i = 0; i < currentModuleInfo.exportedNames.length; i += chunkSize) {
95076                     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())));
95077                 }
95078             }
95079             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
95080             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
95081             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
95082             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
95083             var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray(statements), node.statements));
95084             ts.addEmitHelpers(updated, context.readEmitHelpers());
95085             return updated;
95086         }
95087         /**
95088          * Transforms a SourceFile into an AMD module.
95089          *
95090          * @param node The SourceFile node.
95091          */
95092         function transformAMDModule(node) {
95093             var define = factory.createIdentifier("define");
95094             var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions);
95095             var jsonSourceFile = ts.isJsonSourceFile(node) && node;
95096             // An AMD define function has the following shape:
95097             //
95098             //     define(id?, dependencies?, factory);
95099             //
95100             // This has the shape of the following:
95101             //
95102             //     define(name, ["module1", "module2"], function (module1Alias) { ... }
95103             //
95104             // The location of the alias in the parameter list in the factory function needs to
95105             // match the position of the module name in the dependency list.
95106             //
95107             // To ensure this is true in cases of modules with no aliases, e.g.:
95108             //
95109             //     import "module"
95110             //
95111             // or
95112             //
95113             //     /// <amd-dependency path= "a.css" />
95114             //
95115             // we need to add modules without alias names to the end of the dependencies list
95116             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
95117             // Create an updated SourceFile:
95118             //
95119             //     define(mofactory.updateSourceFile", "module2"], function ...
95120             var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
95121                 factory.createExpressionStatement(factory.createCallExpression(define, 
95122                 /*typeArguments*/ undefined, __spreadArray(__spreadArray([], (moduleName ? [moduleName] : [])), [
95123                     // Add the dependency array argument:
95124                     //
95125                     //     ["require", "exports", module1", "module2", ...]
95126                     factory.createArrayLiteralExpression(jsonSourceFile ? ts.emptyArray : __spreadArray(__spreadArray([
95127                         factory.createStringLiteral("require"),
95128                         factory.createStringLiteral("exports")
95129                     ], aliasedModuleNames), unaliasedModuleNames)),
95130                     // Add the module body function argument:
95131                     //
95132                     //     function (require, exports, module1, module2) ...
95133                     jsonSourceFile ?
95134                         jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : factory.createObjectLiteralExpression() :
95135                         factory.createFunctionExpression(
95136                         /*modifiers*/ undefined, 
95137                         /*asteriskToken*/ undefined, 
95138                         /*name*/ undefined, 
95139                         /*typeParameters*/ undefined, __spreadArray([
95140                             factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
95141                             factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
95142                         ], importAliasNames), 
95143                         /*type*/ undefined, transformAsynchronousModuleBody(node))
95144                 ])))
95145             ]), 
95146             /*location*/ node.statements));
95147             ts.addEmitHelpers(updated, context.readEmitHelpers());
95148             return updated;
95149         }
95150         /**
95151          * Transforms a SourceFile into a UMD module.
95152          *
95153          * @param node The SourceFile node.
95154          */
95155         function transformUMDModule(node) {
95156             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
95157             var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions);
95158             var umdHeader = factory.createFunctionExpression(
95159             /*modifiers*/ undefined, 
95160             /*asteriskToken*/ undefined, 
95161             /*name*/ undefined, 
95162             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], 
95163             /*type*/ undefined, ts.setTextRange(factory.createBlock([
95164                 factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("module"), "object"), factory.createTypeCheck(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), "object")), factory.createBlock([
95165                     factory.createVariableStatement(
95166                     /*modifiers*/ undefined, [
95167                         factory.createVariableDeclaration("v", 
95168                         /*exclamationToken*/ undefined, 
95169                         /*type*/ undefined, factory.createCallExpression(factory.createIdentifier("factory"), 
95170                         /*typeArguments*/ undefined, [
95171                             factory.createIdentifier("require"),
95172                             factory.createIdentifier("exports")
95173                         ]))
95174                     ]),
95175                     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 */)
95176                 ]), factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("define"), "function"), factory.createPropertyAccessExpression(factory.createIdentifier("define"), "amd")), factory.createBlock([
95177                     factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("define"), 
95178                     /*typeArguments*/ undefined, __spreadArray(__spreadArray([], (moduleName ? [moduleName] : [])), [
95179                         factory.createArrayLiteralExpression(__spreadArray(__spreadArray([
95180                             factory.createStringLiteral("require"),
95181                             factory.createStringLiteral("exports")
95182                         ], aliasedModuleNames), unaliasedModuleNames)),
95183                         factory.createIdentifier("factory")
95184                     ])))
95185                 ])))
95186             ], 
95187             /*multiLine*/ true), 
95188             /*location*/ undefined));
95189             // Create an updated SourceFile:
95190             //
95191             //  (function (factory) {
95192             //      if (typeof module === "object" && typeof module.exports === "object") {
95193             //          var v = factory(require, exports);
95194             //          if (v !== undefined) module.exports = v;
95195             //      }
95196             //      else if (typeof define === 'function' && define.amd) {
95197             //          define(["require", "exports"], factory);
95198             //      }
95199             //  })(function ...)
95200             var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
95201                 factory.createExpressionStatement(factory.createCallExpression(umdHeader, 
95202                 /*typeArguments*/ undefined, [
95203                     // Add the module body function argument:
95204                     //
95205                     //     function (require, exports) ...
95206                     factory.createFunctionExpression(
95207                     /*modifiers*/ undefined, 
95208                     /*asteriskToken*/ undefined, 
95209                     /*name*/ undefined, 
95210                     /*typeParameters*/ undefined, __spreadArray([
95211                         factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
95212                         factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
95213                     ], importAliasNames), 
95214                     /*type*/ undefined, transformAsynchronousModuleBody(node))
95215                 ]))
95216             ]), 
95217             /*location*/ node.statements));
95218             ts.addEmitHelpers(updated, context.readEmitHelpers());
95219             return updated;
95220         }
95221         /**
95222          * Collect the additional asynchronous dependencies for the module.
95223          *
95224          * @param node The source file.
95225          * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
95226          */
95227         function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
95228             // names of modules with corresponding parameter in the factory function
95229             var aliasedModuleNames = [];
95230             // names of modules with no corresponding parameters in factory function
95231             var unaliasedModuleNames = [];
95232             // names of the parameters in the factory function; these
95233             // parameters need to match the indexes of the corresponding
95234             // module names in aliasedModuleNames.
95235             var importAliasNames = [];
95236             // Fill in amd-dependency tags
95237             for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
95238                 var amdDependency = _a[_i];
95239                 if (amdDependency.name) {
95240                     aliasedModuleNames.push(factory.createStringLiteral(amdDependency.path));
95241                     importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
95242                 }
95243                 else {
95244                     unaliasedModuleNames.push(factory.createStringLiteral(amdDependency.path));
95245                 }
95246             }
95247             for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
95248                 var importNode = _c[_b];
95249                 // Find the name of the external module
95250                 var externalModuleName = ts.getExternalModuleNameLiteral(factory, importNode, currentSourceFile, host, resolver, compilerOptions);
95251                 // Find the name of the module alias, if there is one
95252                 var importAliasName = ts.getLocalNameForExternalImport(factory, importNode, currentSourceFile);
95253                 // It is possible that externalModuleName is undefined if it is not string literal.
95254                 // This can happen in the invalid import syntax.
95255                 // E.g : "import * from alias from 'someLib';"
95256                 if (externalModuleName) {
95257                     if (includeNonAmdDependencies && importAliasName) {
95258                         // Set emitFlags on the name of the classDeclaration
95259                         // This is so that when printer will not substitute the identifier
95260                         ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
95261                         aliasedModuleNames.push(externalModuleName);
95262                         importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
95263                     }
95264                     else {
95265                         unaliasedModuleNames.push(externalModuleName);
95266                     }
95267                 }
95268             }
95269             return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
95270         }
95271         function getAMDImportExpressionForImport(node) {
95272             if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions)) {
95273                 return undefined;
95274             }
95275             var name = ts.getLocalNameForExternalImport(factory, node, currentSourceFile); // TODO: GH#18217
95276             var expr = getHelperExpressionForImport(node, name);
95277             if (expr === name) {
95278                 return undefined;
95279             }
95280             return factory.createExpressionStatement(factory.createAssignment(name, expr));
95281         }
95282         /**
95283          * Transforms a SourceFile into an AMD or UMD module body.
95284          *
95285          * @param node The SourceFile node.
95286          */
95287         function transformAsynchronousModuleBody(node) {
95288             startLexicalEnvironment();
95289             var statements = [];
95290             var statementOffset = factory.copyPrologue(node.statements, statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
95291             if (shouldEmitUnderscoreUnderscoreESModule()) {
95292                 ts.append(statements, createUnderscoreUnderscoreESModule());
95293             }
95294             if (ts.length(currentModuleInfo.exportedNames)) {
95295                 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())));
95296             }
95297             // Visit each statement of the module body.
95298             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
95299             if (moduleKind === ts.ModuleKind.AMD) {
95300                 ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
95301             }
95302             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
95303             // Append the 'export =' statement if provided.
95304             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
95305             // End the lexical environment for the module body
95306             // and merge any new lexical declarations.
95307             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
95308             var body = factory.createBlock(statements, /*multiLine*/ true);
95309             if (needUMDDynamicImportHelper) {
95310                 ts.addEmitHelper(body, dynamicImportUMDHelper);
95311             }
95312             return body;
95313         }
95314         /**
95315          * Adds the down-level representation of `export=` to the statement list if one exists
95316          * in the source file.
95317          *
95318          * @param statements The Statement list to modify.
95319          * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
95320          * return statement.
95321          */
95322         function addExportEqualsIfNeeded(statements, emitAsReturn) {
95323             if (currentModuleInfo.exportEquals) {
95324                 var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
95325                 if (expressionResult) {
95326                     if (emitAsReturn) {
95327                         var statement = factory.createReturnStatement(expressionResult);
95328                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
95329                         ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
95330                         statements.push(statement);
95331                     }
95332                     else {
95333                         var statement = factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), expressionResult));
95334                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
95335                         ts.setEmitFlags(statement, 1536 /* NoComments */);
95336                         statements.push(statement);
95337                     }
95338                 }
95339             }
95340         }
95341         //
95342         // Top-Level Source Element Visitors
95343         //
95344         /**
95345          * Visits a node at the top level of the source file.
95346          *
95347          * @param node The node to visit.
95348          */
95349         function sourceElementVisitor(node) {
95350             switch (node.kind) {
95351                 case 261 /* ImportDeclaration */:
95352                     return visitImportDeclaration(node);
95353                 case 260 /* ImportEqualsDeclaration */:
95354                     return visitImportEqualsDeclaration(node);
95355                 case 267 /* ExportDeclaration */:
95356                     return visitExportDeclaration(node);
95357                 case 266 /* ExportAssignment */:
95358                     return visitExportAssignment(node);
95359                 case 232 /* VariableStatement */:
95360                     return visitVariableStatement(node);
95361                 case 251 /* FunctionDeclaration */:
95362                     return visitFunctionDeclaration(node);
95363                 case 252 /* ClassDeclaration */:
95364                     return visitClassDeclaration(node);
95365                 case 338 /* MergeDeclarationMarker */:
95366                     return visitMergeDeclarationMarker(node);
95367                 case 339 /* EndOfDeclarationMarker */:
95368                     return visitEndOfDeclarationMarker(node);
95369                 default:
95370                     return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
95371             }
95372         }
95373         function moduleExpressionElementVisitor(node) {
95374             // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
95375             // as export/import statements are only transformed at the top level of a file.
95376             if (!(node.transformFlags & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) {
95377                 return node;
95378             }
95379             if (ts.isImportCall(node)) {
95380                 return visitImportCallExpression(node);
95381             }
95382             else if (ts.isDestructuringAssignment(node)) {
95383                 return visitDestructuringAssignment(node);
95384             }
95385             else {
95386                 return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
95387             }
95388         }
95389         function destructuringNeedsFlattening(node) {
95390             if (ts.isObjectLiteralExpression(node)) {
95391                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
95392                     var elem = _a[_i];
95393                     switch (elem.kind) {
95394                         case 288 /* PropertyAssignment */:
95395                             if (destructuringNeedsFlattening(elem.initializer)) {
95396                                 return true;
95397                             }
95398                             break;
95399                         case 289 /* ShorthandPropertyAssignment */:
95400                             if (destructuringNeedsFlattening(elem.name)) {
95401                                 return true;
95402                             }
95403                             break;
95404                         case 290 /* SpreadAssignment */:
95405                             if (destructuringNeedsFlattening(elem.expression)) {
95406                                 return true;
95407                             }
95408                             break;
95409                         case 165 /* MethodDeclaration */:
95410                         case 167 /* GetAccessor */:
95411                         case 168 /* SetAccessor */:
95412                             return false;
95413                         default: ts.Debug.assertNever(elem, "Unhandled object member kind");
95414                     }
95415                 }
95416             }
95417             else if (ts.isArrayLiteralExpression(node)) {
95418                 for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
95419                     var elem = _c[_b];
95420                     if (ts.isSpreadElement(elem)) {
95421                         if (destructuringNeedsFlattening(elem.expression)) {
95422                             return true;
95423                         }
95424                     }
95425                     else if (destructuringNeedsFlattening(elem)) {
95426                         return true;
95427                     }
95428                 }
95429             }
95430             else if (ts.isIdentifier(node)) {
95431                 return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
95432             }
95433             return false;
95434         }
95435         function visitDestructuringAssignment(node) {
95436             if (destructuringNeedsFlattening(node.left)) {
95437                 return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
95438             }
95439             return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
95440         }
95441         function visitImportCallExpression(node) {
95442             var externalModuleName = ts.getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions);
95443             var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
95444             // 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.
95445             var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument;
95446             var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */);
95447             switch (compilerOptions.module) {
95448                 case ts.ModuleKind.AMD:
95449                     return createImportCallExpressionAMD(argument, containsLexicalThis);
95450                 case ts.ModuleKind.UMD:
95451                     return createImportCallExpressionUMD(argument !== null && argument !== void 0 ? argument : factory.createVoidZero(), containsLexicalThis);
95452                 case ts.ModuleKind.CommonJS:
95453                 default:
95454                     return createImportCallExpressionCommonJS(argument, containsLexicalThis);
95455             }
95456         }
95457         function createImportCallExpressionUMD(arg, containsLexicalThis) {
95458             // (function (factory) {
95459             //      ... (regular UMD)
95460             // }
95461             // })(function (require, exports, useSyncRequire) {
95462             //      "use strict";
95463             //      Object.defineProperty(exports, "__esModule", { value: true });
95464             //      var __syncRequire = typeof module === "object" && typeof module.exports === "object";
95465             //      var __resolved = new Promise(function (resolve) { resolve(); });
95466             //      .....
95467             //      __syncRequire
95468             //          ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
95469             //          : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
95470             // });
95471             needUMDDynamicImportHelper = true;
95472             if (ts.isSimpleCopiableExpression(arg)) {
95473                 var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? factory.createStringLiteralFromNode(arg) : ts.setEmitFlags(ts.setTextRange(factory.cloneNode(arg), arg), 1536 /* NoComments */);
95474                 return factory.createConditionalExpression(
95475                 /*condition*/ factory.createIdentifier("__syncRequire"), 
95476                 /*questionToken*/ undefined, 
95477                 /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), 
95478                 /*colonToken*/ undefined, 
95479                 /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis));
95480             }
95481             else {
95482                 var temp = factory.createTempVariable(hoistVariableDeclaration);
95483                 return factory.createComma(factory.createAssignment(temp, arg), factory.createConditionalExpression(
95484                 /*condition*/ factory.createIdentifier("__syncRequire"), 
95485                 /*questionToken*/ undefined, 
95486                 /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), 
95487                 /*colonToken*/ undefined, 
95488                 /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis)));
95489             }
95490         }
95491         function createImportCallExpressionAMD(arg, containsLexicalThis) {
95492             // improt("./blah")
95493             // emit as
95494             // define(["require", "exports", "blah"], function (require, exports) {
95495             //     ...
95496             //     new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
95497             // });
95498             var resolve = factory.createUniqueName("resolve");
95499             var reject = factory.createUniqueName("reject");
95500             var parameters = [
95501                 factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
95502                 factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)
95503             ];
95504             var body = factory.createBlock([
95505                 factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("require"), 
95506                 /*typeArguments*/ undefined, [factory.createArrayLiteralExpression([arg || factory.createOmittedExpression()]), resolve, reject]))
95507             ]);
95508             var func;
95509             if (languageVersion >= 2 /* ES2015 */) {
95510                 func = factory.createArrowFunction(
95511                 /*modifiers*/ undefined, 
95512                 /*typeParameters*/ undefined, parameters, 
95513                 /*type*/ undefined, 
95514                 /*equalsGreaterThanToken*/ undefined, body);
95515             }
95516             else {
95517                 func = factory.createFunctionExpression(
95518                 /*modifiers*/ undefined, 
95519                 /*asteriskToken*/ undefined, 
95520                 /*name*/ undefined, 
95521                 /*typeParameters*/ undefined, parameters, 
95522                 /*type*/ undefined, body);
95523                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
95524                 // that this new function expression indicates it captures 'this' so that the
95525                 // es2015 transformer will properly substitute 'this' with '_this'.
95526                 if (containsLexicalThis) {
95527                     ts.setEmitFlags(func, 8 /* CapturesThis */);
95528                 }
95529             }
95530             var promise = factory.createNewExpression(factory.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
95531             if (compilerOptions.esModuleInterop) {
95532                 return factory.createCallExpression(factory.createPropertyAccessExpression(promise, factory.createIdentifier("then")), /*typeArguments*/ undefined, [emitHelpers().createImportStarCallbackHelper()]);
95533             }
95534             return promise;
95535         }
95536         function createImportCallExpressionCommonJS(arg, containsLexicalThis) {
95537             // import("./blah")
95538             // emit as
95539             // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/
95540             // We have to wrap require in then callback so that require is done in asynchronously
95541             // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
95542             var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
95543             var requireCall = factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
95544             if (compilerOptions.esModuleInterop) {
95545                 requireCall = emitHelpers().createImportStarHelper(requireCall);
95546             }
95547             var func;
95548             if (languageVersion >= 2 /* ES2015 */) {
95549                 func = factory.createArrowFunction(
95550                 /*modifiers*/ undefined, 
95551                 /*typeParameters*/ undefined, 
95552                 /*parameters*/ [], 
95553                 /*type*/ undefined, 
95554                 /*equalsGreaterThanToken*/ undefined, requireCall);
95555             }
95556             else {
95557                 func = factory.createFunctionExpression(
95558                 /*modifiers*/ undefined, 
95559                 /*asteriskToken*/ undefined, 
95560                 /*name*/ undefined, 
95561                 /*typeParameters*/ undefined, 
95562                 /*parameters*/ [], 
95563                 /*type*/ undefined, factory.createBlock([factory.createReturnStatement(requireCall)]));
95564                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
95565                 // that this new function expression indicates it captures 'this' so that the
95566                 // es2015 transformer will properly substitute 'this' with '_this'.
95567                 if (containsLexicalThis) {
95568                     ts.setEmitFlags(func, 8 /* CapturesThis */);
95569                 }
95570             }
95571             return factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
95572         }
95573         function getHelperExpressionForExport(node, innerExpr) {
95574             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
95575                 return innerExpr;
95576             }
95577             if (ts.getExportNeedsImportStarHelper(node)) {
95578                 return emitHelpers().createImportStarHelper(innerExpr);
95579             }
95580             return innerExpr;
95581         }
95582         function getHelperExpressionForImport(node, innerExpr) {
95583             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
95584                 return innerExpr;
95585             }
95586             if (ts.getImportNeedsImportStarHelper(node)) {
95587                 return emitHelpers().createImportStarHelper(innerExpr);
95588             }
95589             if (ts.getImportNeedsImportDefaultHelper(node)) {
95590                 return emitHelpers().createImportDefaultHelper(innerExpr);
95591             }
95592             return innerExpr;
95593         }
95594         /**
95595          * Visits an ImportDeclaration node.
95596          *
95597          * @param node The node to visit.
95598          */
95599         function visitImportDeclaration(node) {
95600             var statements;
95601             var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
95602             if (moduleKind !== ts.ModuleKind.AMD) {
95603                 if (!node.importClause) {
95604                     // import "mod";
95605                     return ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createRequireCall(node)), node), node);
95606                 }
95607                 else {
95608                     var variables = [];
95609                     if (namespaceDeclaration && !ts.isDefaultImport(node)) {
95610                         // import * as n from "mod";
95611                         variables.push(factory.createVariableDeclaration(factory.cloneNode(namespaceDeclaration.name), 
95612                         /*exclamationToken*/ undefined, 
95613                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
95614                     }
95615                     else {
95616                         // import d from "mod";
95617                         // import { x, y } from "mod";
95618                         // import d, { x, y } from "mod";
95619                         // import d, * as n from "mod";
95620                         variables.push(factory.createVariableDeclaration(factory.getGeneratedNameForNode(node), 
95621                         /*exclamationToken*/ undefined, 
95622                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
95623                         if (namespaceDeclaration && ts.isDefaultImport(node)) {
95624                             variables.push(factory.createVariableDeclaration(factory.cloneNode(namespaceDeclaration.name), 
95625                             /*exclamationToken*/ undefined, 
95626                             /*type*/ undefined, factory.getGeneratedNameForNode(node)));
95627                         }
95628                     }
95629                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
95630                     /*modifiers*/ undefined, factory.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), 
95631                     /*location*/ node), 
95632                     /*original*/ node));
95633                 }
95634             }
95635             else if (namespaceDeclaration && ts.isDefaultImport(node)) {
95636                 // import d, * as n from "mod";
95637                 statements = ts.append(statements, factory.createVariableStatement(
95638                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
95639                     ts.setOriginalNode(ts.setTextRange(factory.createVariableDeclaration(factory.cloneNode(namespaceDeclaration.name), 
95640                     /*exclamationToken*/ undefined, 
95641                     /*type*/ undefined, factory.getGeneratedNameForNode(node)), 
95642                     /*location*/ node), 
95643                     /*original*/ node)
95644                 ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
95645             }
95646             if (hasAssociatedEndOfDeclarationMarker(node)) {
95647                 // Defer exports until we encounter an EndOfDeclarationMarker node
95648                 var id = ts.getOriginalNodeId(node);
95649                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
95650             }
95651             else {
95652                 statements = appendExportsOfImportDeclaration(statements, node);
95653             }
95654             return ts.singleOrMany(statements);
95655         }
95656         /**
95657          * Creates a `require()` call to import an external module.
95658          *
95659          * @param importNode The declararation to import.
95660          */
95661         function createRequireCall(importNode) {
95662             var moduleName = ts.getExternalModuleNameLiteral(factory, importNode, currentSourceFile, host, resolver, compilerOptions);
95663             var args = [];
95664             if (moduleName) {
95665                 args.push(moduleName);
95666             }
95667             return factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, args);
95668         }
95669         /**
95670          * Visits an ImportEqualsDeclaration node.
95671          *
95672          * @param node The node to visit.
95673          */
95674         function visitImportEqualsDeclaration(node) {
95675             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
95676             var statements;
95677             if (moduleKind !== ts.ModuleKind.AMD) {
95678                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
95679                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node));
95680                 }
95681                 else {
95682                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
95683                     /*modifiers*/ undefined, factory.createVariableDeclarationList([
95684                         factory.createVariableDeclaration(factory.cloneNode(node.name), 
95685                         /*exclamationToken*/ undefined, 
95686                         /*type*/ undefined, createRequireCall(node))
95687                     ], 
95688                     /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node));
95689                 }
95690             }
95691             else {
95692                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
95693                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(factory.getExportName(node), factory.getLocalName(node))), node), node));
95694                 }
95695             }
95696             if (hasAssociatedEndOfDeclarationMarker(node)) {
95697                 // Defer exports until we encounter an EndOfDeclarationMarker node
95698                 var id = ts.getOriginalNodeId(node);
95699                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
95700             }
95701             else {
95702                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
95703             }
95704             return ts.singleOrMany(statements);
95705         }
95706         /**
95707          * Visits an ExportDeclaration node.
95708          *
95709          * @param The node to visit.
95710          */
95711         function visitExportDeclaration(node) {
95712             if (!node.moduleSpecifier) {
95713                 // Elide export declarations with no module specifier as they are handled
95714                 // elsewhere.
95715                 return undefined;
95716             }
95717             var generatedName = factory.getGeneratedNameForNode(node);
95718             if (node.exportClause && ts.isNamedExports(node.exportClause)) {
95719                 var statements = [];
95720                 // export { x, y } from "mod";
95721                 if (moduleKind !== ts.ModuleKind.AMD) {
95722                     statements.push(ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
95723                     /*modifiers*/ undefined, factory.createVariableDeclarationList([
95724                         factory.createVariableDeclaration(generatedName, 
95725                         /*exclamationToken*/ undefined, 
95726                         /*type*/ undefined, createRequireCall(node))
95727                     ])), 
95728                     /*location*/ node), 
95729                     /* original */ node));
95730                 }
95731                 for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
95732                     var specifier = _a[_i];
95733                     if (languageVersion === 0 /* ES3 */) {
95734                         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));
95735                     }
95736                     else {
95737                         var exportNeedsImportDefault = !!compilerOptions.esModuleInterop &&
95738                             !(ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) &&
95739                             ts.idText(specifier.propertyName || specifier.name) === "default";
95740                         var exportedValue = factory.createPropertyAccessExpression(exportNeedsImportDefault ? emitHelpers().createImportDefaultHelper(generatedName) : generatedName, specifier.propertyName || specifier.name);
95741                         statements.push(ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(factory.getExportName(specifier), exportedValue, /* location */ undefined, /* liveBinding */ true)), specifier), specifier));
95742                     }
95743                 }
95744                 return ts.singleOrMany(statements);
95745             }
95746             else if (node.exportClause) {
95747                 var statements = [];
95748                 // export * as ns from "mod";
95749                 // export * as default from "mod";
95750                 statements.push(ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(factory.cloneNode(node.exportClause.name), getHelperExpressionForExport(node, moduleKind !== ts.ModuleKind.AMD ?
95751                     createRequireCall(node) :
95752                     ts.isExportNamespaceAsDefaultDeclaration(node) ? generatedName :
95753                         factory.createIdentifier(ts.idText(node.exportClause.name))))), node), node));
95754                 return ts.singleOrMany(statements);
95755             }
95756             else {
95757                 // export * from "mod";
95758                 return ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(emitHelpers().createExportStarHelper(moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node);
95759             }
95760         }
95761         /**
95762          * Visits an ExportAssignment node.
95763          *
95764          * @param node The node to visit.
95765          */
95766         function visitExportAssignment(node) {
95767             if (node.isExportEquals) {
95768                 return undefined;
95769             }
95770             var statements;
95771             var original = node.original;
95772             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
95773                 // Defer exports until we encounter an EndOfDeclarationMarker node
95774                 var id = ts.getOriginalNodeId(node);
95775                 deferredExports[id] = appendExportStatement(deferredExports[id], factory.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
95776             }
95777             else {
95778                 statements = appendExportStatement(statements, factory.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
95779             }
95780             return ts.singleOrMany(statements);
95781         }
95782         /**
95783          * Visits a FunctionDeclaration node.
95784          *
95785          * @param node The node to visit.
95786          */
95787         function visitFunctionDeclaration(node) {
95788             var statements;
95789             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
95790                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(
95791                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
95792                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), 
95793                 /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), 
95794                 /*location*/ node), 
95795                 /*original*/ node));
95796             }
95797             else {
95798                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
95799             }
95800             if (hasAssociatedEndOfDeclarationMarker(node)) {
95801                 // Defer exports until we encounter an EndOfDeclarationMarker node
95802                 var id = ts.getOriginalNodeId(node);
95803                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
95804             }
95805             else {
95806                 statements = appendExportsOfHoistedDeclaration(statements, node);
95807             }
95808             return ts.singleOrMany(statements);
95809         }
95810         /**
95811          * Visits a ClassDeclaration node.
95812          *
95813          * @param node The node to visit.
95814          */
95815         function visitClassDeclaration(node) {
95816             var statements;
95817             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
95818                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration(
95819                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
95820                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
95821             }
95822             else {
95823                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
95824             }
95825             if (hasAssociatedEndOfDeclarationMarker(node)) {
95826                 // Defer exports until we encounter an EndOfDeclarationMarker node
95827                 var id = ts.getOriginalNodeId(node);
95828                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
95829             }
95830             else {
95831                 statements = appendExportsOfHoistedDeclaration(statements, node);
95832             }
95833             return ts.singleOrMany(statements);
95834         }
95835         /**
95836          * Visits a VariableStatement node.
95837          *
95838          * @param node The node to visit.
95839          */
95840         function visitVariableStatement(node) {
95841             var statements;
95842             var variables;
95843             var expressions;
95844             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
95845                 var modifiers = void 0;
95846                 var removeCommentsOnExpressions = false;
95847                 // If we're exporting these variables, then these just become assignments to 'exports.x'.
95848                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
95849                     var variable = _a[_i];
95850                     if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
95851                         if (!modifiers) {
95852                             modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
95853                         }
95854                         variables = ts.append(variables, variable);
95855                     }
95856                     else if (variable.initializer) {
95857                         if (!ts.isBindingPattern(variable.name) && (ts.isArrowFunction(variable.initializer) || ts.isFunctionExpression(variable.initializer) || ts.isClassExpression(variable.initializer))) {
95858                             var expression = factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), variable.name), 
95859                             /*location*/ variable.name), factory.createIdentifier(ts.getTextOfIdentifierOrLiteral(variable.name)));
95860                             var updatedVariable = factory.createVariableDeclaration(variable.name, variable.exclamationToken, variable.type, ts.visitNode(variable.initializer, moduleExpressionElementVisitor));
95861                             variables = ts.append(variables, updatedVariable);
95862                             expressions = ts.append(expressions, expression);
95863                             removeCommentsOnExpressions = true;
95864                         }
95865                         else {
95866                             expressions = ts.append(expressions, transformInitializedVariable(variable));
95867                         }
95868                     }
95869                 }
95870                 if (variables) {
95871                     statements = ts.append(statements, factory.updateVariableStatement(node, modifiers, factory.updateVariableDeclarationList(node.declarationList, variables)));
95872                 }
95873                 if (expressions) {
95874                     var statement = ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node), node);
95875                     if (removeCommentsOnExpressions) {
95876                         ts.removeAllComments(statement);
95877                     }
95878                     statements = ts.append(statements, statement);
95879                 }
95880             }
95881             else {
95882                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
95883             }
95884             if (hasAssociatedEndOfDeclarationMarker(node)) {
95885                 // Defer exports until we encounter an EndOfDeclarationMarker node
95886                 var id = ts.getOriginalNodeId(node);
95887                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
95888             }
95889             else {
95890                 statements = appendExportsOfVariableStatement(statements, node);
95891             }
95892             return ts.singleOrMany(statements);
95893         }
95894         function createAllExportExpressions(name, value, location) {
95895             var exportedNames = getExports(name);
95896             if (exportedNames) {
95897                 // For each additional export of the declaration, apply an export assignment.
95898                 var expression = ts.isExportName(name) ? value : factory.createAssignment(name, value);
95899                 for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
95900                     var exportName = exportedNames_1[_i];
95901                     // Mark the node to prevent triggering substitution.
95902                     ts.setEmitFlags(expression, 4 /* NoSubstitution */);
95903                     expression = createExportExpression(exportName, expression, /*location*/ location);
95904                 }
95905                 return expression;
95906             }
95907             return factory.createAssignment(name, value);
95908         }
95909         /**
95910          * Transforms an exported variable with an initializer into an expression.
95911          *
95912          * @param node The node to transform.
95913          */
95914         function transformInitializedVariable(node) {
95915             if (ts.isBindingPattern(node.name)) {
95916                 return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), 
95917                 /*visitor*/ undefined, context, 0 /* All */, 
95918                 /*needsValue*/ false, createAllExportExpressions);
95919             }
95920             else {
95921                 return factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), node.name), 
95922                 /*location*/ node.name), node.initializer ? ts.visitNode(node.initializer, moduleExpressionElementVisitor) : factory.createVoidZero());
95923             }
95924         }
95925         /**
95926          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
95927          * and transformed declaration.
95928          *
95929          * @param node The node to visit.
95930          */
95931         function visitMergeDeclarationMarker(node) {
95932             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
95933             // declaration we do not emit a leading variable declaration. To preserve the
95934             // begin/end semantics of the declararation and to properly handle exports
95935             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
95936             //
95937             // To balance the declaration, add the exports of the elided variable
95938             // statement.
95939             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) {
95940                 var id = ts.getOriginalNodeId(node);
95941                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
95942             }
95943             return node;
95944         }
95945         /**
95946          * Determines whether a node has an associated EndOfDeclarationMarker.
95947          *
95948          * @param node The node to test.
95949          */
95950         function hasAssociatedEndOfDeclarationMarker(node) {
95951             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
95952         }
95953         /**
95954          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
95955          * declaration.
95956          *
95957          * @param node The node to visit.
95958          */
95959         function visitEndOfDeclarationMarker(node) {
95960             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
95961             // end of the transformed declaration. We use this marker to emit any deferred exports
95962             // of the declaration.
95963             var id = ts.getOriginalNodeId(node);
95964             var statements = deferredExports[id];
95965             if (statements) {
95966                 delete deferredExports[id];
95967                 return ts.append(statements, node);
95968             }
95969             return node;
95970         }
95971         /**
95972          * Appends the exports of an ImportDeclaration to a statement list, returning the
95973          * statement list.
95974          *
95975          * @param statements A statement list to which the down-level export statements are to be
95976          * appended. If `statements` is `undefined`, a new array is allocated if statements are
95977          * appended.
95978          * @param decl The declaration whose exports are to be recorded.
95979          */
95980         function appendExportsOfImportDeclaration(statements, decl) {
95981             if (currentModuleInfo.exportEquals) {
95982                 return statements;
95983             }
95984             var importClause = decl.importClause;
95985             if (!importClause) {
95986                 return statements;
95987             }
95988             if (importClause.name) {
95989                 statements = appendExportsOfDeclaration(statements, importClause);
95990             }
95991             var namedBindings = importClause.namedBindings;
95992             if (namedBindings) {
95993                 switch (namedBindings.kind) {
95994                     case 263 /* NamespaceImport */:
95995                         statements = appendExportsOfDeclaration(statements, namedBindings);
95996                         break;
95997                     case 264 /* NamedImports */:
95998                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
95999                             var importBinding = _a[_i];
96000                             statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true);
96001                         }
96002                         break;
96003                 }
96004             }
96005             return statements;
96006         }
96007         /**
96008          * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
96009          * statement list.
96010          *
96011          * @param statements A statement list to which the down-level export statements are to be
96012          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96013          * appended.
96014          * @param decl The declaration whose exports are to be recorded.
96015          */
96016         function appendExportsOfImportEqualsDeclaration(statements, decl) {
96017             if (currentModuleInfo.exportEquals) {
96018                 return statements;
96019             }
96020             return appendExportsOfDeclaration(statements, decl);
96021         }
96022         /**
96023          * Appends the exports of a VariableStatement to a statement list, returning the statement
96024          * list.
96025          *
96026          * @param statements A statement list to which the down-level export statements are to be
96027          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96028          * appended.
96029          * @param node The VariableStatement whose exports are to be recorded.
96030          */
96031         function appendExportsOfVariableStatement(statements, node) {
96032             if (currentModuleInfo.exportEquals) {
96033                 return statements;
96034             }
96035             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
96036                 var decl = _a[_i];
96037                 statements = appendExportsOfBindingElement(statements, decl);
96038             }
96039             return statements;
96040         }
96041         /**
96042          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
96043          * returning the statement list.
96044          *
96045          * @param statements A statement list to which the down-level export statements are to be
96046          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96047          * appended.
96048          * @param decl The declaration whose exports are to be recorded.
96049          */
96050         function appendExportsOfBindingElement(statements, decl) {
96051             if (currentModuleInfo.exportEquals) {
96052                 return statements;
96053             }
96054             if (ts.isBindingPattern(decl.name)) {
96055                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
96056                     var element = _a[_i];
96057                     if (!ts.isOmittedExpression(element)) {
96058                         statements = appendExportsOfBindingElement(statements, element);
96059                     }
96060                 }
96061             }
96062             else if (!ts.isGeneratedIdentifier(decl.name)) {
96063                 statements = appendExportsOfDeclaration(statements, decl);
96064             }
96065             return statements;
96066         }
96067         /**
96068          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
96069          * returning the statement list.
96070          *
96071          * @param statements A statement list to which the down-level export statements are to be
96072          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96073          * appended.
96074          * @param decl The declaration whose exports are to be recorded.
96075          */
96076         function appendExportsOfHoistedDeclaration(statements, decl) {
96077             if (currentModuleInfo.exportEquals) {
96078                 return statements;
96079             }
96080             if (ts.hasSyntacticModifier(decl, 1 /* Export */)) {
96081                 var exportName = ts.hasSyntacticModifier(decl, 512 /* Default */) ? factory.createIdentifier("default") : factory.getDeclarationName(decl);
96082                 statements = appendExportStatement(statements, exportName, factory.getLocalName(decl), /*location*/ decl);
96083             }
96084             if (decl.name) {
96085                 statements = appendExportsOfDeclaration(statements, decl);
96086             }
96087             return statements;
96088         }
96089         /**
96090          * Appends the exports of a declaration to a statement list, returning the statement list.
96091          *
96092          * @param statements A statement list to which the down-level export statements are to be
96093          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96094          * appended.
96095          * @param decl The declaration to export.
96096          */
96097         function appendExportsOfDeclaration(statements, decl, liveBinding) {
96098             var name = factory.getDeclarationName(decl);
96099             var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name));
96100             if (exportSpecifiers) {
96101                 for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
96102                     var exportSpecifier = exportSpecifiers_1[_i];
96103                     statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /* allowComments */ undefined, liveBinding);
96104                 }
96105             }
96106             return statements;
96107         }
96108         /**
96109          * Appends the down-level representation of an export to a statement list, returning the
96110          * statement list.
96111          *
96112          * @param statements A statement list to which the down-level export statements are to be
96113          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96114          * appended.
96115          * @param exportName The name of the export.
96116          * @param expression The expression to export.
96117          * @param location The location to use for source maps and comments for the export.
96118          * @param allowComments Whether to allow comments on the export.
96119          */
96120         function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) {
96121             statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding));
96122             return statements;
96123         }
96124         function createUnderscoreUnderscoreESModule() {
96125             var statement;
96126             if (languageVersion === 0 /* ES3 */) {
96127                 statement = factory.createExpressionStatement(createExportExpression(factory.createIdentifier("__esModule"), factory.createTrue()));
96128             }
96129             else {
96130                 statement = factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "defineProperty"), 
96131                 /*typeArguments*/ undefined, [
96132                     factory.createIdentifier("exports"),
96133                     factory.createStringLiteral("__esModule"),
96134                     factory.createObjectLiteralExpression([
96135                         factory.createPropertyAssignment("value", factory.createTrue())
96136                     ])
96137                 ]));
96138             }
96139             ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
96140             return statement;
96141         }
96142         /**
96143          * Creates a call to the current file's export function to export a value.
96144          *
96145          * @param name The bound name of the export.
96146          * @param value The exported value.
96147          * @param location The location to use for source maps and comments for the export.
96148          * @param allowComments An optional value indicating whether to emit comments for the statement.
96149          */
96150         function createExportStatement(name, value, location, allowComments, liveBinding) {
96151             var statement = ts.setTextRange(factory.createExpressionStatement(createExportExpression(name, value, /* location */ undefined, liveBinding)), location);
96152             ts.startOnNewLine(statement);
96153             if (!allowComments) {
96154                 ts.setEmitFlags(statement, 1536 /* NoComments */);
96155             }
96156             return statement;
96157         }
96158         /**
96159          * Creates a call to the current file's export function to export a value.
96160          *
96161          * @param name The bound name of the export.
96162          * @param value The exported value.
96163          * @param location The location to use for source maps and comments for the export.
96164          */
96165         function createExportExpression(name, value, location, liveBinding) {
96166             return ts.setTextRange(liveBinding && languageVersion !== 0 /* ES3 */ ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "defineProperty"), 
96167             /*typeArguments*/ undefined, [
96168                 factory.createIdentifier("exports"),
96169                 factory.createStringLiteralFromNode(name),
96170                 factory.createObjectLiteralExpression([
96171                     factory.createPropertyAssignment("enumerable", factory.createTrue()),
96172                     factory.createPropertyAssignment("get", factory.createFunctionExpression(
96173                     /*modifiers*/ undefined, 
96174                     /*asteriskToken*/ undefined, 
96175                     /*name*/ undefined, 
96176                     /*typeParameters*/ undefined, 
96177                     /*parameters*/ [], 
96178                     /*type*/ undefined, factory.createBlock([factory.createReturnStatement(value)])))
96179                 ])
96180             ]) : factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(name)), value), location);
96181         }
96182         //
96183         // Modifier Visitors
96184         //
96185         /**
96186          * Visit nodes to elide module-specific modifiers.
96187          *
96188          * @param node The node to visit.
96189          */
96190         function modifierVisitor(node) {
96191             // Elide module-specific modifiers.
96192             switch (node.kind) {
96193                 case 92 /* ExportKeyword */:
96194                 case 87 /* DefaultKeyword */:
96195                     return undefined;
96196             }
96197             return node;
96198         }
96199         //
96200         // Emit Notification
96201         //
96202         /**
96203          * Hook for node emit notifications.
96204          *
96205          * @param hint A hint as to the intended usage of the node.
96206          * @param node The node to emit.
96207          * @param emit A callback used to emit the node in the printer.
96208          */
96209         function onEmitNode(hint, node, emitCallback) {
96210             if (node.kind === 297 /* SourceFile */) {
96211                 currentSourceFile = node;
96212                 currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
96213                 noSubstitution = [];
96214                 previousOnEmitNode(hint, node, emitCallback);
96215                 currentSourceFile = undefined;
96216                 currentModuleInfo = undefined;
96217                 noSubstitution = undefined;
96218             }
96219             else {
96220                 previousOnEmitNode(hint, node, emitCallback);
96221             }
96222         }
96223         //
96224         // Substitutions
96225         //
96226         /**
96227          * Hooks node substitutions.
96228          *
96229          * @param hint A hint as to the intended usage of the node.
96230          * @param node The node to substitute.
96231          */
96232         function onSubstituteNode(hint, node) {
96233             node = previousOnSubstituteNode(hint, node);
96234             if (node.id && noSubstitution[node.id]) {
96235                 return node;
96236             }
96237             if (hint === 1 /* Expression */) {
96238                 return substituteExpression(node);
96239             }
96240             else if (ts.isShorthandPropertyAssignment(node)) {
96241                 return substituteShorthandPropertyAssignment(node);
96242             }
96243             return node;
96244         }
96245         /**
96246          * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
96247          * or exported symbol.
96248          *
96249          * @param node The node to substitute.
96250          */
96251         function substituteShorthandPropertyAssignment(node) {
96252             var name = node.name;
96253             var exportedOrImportedName = substituteExpressionIdentifier(name);
96254             if (exportedOrImportedName !== name) {
96255                 // A shorthand property with an assignment initializer is probably part of a
96256                 // destructuring assignment
96257                 if (node.objectAssignmentInitializer) {
96258                     var initializer = factory.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
96259                     return ts.setTextRange(factory.createPropertyAssignment(name, initializer), node);
96260                 }
96261                 return ts.setTextRange(factory.createPropertyAssignment(name, exportedOrImportedName), node);
96262             }
96263             return node;
96264         }
96265         /**
96266          * Substitution for an Expression that may contain an imported or exported symbol.
96267          *
96268          * @param node The node to substitute.
96269          */
96270         function substituteExpression(node) {
96271             switch (node.kind) {
96272                 case 78 /* Identifier */:
96273                     return substituteExpressionIdentifier(node);
96274                 case 216 /* BinaryExpression */:
96275                     return substituteBinaryExpression(node);
96276                 case 215 /* PostfixUnaryExpression */:
96277                 case 214 /* PrefixUnaryExpression */:
96278                     return substituteUnaryExpression(node);
96279             }
96280             return node;
96281         }
96282         /**
96283          * Substitution for an Identifier expression that may contain an imported or exported
96284          * symbol.
96285          *
96286          * @param node The node to substitute.
96287          */
96288         function substituteExpressionIdentifier(node) {
96289             var _a, _b;
96290             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
96291                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
96292                 if (externalHelpersModuleName) {
96293                     return factory.createPropertyAccessExpression(externalHelpersModuleName, node);
96294                 }
96295                 return node;
96296             }
96297             if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) {
96298                 var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
96299                 if (exportContainer && exportContainer.kind === 297 /* SourceFile */) {
96300                     return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), 
96301                     /*location*/ node);
96302                 }
96303                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
96304                 if (importDeclaration) {
96305                     if (ts.isImportClause(importDeclaration)) {
96306                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")), 
96307                         /*location*/ node);
96308                     }
96309                     else if (ts.isImportSpecifier(importDeclaration)) {
96310                         var name = importDeclaration.propertyName || importDeclaration.name;
96311                         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)), 
96312                         /*location*/ node);
96313                     }
96314                 }
96315             }
96316             return node;
96317         }
96318         /**
96319          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
96320          *
96321          * @param node The node to substitute.
96322          */
96323         function substituteBinaryExpression(node) {
96324             // When we see an assignment expression whose left-hand side is an exported symbol,
96325             // we should ensure all exports of that symbol are updated with the correct value.
96326             //
96327             // - We do not substitute generated identifiers for any reason.
96328             // - We do not substitute identifiers tagged with the LocalName flag.
96329             // - We do not substitute identifiers that were originally the name of an enum or
96330             //   namespace due to how they are transformed in TypeScript.
96331             // - We only substitute identifiers that are exported at the top level.
96332             if (ts.isAssignmentOperator(node.operatorToken.kind)
96333                 && ts.isIdentifier(node.left)
96334                 && !ts.isGeneratedIdentifier(node.left)
96335                 && !ts.isLocalName(node.left)
96336                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
96337                 var exportedNames = getExports(node.left);
96338                 if (exportedNames) {
96339                     // For each additional export of the declaration, apply an export assignment.
96340                     var expression = node;
96341                     for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
96342                         var exportName = exportedNames_2[_i];
96343                         // Mark the node to prevent triggering this rule again.
96344                         noSubstitution[ts.getNodeId(expression)] = true;
96345                         expression = createExportExpression(exportName, expression, /*location*/ node);
96346                     }
96347                     return expression;
96348                 }
96349             }
96350             return node;
96351         }
96352         /**
96353          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
96354          *
96355          * @param node The node to substitute.
96356          */
96357         function substituteUnaryExpression(node) {
96358             // When we see a prefix or postfix increment expression whose operand is an exported
96359             // symbol, we should ensure all exports of that symbol are updated with the correct
96360             // value.
96361             //
96362             // - We do not substitute generated identifiers for any reason.
96363             // - We do not substitute identifiers tagged with the LocalName flag.
96364             // - We do not substitute identifiers that were originally the name of an enum or
96365             //   namespace due to how they are transformed in TypeScript.
96366             // - We only substitute identifiers that are exported at the top level.
96367             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
96368                 && ts.isIdentifier(node.operand)
96369                 && !ts.isGeneratedIdentifier(node.operand)
96370                 && !ts.isLocalName(node.operand)
96371                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
96372                 var exportedNames = getExports(node.operand);
96373                 if (exportedNames) {
96374                     var expression = node.kind === 215 /* PostfixUnaryExpression */
96375                         ? ts.setTextRange(factory.createBinaryExpression(node.operand, factory.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), factory.createNumericLiteral(1)), 
96376                         /*location*/ node)
96377                         : node;
96378                     for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
96379                         var exportName = exportedNames_3[_i];
96380                         // Mark the node to prevent triggering this rule again.
96381                         noSubstitution[ts.getNodeId(expression)] = true;
96382                         expression = factory.createParenthesizedExpression(createExportExpression(exportName, expression));
96383                     }
96384                     return expression;
96385                 }
96386             }
96387             return node;
96388         }
96389         /**
96390          * Gets the additional exports of a name.
96391          *
96392          * @param name The name.
96393          */
96394         function getExports(name) {
96395             if (!ts.isGeneratedIdentifier(name)) {
96396                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
96397                     || resolver.getReferencedValueDeclaration(name);
96398                 if (valueDeclaration) {
96399                     return currentModuleInfo
96400                         && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
96401                 }
96402             }
96403         }
96404     }
96405     ts.transformModule = transformModule;
96406     // emit helper for dynamic import
96407     var dynamicImportUMDHelper = {
96408         name: "typescript:dynamicimport-sync-require",
96409         scoped: true,
96410         text: "\n            var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
96411     };
96412 })(ts || (ts = {}));
96413 /*@internal*/
96414 var ts;
96415 (function (ts) {
96416     function transformSystemModule(context) {
96417         var factory = context.factory, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
96418         var compilerOptions = context.getCompilerOptions();
96419         var resolver = context.getEmitResolver();
96420         var host = context.getEmitHost();
96421         var previousOnSubstituteNode = context.onSubstituteNode;
96422         var previousOnEmitNode = context.onEmitNode;
96423         context.onSubstituteNode = onSubstituteNode;
96424         context.onEmitNode = onEmitNode;
96425         context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers for imported symbols.
96426         context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols
96427         context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols.
96428         context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
96429         context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
96430         context.enableSubstitution(226 /* MetaProperty */); // Substitutes 'import.meta'
96431         context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file.
96432         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
96433         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
96434         var exportFunctionsMap = []; // The export function associated with a source file.
96435         var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
96436         var contextObjectMap = []; // The context object associated with a source file.
96437         var currentSourceFile; // The current file.
96438         var moduleInfo; // ExternalModuleInfo for the current file.
96439         var exportFunction; // The export function for the current file.
96440         var contextObject; // The context object for the current file.
96441         var hoistedStatements;
96442         var enclosingBlockScopedContainer;
96443         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
96444         return ts.chainBundle(context, transformSourceFile);
96445         /**
96446          * Transforms the module aspects of a SourceFile.
96447          *
96448          * @param node The SourceFile node.
96449          */
96450         function transformSourceFile(node) {
96451             if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
96452                 return node;
96453             }
96454             var id = ts.getOriginalNodeId(node);
96455             currentSourceFile = node;
96456             enclosingBlockScopedContainer = node;
96457             // System modules have the following shape:
96458             //
96459             //     System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
96460             //
96461             // The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
96462             // is used to publish exported values. 'exports' returns its 'value' argument so in
96463             // most cases expressions that mutate exported values can be rewritten as:
96464             //
96465             //     expr -> exports('name', expr)
96466             //
96467             // The only exception in this rule is postfix unary operators,
96468             // see comment to 'substitutePostfixUnaryExpression' for more details
96469             // Collect information about the external module and dependency groups.
96470             moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(context, node, resolver, compilerOptions);
96471             // Make sure that the name of the 'exports' function does not conflict with
96472             // existing identifiers.
96473             exportFunction = factory.createUniqueName("exports");
96474             exportFunctionsMap[id] = exportFunction;
96475             contextObject = contextObjectMap[id] = factory.createUniqueName("context");
96476             // Add the body of the module.
96477             var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
96478             var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
96479             var moduleBodyFunction = factory.createFunctionExpression(
96480             /*modifiers*/ undefined, 
96481             /*asteriskToken*/ undefined, 
96482             /*name*/ undefined, 
96483             /*typeParameters*/ undefined, [
96484                 factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
96485                 factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
96486             ], 
96487             /*type*/ undefined, moduleBodyBlock);
96488             // Write the call to `System.register`
96489             // Clear the emit-helpers flag for later passes since we'll have already used it in the module body
96490             // So the helper will be emit at the correct position instead of at the top of the source-file
96491             var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions);
96492             var dependencies = factory.createArrayLiteralExpression(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; }));
96493             var updated = ts.setEmitFlags(factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
96494                 factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("System"), "register"), 
96495                 /*typeArguments*/ undefined, moduleName
96496                     ? [moduleName, dependencies, moduleBodyFunction]
96497                     : [dependencies, moduleBodyFunction]))
96498             ]), node.statements)), 1024 /* NoTrailingComments */);
96499             if (!ts.outFile(compilerOptions)) {
96500                 ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; });
96501             }
96502             if (noSubstitution) {
96503                 noSubstitutionMap[id] = noSubstitution;
96504                 noSubstitution = undefined;
96505             }
96506             currentSourceFile = undefined;
96507             moduleInfo = undefined;
96508             exportFunction = undefined;
96509             contextObject = undefined;
96510             hoistedStatements = undefined;
96511             enclosingBlockScopedContainer = undefined;
96512             return updated;
96513         }
96514         /**
96515          * Collects the dependency groups for this files imports.
96516          *
96517          * @param externalImports The imports for the file.
96518          */
96519         function collectDependencyGroups(externalImports) {
96520             var groupIndices = new ts.Map();
96521             var dependencyGroups = [];
96522             for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) {
96523                 var externalImport = externalImports_1[_i];
96524                 var externalModuleName = ts.getExternalModuleNameLiteral(factory, externalImport, currentSourceFile, host, resolver, compilerOptions);
96525                 if (externalModuleName) {
96526                     var text = externalModuleName.text;
96527                     var groupIndex = groupIndices.get(text);
96528                     if (groupIndex !== undefined) {
96529                         // deduplicate/group entries in dependency list by the dependency name
96530                         dependencyGroups[groupIndex].externalImports.push(externalImport);
96531                     }
96532                     else {
96533                         groupIndices.set(text, dependencyGroups.length);
96534                         dependencyGroups.push({
96535                             name: externalModuleName,
96536                             externalImports: [externalImport]
96537                         });
96538                     }
96539                 }
96540             }
96541             return dependencyGroups;
96542         }
96543         /**
96544          * Adds the statements for the module body function for the source file.
96545          *
96546          * @param node The source file for the module.
96547          * @param dependencyGroups The grouped dependencies of the module.
96548          */
96549         function createSystemModuleBody(node, dependencyGroups) {
96550             // Shape of the body in system modules:
96551             //
96552             //  function (exports) {
96553             //      <list of local aliases for imports>
96554             //      <hoisted variable declarations>
96555             //      <hoisted function declarations>
96556             //      return {
96557             //          setters: [
96558             //              <list of setter function for imports>
96559             //          ],
96560             //          execute: function() {
96561             //              <module statements>
96562             //          }
96563             //      }
96564             //      <temp declarations>
96565             //  }
96566             //
96567             // i.e:
96568             //
96569             //   import {x} from 'file1'
96570             //   var y = 1;
96571             //   export function foo() { return y + x(); }
96572             //   console.log(y);
96573             //
96574             // Will be transformed to:
96575             //
96576             //  function(exports) {
96577             //      function foo() { return y + file_1.x(); }
96578             //      exports("foo", foo);
96579             //      var file_1, y;
96580             //      return {
96581             //          setters: [
96582             //              function(v) { file_1 = v }
96583             //          ],
96584             //          execute(): function() {
96585             //              y = 1;
96586             //              console.log(y);
96587             //          }
96588             //      };
96589             //  }
96590             var statements = [];
96591             // We start a new lexical environment in this function body, but *not* in the
96592             // body of the execute function. This allows us to emit temporary declarations
96593             // only in the outer module body and not in the inner one.
96594             startLexicalEnvironment();
96595             // Add any prologue directives.
96596             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
96597             var statementOffset = factory.copyPrologue(node.statements, statements, ensureUseStrict, sourceElementVisitor);
96598             // var __moduleName = context_1 && context_1.id;
96599             statements.push(factory.createVariableStatement(
96600             /*modifiers*/ undefined, factory.createVariableDeclarationList([
96601                 factory.createVariableDeclaration("__moduleName", 
96602                 /*exclamationToken*/ undefined, 
96603                 /*type*/ undefined, factory.createLogicalAnd(contextObject, factory.createPropertyAccessExpression(contextObject, "id")))
96604             ])));
96605             // Visit the synthetic external helpers import declaration if present
96606             ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement);
96607             // Visit the statements of the source file, emitting any transformations into
96608             // the `executeStatements` array. We do this *before* we fill the `setters` array
96609             // as we both emit transformations as well as aggregate some data used when creating
96610             // setters. This allows us to reduce the number of times we need to loop through the
96611             // statements of the source file.
96612             var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset);
96613             // Emit early exports for function declarations.
96614             ts.addRange(statements, hoistedStatements);
96615             // We emit hoisted variables early to align roughly with our previous emit output.
96616             // Two key differences in this approach are:
96617             // - Temporary variables will appear at the top rather than at the bottom of the file
96618             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
96619             var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
96620             var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ?
96621                 factory.createModifiersFromModifierFlags(256 /* Async */) :
96622                 undefined;
96623             var moduleObject = factory.createObjectLiteralExpression([
96624                 factory.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
96625                 factory.createPropertyAssignment("execute", factory.createFunctionExpression(modifiers, 
96626                 /*asteriskToken*/ undefined, 
96627                 /*name*/ undefined, 
96628                 /*typeParameters*/ undefined, 
96629                 /*parameters*/ [], 
96630                 /*type*/ undefined, factory.createBlock(executeStatements, /*multiLine*/ true)))
96631             ], /*multiLine*/ true);
96632             statements.push(factory.createReturnStatement(moduleObject));
96633             return factory.createBlock(statements, /*multiLine*/ true);
96634         }
96635         /**
96636          * Adds an exportStar function to a statement list if it is needed for the file.
96637          *
96638          * @param statements A statement list.
96639          */
96640         function addExportStarIfNeeded(statements) {
96641             if (!moduleInfo.hasExportStarsToExportValues) {
96642                 return;
96643             }
96644             // when resolving exports local exported entries/indirect exported entries in the module
96645             // should always win over entries with similar names that were added via star exports
96646             // to support this we store names of local/indirect exported entries in a set.
96647             // this set is used to filter names brought by star expors.
96648             // local names set should only be added if we have anything exported
96649             if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
96650                 // no exported declarations (export var ...) or export specifiers (export {x})
96651                 // check if we have any non star export declarations.
96652                 var hasExportDeclarationWithExportClause = false;
96653                 for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) {
96654                     var externalImport = _a[_i];
96655                     if (externalImport.kind === 267 /* ExportDeclaration */ && externalImport.exportClause) {
96656                         hasExportDeclarationWithExportClause = true;
96657                         break;
96658                     }
96659                 }
96660                 if (!hasExportDeclarationWithExportClause) {
96661                     // we still need to emit exportStar helper
96662                     var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined);
96663                     statements.push(exportStarFunction_1);
96664                     return exportStarFunction_1.name;
96665                 }
96666             }
96667             var exportedNames = [];
96668             if (moduleInfo.exportedNames) {
96669                 for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) {
96670                     var exportedLocalName = _c[_b];
96671                     if (exportedLocalName.escapedText === "default") {
96672                         continue;
96673                     }
96674                     // write name of exported declaration, i.e 'export var x...'
96675                     exportedNames.push(factory.createPropertyAssignment(factory.createStringLiteralFromNode(exportedLocalName), factory.createTrue()));
96676                 }
96677             }
96678             var exportedNamesStorageRef = factory.createUniqueName("exportedNames");
96679             statements.push(factory.createVariableStatement(
96680             /*modifiers*/ undefined, factory.createVariableDeclarationList([
96681                 factory.createVariableDeclaration(exportedNamesStorageRef, 
96682                 /*exclamationToken*/ undefined, 
96683                 /*type*/ undefined, factory.createObjectLiteralExpression(exportedNames, /*multiline*/ true))
96684             ])));
96685             var exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
96686             statements.push(exportStarFunction);
96687             return exportStarFunction.name;
96688         }
96689         /**
96690          * Creates an exportStar function for the file, with an optional set of excluded local
96691          * names.
96692          *
96693          * @param localNames An optional reference to an object containing a set of excluded local
96694          * names.
96695          */
96696         function createExportStarFunction(localNames) {
96697             var exportStarFunction = factory.createUniqueName("exportStar");
96698             var m = factory.createIdentifier("m");
96699             var n = factory.createIdentifier("n");
96700             var exports = factory.createIdentifier("exports");
96701             var condition = factory.createStrictInequality(n, factory.createStringLiteral("default"));
96702             if (localNames) {
96703                 condition = factory.createLogicalAnd(condition, factory.createLogicalNot(factory.createCallExpression(factory.createPropertyAccessExpression(localNames, "hasOwnProperty"), 
96704                 /*typeArguments*/ undefined, [n])));
96705             }
96706             return factory.createFunctionDeclaration(
96707             /*decorators*/ undefined, 
96708             /*modifiers*/ undefined, 
96709             /*asteriskToken*/ undefined, exportStarFunction, 
96710             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], 
96711             /*type*/ undefined, factory.createBlock([
96712                 factory.createVariableStatement(
96713                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
96714                     factory.createVariableDeclaration(exports, 
96715                     /*exclamationToken*/ undefined, 
96716                     /*type*/ undefined, factory.createObjectLiteralExpression([]))
96717                 ])),
96718                 factory.createForInStatement(factory.createVariableDeclarationList([
96719                     factory.createVariableDeclaration(n)
96720                 ]), m, factory.createBlock([
96721                     ts.setEmitFlags(factory.createIfStatement(condition, factory.createExpressionStatement(factory.createAssignment(factory.createElementAccessExpression(exports, n), factory.createElementAccessExpression(m, n)))), 1 /* SingleLine */)
96722                 ])),
96723                 factory.createExpressionStatement(factory.createCallExpression(exportFunction, 
96724                 /*typeArguments*/ undefined, [exports]))
96725             ], /*multiline*/ true));
96726         }
96727         /**
96728          * Creates an array setter callbacks for each dependency group.
96729          *
96730          * @param exportStarFunction A reference to an exportStarFunction for the file.
96731          * @param dependencyGroups An array of grouped dependencies.
96732          */
96733         function createSettersArray(exportStarFunction, dependencyGroups) {
96734             var setters = [];
96735             for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
96736                 var group_2 = dependencyGroups_1[_i];
96737                 // derive a unique name for parameter from the first named entry in the group
96738                 var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(factory, i, currentSourceFile); });
96739                 var parameterName = localName ? factory.getGeneratedNameForNode(localName) : factory.createUniqueName("");
96740                 var statements = [];
96741                 for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
96742                     var entry = _b[_a];
96743                     var importVariableName = ts.getLocalNameForExternalImport(factory, entry, currentSourceFile); // TODO: GH#18217
96744                     switch (entry.kind) {
96745                         case 261 /* ImportDeclaration */:
96746                             if (!entry.importClause) {
96747                                 // 'import "..."' case
96748                                 // module is imported only for side-effects, no emit required
96749                                 break;
96750                             }
96751                         // falls through
96752                         case 260 /* ImportEqualsDeclaration */:
96753                             ts.Debug.assert(importVariableName !== undefined);
96754                             // save import into the local
96755                             statements.push(factory.createExpressionStatement(factory.createAssignment(importVariableName, parameterName)));
96756                             break;
96757                         case 267 /* ExportDeclaration */:
96758                             ts.Debug.assert(importVariableName !== undefined);
96759                             if (entry.exportClause) {
96760                                 if (ts.isNamedExports(entry.exportClause)) {
96761                                     //  export {a, b as c} from 'foo'
96762                                     //
96763                                     // emit as:
96764                                     //
96765                                     //  exports_({
96766                                     //     "a": _["a"],
96767                                     //     "c": _["b"]
96768                                     //  });
96769                                     var properties = [];
96770                                     for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) {
96771                                         var e = _d[_c];
96772                                         properties.push(factory.createPropertyAssignment(factory.createStringLiteral(ts.idText(e.name)), factory.createElementAccessExpression(parameterName, factory.createStringLiteral(ts.idText(e.propertyName || e.name)))));
96773                                     }
96774                                     statements.push(factory.createExpressionStatement(factory.createCallExpression(exportFunction, 
96775                                     /*typeArguments*/ undefined, [factory.createObjectLiteralExpression(properties, /*multiline*/ true)])));
96776                                 }
96777                                 else {
96778                                     statements.push(factory.createExpressionStatement(factory.createCallExpression(exportFunction, 
96779                                     /*typeArguments*/ undefined, [
96780                                         factory.createStringLiteral(ts.idText(entry.exportClause.name)),
96781                                         parameterName
96782                                     ])));
96783                                 }
96784                             }
96785                             else {
96786                                 //  export * from 'foo'
96787                                 //
96788                                 // emit as:
96789                                 //
96790                                 //  exportStar(foo_1_1);
96791                                 statements.push(factory.createExpressionStatement(factory.createCallExpression(exportStarFunction, 
96792                                 /*typeArguments*/ undefined, [parameterName])));
96793                             }
96794                             break;
96795                     }
96796                 }
96797                 setters.push(factory.createFunctionExpression(
96798                 /*modifiers*/ undefined, 
96799                 /*asteriskToken*/ undefined, 
96800                 /*name*/ undefined, 
96801                 /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
96802                 /*type*/ undefined, factory.createBlock(statements, /*multiLine*/ true)));
96803             }
96804             return factory.createArrayLiteralExpression(setters, /*multiLine*/ true);
96805         }
96806         //
96807         // Top-level Source Element Visitors
96808         //
96809         /**
96810          * Visit source elements at the top-level of a module.
96811          *
96812          * @param node The node to visit.
96813          */
96814         function sourceElementVisitor(node) {
96815             switch (node.kind) {
96816                 case 261 /* ImportDeclaration */:
96817                     return visitImportDeclaration(node);
96818                 case 260 /* ImportEqualsDeclaration */:
96819                     return visitImportEqualsDeclaration(node);
96820                 case 267 /* ExportDeclaration */:
96821                     return visitExportDeclaration(node);
96822                 case 266 /* ExportAssignment */:
96823                     return visitExportAssignment(node);
96824                 default:
96825                     return nestedElementVisitor(node);
96826             }
96827         }
96828         /**
96829          * Visits an ImportDeclaration node.
96830          *
96831          * @param node The node to visit.
96832          */
96833         function visitImportDeclaration(node) {
96834             var statements;
96835             if (node.importClause) {
96836                 hoistVariableDeclaration(ts.getLocalNameForExternalImport(factory, node, currentSourceFile)); // TODO: GH#18217
96837             }
96838             if (hasAssociatedEndOfDeclarationMarker(node)) {
96839                 // Defer exports until we encounter an EndOfDeclarationMarker node
96840                 var id = ts.getOriginalNodeId(node);
96841                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
96842             }
96843             else {
96844                 statements = appendExportsOfImportDeclaration(statements, node);
96845             }
96846             return ts.singleOrMany(statements);
96847         }
96848         function visitExportDeclaration(node) {
96849             ts.Debug.assertIsDefined(node);
96850             return undefined;
96851         }
96852         /**
96853          * Visits an ImportEqualsDeclaration node.
96854          *
96855          * @param node The node to visit.
96856          */
96857         function visitImportEqualsDeclaration(node) {
96858             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
96859             var statements;
96860             hoistVariableDeclaration(ts.getLocalNameForExternalImport(factory, node, currentSourceFile)); // TODO: GH#18217
96861             if (hasAssociatedEndOfDeclarationMarker(node)) {
96862                 // Defer exports until we encounter an EndOfDeclarationMarker node
96863                 var id = ts.getOriginalNodeId(node);
96864                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
96865             }
96866             else {
96867                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
96868             }
96869             return ts.singleOrMany(statements);
96870         }
96871         /**
96872          * Visits an ExportAssignment node.
96873          *
96874          * @param node The node to visit.
96875          */
96876         function visitExportAssignment(node) {
96877             if (node.isExportEquals) {
96878                 // Elide `export=` as it is illegal in a SystemJS module.
96879                 return undefined;
96880             }
96881             var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression);
96882             var original = node.original;
96883             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
96884                 // Defer exports until we encounter an EndOfDeclarationMarker node
96885                 var id = ts.getOriginalNodeId(node);
96886                 deferredExports[id] = appendExportStatement(deferredExports[id], factory.createIdentifier("default"), expression, /*allowComments*/ true);
96887             }
96888             else {
96889                 return createExportStatement(factory.createIdentifier("default"), expression, /*allowComments*/ true);
96890             }
96891         }
96892         /**
96893          * Visits a FunctionDeclaration, hoisting it to the outer module body function.
96894          *
96895          * @param node The node to visit.
96896          */
96897         function visitFunctionDeclaration(node) {
96898             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
96899                 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), 
96900                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), 
96901                 /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock)));
96902             }
96903             else {
96904                 hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context));
96905             }
96906             if (hasAssociatedEndOfDeclarationMarker(node)) {
96907                 // Defer exports until we encounter an EndOfDeclarationMarker node
96908                 var id = ts.getOriginalNodeId(node);
96909                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
96910             }
96911             else {
96912                 hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
96913             }
96914             return undefined;
96915         }
96916         /**
96917          * Visits a ClassDeclaration, hoisting its name to the outer module body function.
96918          *
96919          * @param node The node to visit.
96920          */
96921         function visitClassDeclaration(node) {
96922             var statements;
96923             // Hoist the name of the class declaration to the outer module body function.
96924             var name = factory.getLocalName(node);
96925             hoistVariableDeclaration(name);
96926             // Rewrite the class declaration into an assignment of a class expression.
96927             statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.decorators, destructuringAndImportCallVisitor, ts.isDecorator), 
96928             /*modifiers*/ undefined, node.name, 
96929             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node));
96930             if (hasAssociatedEndOfDeclarationMarker(node)) {
96931                 // Defer exports until we encounter an EndOfDeclarationMarker node
96932                 var id = ts.getOriginalNodeId(node);
96933                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
96934             }
96935             else {
96936                 statements = appendExportsOfHoistedDeclaration(statements, node);
96937             }
96938             return ts.singleOrMany(statements);
96939         }
96940         /**
96941          * Visits a variable statement, hoisting declared names to the top-level module body.
96942          * Each declaration is rewritten into an assignment expression.
96943          *
96944          * @param node The node to visit.
96945          */
96946         function visitVariableStatement(node) {
96947             if (!shouldHoistVariableDeclarationList(node.declarationList)) {
96948                 return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement);
96949             }
96950             var expressions;
96951             var isExportedDeclaration = ts.hasSyntacticModifier(node, 1 /* Export */);
96952             var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
96953             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
96954                 var variable = _a[_i];
96955                 if (variable.initializer) {
96956                     expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
96957                 }
96958                 else {
96959                     hoistBindingElement(variable);
96960                 }
96961             }
96962             var statements;
96963             if (expressions) {
96964                 statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node));
96965             }
96966             if (isMarkedDeclaration) {
96967                 // Defer exports until we encounter an EndOfDeclarationMarker node
96968                 var id = ts.getOriginalNodeId(node);
96969                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
96970             }
96971             else {
96972                 statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
96973             }
96974             return ts.singleOrMany(statements);
96975         }
96976         /**
96977          * Hoists the declared names of a VariableDeclaration or BindingElement.
96978          *
96979          * @param node The declaration to hoist.
96980          */
96981         function hoistBindingElement(node) {
96982             if (ts.isBindingPattern(node.name)) {
96983                 for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {
96984                     var element = _a[_i];
96985                     if (!ts.isOmittedExpression(element)) {
96986                         hoistBindingElement(element);
96987                     }
96988                 }
96989             }
96990             else {
96991                 hoistVariableDeclaration(factory.cloneNode(node.name));
96992             }
96993         }
96994         /**
96995          * Determines whether a VariableDeclarationList should be hoisted.
96996          *
96997          * @param node The node to test.
96998          */
96999         function shouldHoistVariableDeclarationList(node) {
97000             // hoist only non-block scoped declarations or block scoped declarations parented by source file
97001             return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
97002                 && (enclosingBlockScopedContainer.kind === 297 /* SourceFile */
97003                     || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
97004         }
97005         /**
97006          * Transform an initialized variable declaration into an expression.
97007          *
97008          * @param node The node to transform.
97009          * @param isExportedDeclaration A value indicating whether the variable is exported.
97010          */
97011         function transformInitializedVariable(node, isExportedDeclaration) {
97012             var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
97013             return ts.isBindingPattern(node.name)
97014                 ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
97015                 /*needsValue*/ false, createAssignment)
97016                 : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name;
97017         }
97018         /**
97019          * Creates an assignment expression for an exported variable declaration.
97020          *
97021          * @param name The name of the variable.
97022          * @param value The value of the variable's initializer.
97023          * @param location The source map location for the assignment.
97024          */
97025         function createExportedVariableAssignment(name, value, location) {
97026             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
97027         }
97028         /**
97029          * Creates an assignment expression for a non-exported variable declaration.
97030          *
97031          * @param name The name of the variable.
97032          * @param value The value of the variable's initializer.
97033          * @param location The source map location for the assignment.
97034          */
97035         function createNonExportedVariableAssignment(name, value, location) {
97036             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
97037         }
97038         /**
97039          * Creates an assignment expression for a variable declaration.
97040          *
97041          * @param name The name of the variable.
97042          * @param value The value of the variable's initializer.
97043          * @param location The source map location for the assignment.
97044          * @param isExportedDeclaration A value indicating whether the variable is exported.
97045          */
97046         function createVariableAssignment(name, value, location, isExportedDeclaration) {
97047             hoistVariableDeclaration(factory.cloneNode(name));
97048             return isExportedDeclaration
97049                 ? createExportExpression(name, preventSubstitution(ts.setTextRange(factory.createAssignment(name, value), location)))
97050                 : preventSubstitution(ts.setTextRange(factory.createAssignment(name, value), location));
97051         }
97052         /**
97053          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
97054          * and transformed declaration.
97055          *
97056          * @param node The node to visit.
97057          */
97058         function visitMergeDeclarationMarker(node) {
97059             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
97060             // declaration we do not emit a leading variable declaration. To preserve the
97061             // begin/end semantics of the declararation and to properly handle exports
97062             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
97063             //
97064             // To balance the declaration, we defer the exports of the elided variable
97065             // statement until we visit this declaration's `EndOfDeclarationMarker`.
97066             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) {
97067                 var id = ts.getOriginalNodeId(node);
97068                 var isExportedDeclaration = ts.hasSyntacticModifier(node.original, 1 /* Export */);
97069                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration);
97070             }
97071             return node;
97072         }
97073         /**
97074          * Determines whether a node has an associated EndOfDeclarationMarker.
97075          *
97076          * @param node The node to test.
97077          */
97078         function hasAssociatedEndOfDeclarationMarker(node) {
97079             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
97080         }
97081         /**
97082          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
97083          * declaration.
97084          *
97085          * @param node The node to visit.
97086          */
97087         function visitEndOfDeclarationMarker(node) {
97088             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
97089             // end of the transformed declaration. We use this marker to emit any deferred exports
97090             // of the declaration.
97091             var id = ts.getOriginalNodeId(node);
97092             var statements = deferredExports[id];
97093             if (statements) {
97094                 delete deferredExports[id];
97095                 return ts.append(statements, node);
97096             }
97097             else {
97098                 var original = ts.getOriginalNode(node);
97099                 if (ts.isModuleOrEnumDeclaration(original)) {
97100                     return ts.append(appendExportsOfDeclaration(statements, original), node);
97101                 }
97102             }
97103             return node;
97104         }
97105         /**
97106          * Appends the exports of an ImportDeclaration to a statement list, returning the
97107          * statement list.
97108          *
97109          * @param statements A statement list to which the down-level export statements are to be
97110          * appended. If `statements` is `undefined`, a new array is allocated if statements are
97111          * appended.
97112          * @param decl The declaration whose exports are to be recorded.
97113          */
97114         function appendExportsOfImportDeclaration(statements, decl) {
97115             if (moduleInfo.exportEquals) {
97116                 return statements;
97117             }
97118             var importClause = decl.importClause;
97119             if (!importClause) {
97120                 return statements;
97121             }
97122             if (importClause.name) {
97123                 statements = appendExportsOfDeclaration(statements, importClause);
97124             }
97125             var namedBindings = importClause.namedBindings;
97126             if (namedBindings) {
97127                 switch (namedBindings.kind) {
97128                     case 263 /* NamespaceImport */:
97129                         statements = appendExportsOfDeclaration(statements, namedBindings);
97130                         break;
97131                     case 264 /* NamedImports */:
97132                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
97133                             var importBinding = _a[_i];
97134                             statements = appendExportsOfDeclaration(statements, importBinding);
97135                         }
97136                         break;
97137                 }
97138             }
97139             return statements;
97140         }
97141         /**
97142          * Appends the export of an ImportEqualsDeclaration to a statement list, returning the
97143          * statement list.
97144          *
97145          * @param statements A statement list to which the down-level export statements are to be
97146          * appended. If `statements` is `undefined`, a new array is allocated if statements are
97147          * appended.
97148          * @param decl The declaration whose exports are to be recorded.
97149          */
97150         function appendExportsOfImportEqualsDeclaration(statements, decl) {
97151             if (moduleInfo.exportEquals) {
97152                 return statements;
97153             }
97154             return appendExportsOfDeclaration(statements, decl);
97155         }
97156         /**
97157          * Appends the exports of a VariableStatement to a statement list, returning the statement
97158          * list.
97159          *
97160          * @param statements A statement list to which the down-level export statements are to be
97161          * appended. If `statements` is `undefined`, a new array is allocated if statements are
97162          * appended.
97163          * @param node The VariableStatement whose exports are to be recorded.
97164          * @param exportSelf A value indicating whether to also export each VariableDeclaration of
97165          * `nodes` declaration list.
97166          */
97167         function appendExportsOfVariableStatement(statements, node, exportSelf) {
97168             if (moduleInfo.exportEquals) {
97169                 return statements;
97170             }
97171             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
97172                 var decl = _a[_i];
97173                 if (decl.initializer || exportSelf) {
97174                     statements = appendExportsOfBindingElement(statements, decl, exportSelf);
97175                 }
97176             }
97177             return statements;
97178         }
97179         /**
97180          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
97181          * returning the statement list.
97182          *
97183          * @param statements A statement list to which the down-level export statements are to be
97184          * appended. If `statements` is `undefined`, a new array is allocated if statements are
97185          * appended.
97186          * @param decl The declaration whose exports are to be recorded.
97187          * @param exportSelf A value indicating whether to also export the declaration itself.
97188          */
97189         function appendExportsOfBindingElement(statements, decl, exportSelf) {
97190             if (moduleInfo.exportEquals) {
97191                 return statements;
97192             }
97193             if (ts.isBindingPattern(decl.name)) {
97194                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
97195                     var element = _a[_i];
97196                     if (!ts.isOmittedExpression(element)) {
97197                         statements = appendExportsOfBindingElement(statements, element, exportSelf);
97198                     }
97199                 }
97200             }
97201             else if (!ts.isGeneratedIdentifier(decl.name)) {
97202                 var excludeName = void 0;
97203                 if (exportSelf) {
97204                     statements = appendExportStatement(statements, decl.name, factory.getLocalName(decl));
97205                     excludeName = ts.idText(decl.name);
97206                 }
97207                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
97208             }
97209             return statements;
97210         }
97211         /**
97212          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
97213          * returning the statement list.
97214          *
97215          * @param statements A statement list to which the down-level export statements are to be
97216          * appended. If `statements` is `undefined`, a new array is allocated if statements are
97217          * appended.
97218          * @param decl The declaration whose exports are to be recorded.
97219          */
97220         function appendExportsOfHoistedDeclaration(statements, decl) {
97221             if (moduleInfo.exportEquals) {
97222                 return statements;
97223             }
97224             var excludeName;
97225             if (ts.hasSyntacticModifier(decl, 1 /* Export */)) {
97226                 var exportName = ts.hasSyntacticModifier(decl, 512 /* Default */) ? factory.createStringLiteral("default") : decl.name;
97227                 statements = appendExportStatement(statements, exportName, factory.getLocalName(decl));
97228                 excludeName = ts.getTextOfIdentifierOrLiteral(exportName);
97229             }
97230             if (decl.name) {
97231                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
97232             }
97233             return statements;
97234         }
97235         /**
97236          * Appends the exports of a declaration to a statement list, returning the statement list.
97237          *
97238          * @param statements A statement list to which the down-level export statements are to be
97239          * appended. If `statements` is `undefined`, a new array is allocated if statements are
97240          * appended.
97241          * @param decl The declaration to export.
97242          * @param excludeName An optional name to exclude from exports.
97243          */
97244         function appendExportsOfDeclaration(statements, decl, excludeName) {
97245             if (moduleInfo.exportEquals) {
97246                 return statements;
97247             }
97248             var name = factory.getDeclarationName(decl);
97249             var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name));
97250             if (exportSpecifiers) {
97251                 for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
97252                     var exportSpecifier = exportSpecifiers_2[_i];
97253                     if (exportSpecifier.name.escapedText !== excludeName) {
97254                         statements = appendExportStatement(statements, exportSpecifier.name, name);
97255                     }
97256                 }
97257             }
97258             return statements;
97259         }
97260         /**
97261          * Appends the down-level representation of an export to a statement list, returning the
97262          * statement list.
97263          *
97264          * @param statements A statement list to which the down-level export statements are to be
97265          * appended. If `statements` is `undefined`, a new array is allocated if statements are
97266          * appended.
97267          * @param exportName The name of the export.
97268          * @param expression The expression to export.
97269          * @param allowComments Whether to allow comments on the export.
97270          */
97271         function appendExportStatement(statements, exportName, expression, allowComments) {
97272             statements = ts.append(statements, createExportStatement(exportName, expression, allowComments));
97273             return statements;
97274         }
97275         /**
97276          * Creates a call to the current file's export function to export a value.
97277          *
97278          * @param name The bound name of the export.
97279          * @param value The exported value.
97280          * @param allowComments An optional value indicating whether to emit comments for the statement.
97281          */
97282         function createExportStatement(name, value, allowComments) {
97283             var statement = factory.createExpressionStatement(createExportExpression(name, value));
97284             ts.startOnNewLine(statement);
97285             if (!allowComments) {
97286                 ts.setEmitFlags(statement, 1536 /* NoComments */);
97287             }
97288             return statement;
97289         }
97290         /**
97291          * Creates a call to the current file's export function to export a value.
97292          *
97293          * @param name The bound name of the export.
97294          * @param value The exported value.
97295          */
97296         function createExportExpression(name, value) {
97297             var exportName = ts.isIdentifier(name) ? factory.createStringLiteralFromNode(name) : name;
97298             ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */);
97299             return ts.setCommentRange(factory.createCallExpression(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value);
97300         }
97301         //
97302         // Top-Level or Nested Source Element Visitors
97303         //
97304         /**
97305          * Visit nested elements at the top-level of a module.
97306          *
97307          * @param node The node to visit.
97308          */
97309         function nestedElementVisitor(node) {
97310             switch (node.kind) {
97311                 case 232 /* VariableStatement */:
97312                     return visitVariableStatement(node);
97313                 case 251 /* FunctionDeclaration */:
97314                     return visitFunctionDeclaration(node);
97315                 case 252 /* ClassDeclaration */:
97316                     return visitClassDeclaration(node);
97317                 case 237 /* ForStatement */:
97318                     return visitForStatement(node);
97319                 case 238 /* ForInStatement */:
97320                     return visitForInStatement(node);
97321                 case 239 /* ForOfStatement */:
97322                     return visitForOfStatement(node);
97323                 case 235 /* DoStatement */:
97324                     return visitDoStatement(node);
97325                 case 236 /* WhileStatement */:
97326                     return visitWhileStatement(node);
97327                 case 245 /* LabeledStatement */:
97328                     return visitLabeledStatement(node);
97329                 case 243 /* WithStatement */:
97330                     return visitWithStatement(node);
97331                 case 244 /* SwitchStatement */:
97332                     return visitSwitchStatement(node);
97333                 case 258 /* CaseBlock */:
97334                     return visitCaseBlock(node);
97335                 case 284 /* CaseClause */:
97336                     return visitCaseClause(node);
97337                 case 285 /* DefaultClause */:
97338                     return visitDefaultClause(node);
97339                 case 247 /* TryStatement */:
97340                     return visitTryStatement(node);
97341                 case 287 /* CatchClause */:
97342                     return visitCatchClause(node);
97343                 case 230 /* Block */:
97344                     return visitBlock(node);
97345                 case 338 /* MergeDeclarationMarker */:
97346                     return visitMergeDeclarationMarker(node);
97347                 case 339 /* EndOfDeclarationMarker */:
97348                     return visitEndOfDeclarationMarker(node);
97349                 default:
97350                     return destructuringAndImportCallVisitor(node);
97351             }
97352         }
97353         /**
97354          * Visits the body of a ForStatement to hoist declarations.
97355          *
97356          * @param node The node to visit.
97357          */
97358         function visitForStatement(node) {
97359             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
97360             enclosingBlockScopedContainer = node;
97361             node = factory.updateForStatement(node, node.initializer && visitForInitializer(node.initializer), ts.visitNode(node.condition, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.incrementor, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement));
97362             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
97363             return node;
97364         }
97365         /**
97366          * Visits the body of a ForInStatement to hoist declarations.
97367          *
97368          * @param node The node to visit.
97369          */
97370         function visitForInStatement(node) {
97371             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
97372             enclosingBlockScopedContainer = node;
97373             node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
97374             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
97375             return node;
97376         }
97377         /**
97378          * Visits the body of a ForOfStatement to hoist declarations.
97379          *
97380          * @param node The node to visit.
97381          */
97382         function visitForOfStatement(node) {
97383             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
97384             enclosingBlockScopedContainer = node;
97385             node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
97386             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
97387             return node;
97388         }
97389         /**
97390          * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
97391          * ForOfStatement.
97392          *
97393          * @param node The node to test.
97394          */
97395         function shouldHoistForInitializer(node) {
97396             return ts.isVariableDeclarationList(node)
97397                 && shouldHoistVariableDeclarationList(node);
97398         }
97399         /**
97400          * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
97401          *
97402          * @param node The node to visit.
97403          */
97404         function visitForInitializer(node) {
97405             if (shouldHoistForInitializer(node)) {
97406                 var expressions = void 0;
97407                 for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
97408                     var variable = _a[_i];
97409                     expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
97410                     if (!variable.initializer) {
97411                         hoistBindingElement(variable);
97412                     }
97413                 }
97414                 return expressions ? factory.inlineExpressions(expressions) : factory.createOmittedExpression();
97415             }
97416             else {
97417                 return ts.visitEachChild(node, nestedElementVisitor, context);
97418             }
97419         }
97420         /**
97421          * Visits the body of a DoStatement to hoist declarations.
97422          *
97423          * @param node The node to visit.
97424          */
97425         function visitDoStatement(node) {
97426             return factory.updateDoStatement(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression));
97427         }
97428         /**
97429          * Visits the body of a WhileStatement to hoist declarations.
97430          *
97431          * @param node The node to visit.
97432          */
97433         function visitWhileStatement(node) {
97434             return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
97435         }
97436         /**
97437          * Visits the body of a LabeledStatement to hoist declarations.
97438          *
97439          * @param node The node to visit.
97440          */
97441         function visitLabeledStatement(node) {
97442             return factory.updateLabeledStatement(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
97443         }
97444         /**
97445          * Visits the body of a WithStatement to hoist declarations.
97446          *
97447          * @param node The node to visit.
97448          */
97449         function visitWithStatement(node) {
97450             return factory.updateWithStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
97451         }
97452         /**
97453          * Visits the body of a SwitchStatement to hoist declarations.
97454          *
97455          * @param node The node to visit.
97456          */
97457         function visitSwitchStatement(node) {
97458             return factory.updateSwitchStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock));
97459         }
97460         /**
97461          * Visits the body of a CaseBlock to hoist declarations.
97462          *
97463          * @param node The node to visit.
97464          */
97465         function visitCaseBlock(node) {
97466             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
97467             enclosingBlockScopedContainer = node;
97468             node = factory.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause));
97469             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
97470             return node;
97471         }
97472         /**
97473          * Visits the body of a CaseClause to hoist declarations.
97474          *
97475          * @param node The node to visit.
97476          */
97477         function visitCaseClause(node) {
97478             return factory.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement));
97479         }
97480         /**
97481          * Visits the body of a DefaultClause to hoist declarations.
97482          *
97483          * @param node The node to visit.
97484          */
97485         function visitDefaultClause(node) {
97486             return ts.visitEachChild(node, nestedElementVisitor, context);
97487         }
97488         /**
97489          * Visits the body of a TryStatement to hoist declarations.
97490          *
97491          * @param node The node to visit.
97492          */
97493         function visitTryStatement(node) {
97494             return ts.visitEachChild(node, nestedElementVisitor, context);
97495         }
97496         /**
97497          * Visits the body of a CatchClause to hoist declarations.
97498          *
97499          * @param node The node to visit.
97500          */
97501         function visitCatchClause(node) {
97502             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
97503             enclosingBlockScopedContainer = node;
97504             node = factory.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock));
97505             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
97506             return node;
97507         }
97508         /**
97509          * Visits the body of a Block to hoist declarations.
97510          *
97511          * @param node The node to visit.
97512          */
97513         function visitBlock(node) {
97514             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
97515             enclosingBlockScopedContainer = node;
97516             node = ts.visitEachChild(node, nestedElementVisitor, context);
97517             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
97518             return node;
97519         }
97520         //
97521         // Destructuring Assignment Visitors
97522         //
97523         /**
97524          * Visit nodes to flatten destructuring assignments to exported symbols.
97525          *
97526          * @param node The node to visit.
97527          */
97528         function destructuringAndImportCallVisitor(node) {
97529             if (ts.isDestructuringAssignment(node)) {
97530                 return visitDestructuringAssignment(node);
97531             }
97532             else if (ts.isImportCall(node)) {
97533                 return visitImportCallExpression(node);
97534             }
97535             else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
97536                 return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
97537             }
97538             else {
97539                 return node;
97540             }
97541         }
97542         function visitImportCallExpression(node) {
97543             // import("./blah")
97544             // emit as
97545             // System.register([], function (_export, _context) {
97546             //     return {
97547             //         setters: [],
97548             //         execute: () => {
97549             //             _context.import('./blah');
97550             //         }
97551             //     };
97552             // });
97553             var externalModuleName = ts.getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions);
97554             var firstArgument = ts.visitNode(ts.firstOrUndefined(node.arguments), destructuringAndImportCallVisitor);
97555             // 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.
97556             var argument = externalModuleName && (!firstArgument || !ts.isStringLiteral(firstArgument) || firstArgument.text !== externalModuleName.text) ? externalModuleName : firstArgument;
97557             return factory.createCallExpression(factory.createPropertyAccessExpression(contextObject, factory.createIdentifier("import")), 
97558             /*typeArguments*/ undefined, argument ? [argument] : []);
97559         }
97560         /**
97561          * Visits a DestructuringAssignment to flatten destructuring to exported symbols.
97562          *
97563          * @param node The node to visit.
97564          */
97565         function visitDestructuringAssignment(node) {
97566             if (hasExportedReferenceInDestructuringTarget(node.left)) {
97567                 return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
97568                 /*needsValue*/ true);
97569             }
97570             return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
97571         }
97572         /**
97573          * Determines whether the target of a destructuring assigment refers to an exported symbol.
97574          *
97575          * @param node The destructuring target.
97576          */
97577         function hasExportedReferenceInDestructuringTarget(node) {
97578             if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
97579                 return hasExportedReferenceInDestructuringTarget(node.left);
97580             }
97581             else if (ts.isSpreadElement(node)) {
97582                 return hasExportedReferenceInDestructuringTarget(node.expression);
97583             }
97584             else if (ts.isObjectLiteralExpression(node)) {
97585                 return ts.some(node.properties, hasExportedReferenceInDestructuringTarget);
97586             }
97587             else if (ts.isArrayLiteralExpression(node)) {
97588                 return ts.some(node.elements, hasExportedReferenceInDestructuringTarget);
97589             }
97590             else if (ts.isShorthandPropertyAssignment(node)) {
97591                 return hasExportedReferenceInDestructuringTarget(node.name);
97592             }
97593             else if (ts.isPropertyAssignment(node)) {
97594                 return hasExportedReferenceInDestructuringTarget(node.initializer);
97595             }
97596             else if (ts.isIdentifier(node)) {
97597                 var container = resolver.getReferencedExportContainer(node);
97598                 return container !== undefined && container.kind === 297 /* SourceFile */;
97599             }
97600             else {
97601                 return false;
97602             }
97603         }
97604         //
97605         // Modifier Visitors
97606         //
97607         /**
97608          * Visit nodes to elide module-specific modifiers.
97609          *
97610          * @param node The node to visit.
97611          */
97612         function modifierVisitor(node) {
97613             switch (node.kind) {
97614                 case 92 /* ExportKeyword */:
97615                 case 87 /* DefaultKeyword */:
97616                     return undefined;
97617             }
97618             return node;
97619         }
97620         //
97621         // Emit Notification
97622         //
97623         /**
97624          * Hook for node emit notifications.
97625          *
97626          * @param hint A hint as to the intended usage of the node.
97627          * @param node The node to emit.
97628          * @param emitCallback A callback used to emit the node in the printer.
97629          */
97630         function onEmitNode(hint, node, emitCallback) {
97631             if (node.kind === 297 /* SourceFile */) {
97632                 var id = ts.getOriginalNodeId(node);
97633                 currentSourceFile = node;
97634                 moduleInfo = moduleInfoMap[id];
97635                 exportFunction = exportFunctionsMap[id];
97636                 noSubstitution = noSubstitutionMap[id];
97637                 contextObject = contextObjectMap[id];
97638                 if (noSubstitution) {
97639                     delete noSubstitutionMap[id];
97640                 }
97641                 previousOnEmitNode(hint, node, emitCallback);
97642                 currentSourceFile = undefined;
97643                 moduleInfo = undefined;
97644                 exportFunction = undefined;
97645                 contextObject = undefined;
97646                 noSubstitution = undefined;
97647             }
97648             else {
97649                 previousOnEmitNode(hint, node, emitCallback);
97650             }
97651         }
97652         //
97653         // Substitutions
97654         //
97655         /**
97656          * Hooks node substitutions.
97657          *
97658          * @param hint A hint as to the intended usage of the node.
97659          * @param node The node to substitute.
97660          */
97661         function onSubstituteNode(hint, node) {
97662             node = previousOnSubstituteNode(hint, node);
97663             if (isSubstitutionPrevented(node)) {
97664                 return node;
97665             }
97666             if (hint === 1 /* Expression */) {
97667                 return substituteExpression(node);
97668             }
97669             else if (hint === 4 /* Unspecified */) {
97670                 return substituteUnspecified(node);
97671             }
97672             return node;
97673         }
97674         /**
97675          * Substitute the node, if necessary.
97676          *
97677          * @param node The node to substitute.
97678          */
97679         function substituteUnspecified(node) {
97680             switch (node.kind) {
97681                 case 289 /* ShorthandPropertyAssignment */:
97682                     return substituteShorthandPropertyAssignment(node);
97683             }
97684             return node;
97685         }
97686         /**
97687          * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol.
97688          *
97689          * @param node The node to substitute.
97690          */
97691         function substituteShorthandPropertyAssignment(node) {
97692             var _a, _b;
97693             var name = node.name;
97694             if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) {
97695                 var importDeclaration = resolver.getReferencedImportDeclaration(name);
97696                 if (importDeclaration) {
97697                     if (ts.isImportClause(importDeclaration)) {
97698                         return ts.setTextRange(factory.createPropertyAssignment(factory.cloneNode(name), factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default"))), 
97699                         /*location*/ node);
97700                     }
97701                     else if (ts.isImportSpecifier(importDeclaration)) {
97702                         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))), 
97703                         /*location*/ node);
97704                     }
97705                 }
97706             }
97707             return node;
97708         }
97709         /**
97710          * Substitute the expression, if necessary.
97711          *
97712          * @param node The node to substitute.
97713          */
97714         function substituteExpression(node) {
97715             switch (node.kind) {
97716                 case 78 /* Identifier */:
97717                     return substituteExpressionIdentifier(node);
97718                 case 216 /* BinaryExpression */:
97719                     return substituteBinaryExpression(node);
97720                 case 214 /* PrefixUnaryExpression */:
97721                 case 215 /* PostfixUnaryExpression */:
97722                     return substituteUnaryExpression(node);
97723                 case 226 /* MetaProperty */:
97724                     return substituteMetaProperty(node);
97725             }
97726             return node;
97727         }
97728         /**
97729          * Substitution for an Identifier expression that may contain an imported or exported symbol.
97730          *
97731          * @param node The node to substitute.
97732          */
97733         function substituteExpressionIdentifier(node) {
97734             var _a, _b;
97735             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
97736                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
97737                 if (externalHelpersModuleName) {
97738                     return factory.createPropertyAccessExpression(externalHelpersModuleName, node);
97739                 }
97740                 return node;
97741             }
97742             // When we see an identifier in an expression position that
97743             // points to an imported symbol, we should substitute a qualified
97744             // reference to the imported symbol if one is needed.
97745             //
97746             // - We do not substitute generated identifiers for any reason.
97747             // - We do not substitute identifiers tagged with the LocalName flag.
97748             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
97749                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
97750                 if (importDeclaration) {
97751                     if (ts.isImportClause(importDeclaration)) {
97752                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")), 
97753                         /*location*/ node);
97754                     }
97755                     else if (ts.isImportSpecifier(importDeclaration)) {
97756                         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)), 
97757                         /*location*/ node);
97758                     }
97759                 }
97760             }
97761             return node;
97762         }
97763         /**
97764          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
97765          *
97766          * @param node The node to substitute.
97767          */
97768         function substituteBinaryExpression(node) {
97769             // When we see an assignment expression whose left-hand side is an exported symbol,
97770             // we should ensure all exports of that symbol are updated with the correct value.
97771             //
97772             // - We do not substitute generated identifiers for any reason.
97773             // - We do not substitute identifiers tagged with the LocalName flag.
97774             // - We do not substitute identifiers that were originally the name of an enum or
97775             //   namespace due to how they are transformed in TypeScript.
97776             // - We only substitute identifiers that are exported at the top level.
97777             if (ts.isAssignmentOperator(node.operatorToken.kind)
97778                 && ts.isIdentifier(node.left)
97779                 && !ts.isGeneratedIdentifier(node.left)
97780                 && !ts.isLocalName(node.left)
97781                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
97782                 var exportedNames = getExports(node.left);
97783                 if (exportedNames) {
97784                     // For each additional export of the declaration, apply an export assignment.
97785                     var expression = node;
97786                     for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
97787                         var exportName = exportedNames_4[_i];
97788                         expression = createExportExpression(exportName, preventSubstitution(expression));
97789                     }
97790                     return expression;
97791                 }
97792             }
97793             return node;
97794         }
97795         /**
97796          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
97797          *
97798          * @param node The node to substitute.
97799          */
97800         function substituteUnaryExpression(node) {
97801             // When we see a prefix or postfix increment expression whose operand is an exported
97802             // symbol, we should ensure all exports of that symbol are updated with the correct
97803             // value.
97804             //
97805             // - We do not substitute generated identifiers for any reason.
97806             // - We do not substitute identifiers tagged with the LocalName flag.
97807             // - We do not substitute identifiers that were originally the name of an enum or
97808             //   namespace due to how they are transformed in TypeScript.
97809             // - We only substitute identifiers that are exported at the top level.
97810             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
97811                 && ts.isIdentifier(node.operand)
97812                 && !ts.isGeneratedIdentifier(node.operand)
97813                 && !ts.isLocalName(node.operand)
97814                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
97815                 var exportedNames = getExports(node.operand);
97816                 if (exportedNames) {
97817                     var expression = node.kind === 215 /* PostfixUnaryExpression */
97818                         ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), node)
97819                         : node;
97820                     for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
97821                         var exportName = exportedNames_5[_i];
97822                         expression = createExportExpression(exportName, preventSubstitution(expression));
97823                     }
97824                     if (node.kind === 215 /* PostfixUnaryExpression */) {
97825                         expression = node.operator === 45 /* PlusPlusToken */
97826                             ? factory.createSubtract(preventSubstitution(expression), factory.createNumericLiteral(1))
97827                             : factory.createAdd(preventSubstitution(expression), factory.createNumericLiteral(1));
97828                     }
97829                     return expression;
97830                 }
97831             }
97832             return node;
97833         }
97834         function substituteMetaProperty(node) {
97835             if (ts.isImportMeta(node)) {
97836                 return factory.createPropertyAccessExpression(contextObject, factory.createIdentifier("meta"));
97837             }
97838             return node;
97839         }
97840         /**
97841          * Gets the exports of a name.
97842          *
97843          * @param name The name.
97844          */
97845         function getExports(name) {
97846             var exportedNames;
97847             if (!ts.isGeneratedIdentifier(name)) {
97848                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
97849                     || resolver.getReferencedValueDeclaration(name);
97850                 if (valueDeclaration) {
97851                     var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
97852                     if (exportContainer && exportContainer.kind === 297 /* SourceFile */) {
97853                         exportedNames = ts.append(exportedNames, factory.getDeclarationName(valueDeclaration));
97854                     }
97855                     exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
97856                 }
97857             }
97858             return exportedNames;
97859         }
97860         /**
97861          * Prevent substitution of a node for this transformer.
97862          *
97863          * @param node The node which should not be substituted.
97864          */
97865         function preventSubstitution(node) {
97866             if (noSubstitution === undefined)
97867                 noSubstitution = [];
97868             noSubstitution[ts.getNodeId(node)] = true;
97869             return node;
97870         }
97871         /**
97872          * Determines whether a node should not be substituted.
97873          *
97874          * @param node The node to test.
97875          */
97876         function isSubstitutionPrevented(node) {
97877             return noSubstitution && node.id && noSubstitution[node.id];
97878         }
97879     }
97880     ts.transformSystemModule = transformSystemModule;
97881 })(ts || (ts = {}));
97882 /*@internal*/
97883 var ts;
97884 (function (ts) {
97885     function transformECMAScriptModule(context) {
97886         var factory = context.factory, emitHelpers = context.getEmitHelperFactory;
97887         var compilerOptions = context.getCompilerOptions();
97888         var previousOnEmitNode = context.onEmitNode;
97889         var previousOnSubstituteNode = context.onSubstituteNode;
97890         context.onEmitNode = onEmitNode;
97891         context.onSubstituteNode = onSubstituteNode;
97892         context.enableEmitNotification(297 /* SourceFile */);
97893         context.enableSubstitution(78 /* Identifier */);
97894         var helperNameSubstitutions;
97895         return ts.chainBundle(context, transformSourceFile);
97896         function transformSourceFile(node) {
97897             if (node.isDeclarationFile) {
97898                 return node;
97899             }
97900             if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
97901                 var result = updateExternalModule(node);
97902                 if (!ts.isExternalModule(node) || ts.some(result.statements, ts.isExternalModuleIndicator)) {
97903                     return result;
97904                 }
97905                 return factory.updateSourceFile(result, ts.setTextRange(factory.createNodeArray(__spreadArray(__spreadArray([], result.statements), [ts.createEmptyExports(factory)])), result.statements));
97906             }
97907             return node;
97908         }
97909         function updateExternalModule(node) {
97910             var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(factory, emitHelpers(), node, compilerOptions);
97911             if (externalHelpersImportDeclaration) {
97912                 var statements = [];
97913                 var statementOffset = factory.copyPrologue(node.statements, statements);
97914                 ts.append(statements, externalHelpersImportDeclaration);
97915                 ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
97916                 return factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray(statements), node.statements));
97917             }
97918             else {
97919                 return ts.visitEachChild(node, visitor, context);
97920             }
97921         }
97922         function visitor(node) {
97923             switch (node.kind) {
97924                 case 260 /* ImportEqualsDeclaration */:
97925                     // Elide `import=` as it is not legal with --module ES6
97926                     return undefined;
97927                 case 266 /* ExportAssignment */:
97928                     return visitExportAssignment(node);
97929                 case 267 /* ExportDeclaration */:
97930                     var exportDecl = node;
97931                     return visitExportDeclaration(exportDecl);
97932             }
97933             return node;
97934         }
97935         function visitExportAssignment(node) {
97936             // Elide `export=` as it is not legal with --module ES6
97937             return node.isExportEquals ? undefined : node;
97938         }
97939         function visitExportDeclaration(node) {
97940             // `export * as ns` only needs to be transformed in ES2015
97941             if (compilerOptions.module !== undefined && compilerOptions.module > ts.ModuleKind.ES2015) {
97942                 return node;
97943             }
97944             // Either ill-formed or don't need to be tranformed.
97945             if (!node.exportClause || !ts.isNamespaceExport(node.exportClause) || !node.moduleSpecifier) {
97946                 return node;
97947             }
97948             var oldIdentifier = node.exportClause.name;
97949             var synthName = factory.getGeneratedNameForNode(oldIdentifier);
97950             var importDecl = factory.createImportDeclaration(
97951             /*decorators*/ undefined, 
97952             /*modifiers*/ undefined, factory.createImportClause(
97953             /*isTypeOnly*/ false, 
97954             /*name*/ undefined, factory.createNamespaceImport(synthName)), node.moduleSpecifier);
97955             ts.setOriginalNode(importDecl, node.exportClause);
97956             var exportDecl = ts.isExportNamespaceAsDefaultDeclaration(node) ? factory.createExportDefault(synthName) : factory.createExportDeclaration(
97957             /*decorators*/ undefined, 
97958             /*modifiers*/ undefined, 
97959             /*isTypeOnly*/ false, factory.createNamedExports([factory.createExportSpecifier(synthName, oldIdentifier)]));
97960             ts.setOriginalNode(exportDecl, node);
97961             return [importDecl, exportDecl];
97962         }
97963         //
97964         // Emit Notification
97965         //
97966         /**
97967          * Hook for node emit.
97968          *
97969          * @param hint A hint as to the intended usage of the node.
97970          * @param node The node to emit.
97971          * @param emit A callback used to emit the node in the printer.
97972          */
97973         function onEmitNode(hint, node, emitCallback) {
97974             if (ts.isSourceFile(node)) {
97975                 if ((ts.isExternalModule(node) || compilerOptions.isolatedModules) && compilerOptions.importHelpers) {
97976                     helperNameSubstitutions = new ts.Map();
97977                 }
97978                 previousOnEmitNode(hint, node, emitCallback);
97979                 helperNameSubstitutions = undefined;
97980             }
97981             else {
97982                 previousOnEmitNode(hint, node, emitCallback);
97983             }
97984         }
97985         //
97986         // Substitutions
97987         //
97988         /**
97989          * Hooks node substitutions.
97990          *
97991          * @param hint A hint as to the intended usage of the node.
97992          * @param node The node to substitute.
97993          */
97994         function onSubstituteNode(hint, node) {
97995             node = previousOnSubstituteNode(hint, node);
97996             if (helperNameSubstitutions && ts.isIdentifier(node) && ts.getEmitFlags(node) & 4096 /* HelperName */) {
97997                 return substituteHelperName(node);
97998             }
97999             return node;
98000         }
98001         function substituteHelperName(node) {
98002             var name = ts.idText(node);
98003             var substitution = helperNameSubstitutions.get(name);
98004             if (!substitution) {
98005                 helperNameSubstitutions.set(name, substitution = factory.createUniqueName(name, 16 /* Optimistic */ | 32 /* FileLevel */));
98006             }
98007             return substitution;
98008         }
98009     }
98010     ts.transformECMAScriptModule = transformECMAScriptModule;
98011 })(ts || (ts = {}));
98012 /* @internal */
98013 var ts;
98014 (function (ts) {
98015     function canProduceDiagnostics(node) {
98016         return ts.isVariableDeclaration(node) ||
98017             ts.isPropertyDeclaration(node) ||
98018             ts.isPropertySignature(node) ||
98019             ts.isBindingElement(node) ||
98020             ts.isSetAccessor(node) ||
98021             ts.isGetAccessor(node) ||
98022             ts.isConstructSignatureDeclaration(node) ||
98023             ts.isCallSignatureDeclaration(node) ||
98024             ts.isMethodDeclaration(node) ||
98025             ts.isMethodSignature(node) ||
98026             ts.isFunctionDeclaration(node) ||
98027             ts.isParameter(node) ||
98028             ts.isTypeParameterDeclaration(node) ||
98029             ts.isExpressionWithTypeArguments(node) ||
98030             ts.isImportEqualsDeclaration(node) ||
98031             ts.isTypeAliasDeclaration(node) ||
98032             ts.isConstructorDeclaration(node) ||
98033             ts.isIndexSignatureDeclaration(node) ||
98034             ts.isPropertyAccessExpression(node) ||
98035             ts.isJSDocTypeAlias(node);
98036     }
98037     ts.canProduceDiagnostics = canProduceDiagnostics;
98038     function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
98039         if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
98040             return getAccessorNameVisibilityError;
98041         }
98042         else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) {
98043             return getMethodNameVisibilityError;
98044         }
98045         else {
98046             return createGetSymbolAccessibilityDiagnosticForNode(node);
98047         }
98048         function getAccessorNameVisibilityError(symbolAccessibilityResult) {
98049             var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
98050             return diagnosticMessage !== undefined ? {
98051                 diagnosticMessage: diagnosticMessage,
98052                 errorNode: node,
98053                 typeName: node.name
98054             } : undefined;
98055         }
98056         function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
98057             if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
98058                 return symbolAccessibilityResult.errorModuleName ?
98059                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98060                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
98061                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
98062                     ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
98063             }
98064             else if (node.parent.kind === 252 /* ClassDeclaration */) {
98065                 return symbolAccessibilityResult.errorModuleName ?
98066                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98067                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
98068                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
98069                     ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
98070             }
98071             else {
98072                 return symbolAccessibilityResult.errorModuleName ?
98073                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
98074                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
98075             }
98076         }
98077         function getMethodNameVisibilityError(symbolAccessibilityResult) {
98078             var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
98079             return diagnosticMessage !== undefined ? {
98080                 diagnosticMessage: diagnosticMessage,
98081                 errorNode: node,
98082                 typeName: node.name
98083             } : undefined;
98084         }
98085         function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
98086             if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
98087                 return symbolAccessibilityResult.errorModuleName ?
98088                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98089                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
98090                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
98091                     ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
98092             }
98093             else if (node.parent.kind === 252 /* ClassDeclaration */) {
98094                 return symbolAccessibilityResult.errorModuleName ?
98095                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98096                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
98097                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
98098                     ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
98099             }
98100             else {
98101                 return symbolAccessibilityResult.errorModuleName ?
98102                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
98103                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
98104             }
98105         }
98106     }
98107     ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
98108     function createGetSymbolAccessibilityDiagnosticForNode(node) {
98109         if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
98110             return getVariableDeclarationTypeVisibilityError;
98111         }
98112         else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
98113             return getAccessorDeclarationTypeVisibilityError;
98114         }
98115         else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) {
98116             return getReturnTypeVisibilityError;
98117         }
98118         else if (ts.isParameter(node)) {
98119             if (ts.isParameterPropertyDeclaration(node, node.parent) && ts.hasSyntacticModifier(node.parent, 8 /* Private */)) {
98120                 return getVariableDeclarationTypeVisibilityError;
98121             }
98122             return getParameterDeclarationTypeVisibilityError;
98123         }
98124         else if (ts.isTypeParameterDeclaration(node)) {
98125             return getTypeParameterConstraintVisibilityError;
98126         }
98127         else if (ts.isExpressionWithTypeArguments(node)) {
98128             return getHeritageClauseVisibilityError;
98129         }
98130         else if (ts.isImportEqualsDeclaration(node)) {
98131             return getImportEntityNameVisibilityError;
98132         }
98133         else if (ts.isTypeAliasDeclaration(node) || ts.isJSDocTypeAlias(node)) {
98134             return getTypeAliasDeclarationVisibilityError;
98135         }
98136         else {
98137             return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]);
98138         }
98139         function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
98140             if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) {
98141                 return symbolAccessibilityResult.errorModuleName ?
98142                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98143                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
98144                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
98145                     ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
98146             }
98147             // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
98148             // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
98149             else if (node.kind === 163 /* PropertyDeclaration */ || node.kind === 201 /* PropertyAccessExpression */ || node.kind === 162 /* PropertySignature */ ||
98150                 (node.kind === 160 /* Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* Private */))) {
98151                 // TODO(jfreeman): Deal with computed properties in error reporting.
98152                 if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
98153                     return symbolAccessibilityResult.errorModuleName ?
98154                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98155                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
98156                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
98157                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
98158                 }
98159                 else if (node.parent.kind === 252 /* ClassDeclaration */ || node.kind === 160 /* Parameter */) {
98160                     return symbolAccessibilityResult.errorModuleName ?
98161                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98162                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
98163                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
98164                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
98165                 }
98166                 else {
98167                     // Interfaces cannot have types that cannot be named
98168                     return symbolAccessibilityResult.errorModuleName ?
98169                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
98170                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
98171                 }
98172             }
98173         }
98174         function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
98175             var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
98176             return diagnosticMessage !== undefined ? {
98177                 diagnosticMessage: diagnosticMessage,
98178                 errorNode: node,
98179                 typeName: node.name
98180             } : undefined;
98181         }
98182         function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
98183             var diagnosticMessage;
98184             if (node.kind === 168 /* SetAccessor */) {
98185                 // Getters can infer the return type from the returned expression, but setters cannot, so the
98186                 // "_from_external_module_1_but_cannot_be_named" case cannot occur.
98187                 if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
98188                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
98189                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
98190                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
98191                 }
98192                 else {
98193                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
98194                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
98195                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
98196                 }
98197             }
98198             else {
98199                 if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
98200                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
98201                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98202                             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 :
98203                             ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
98204                         ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
98205                 }
98206                 else {
98207                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
98208                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98209                             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 :
98210                             ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
98211                         ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
98212                 }
98213             }
98214             return {
98215                 diagnosticMessage: diagnosticMessage,
98216                 errorNode: node.name,
98217                 typeName: node.name
98218             };
98219         }
98220         function getReturnTypeVisibilityError(symbolAccessibilityResult) {
98221             var diagnosticMessage;
98222             switch (node.kind) {
98223                 case 170 /* ConstructSignature */:
98224                     // Interfaces cannot have return types that cannot be named
98225                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
98226                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
98227                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
98228                     break;
98229                 case 169 /* CallSignature */:
98230                     // Interfaces cannot have return types that cannot be named
98231                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
98232                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
98233                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
98234                     break;
98235                 case 171 /* IndexSignature */:
98236                     // Interfaces cannot have return types that cannot be named
98237                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
98238                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
98239                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
98240                     break;
98241                 case 165 /* MethodDeclaration */:
98242                 case 164 /* MethodSignature */:
98243                     if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
98244                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
98245                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98246                                 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 :
98247                                 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
98248                             ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
98249                     }
98250                     else if (node.parent.kind === 252 /* ClassDeclaration */) {
98251                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
98252                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98253                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
98254                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
98255                             ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
98256                     }
98257                     else {
98258                         // Interfaces cannot have return types that cannot be named
98259                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
98260                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
98261                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
98262                     }
98263                     break;
98264                 case 251 /* FunctionDeclaration */:
98265                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
98266                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98267                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
98268                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
98269                         ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
98270                     break;
98271                 default:
98272                     return ts.Debug.fail("This is unknown kind for signature: " + node.kind);
98273             }
98274             return {
98275                 diagnosticMessage: diagnosticMessage,
98276                 errorNode: node.name || node
98277             };
98278         }
98279         function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
98280             var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
98281             return diagnosticMessage !== undefined ? {
98282                 diagnosticMessage: diagnosticMessage,
98283                 errorNode: node,
98284                 typeName: node.name
98285             } : undefined;
98286         }
98287         function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
98288             switch (node.parent.kind) {
98289                 case 166 /* Constructor */:
98290                     return symbolAccessibilityResult.errorModuleName ?
98291                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98292                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
98293                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
98294                         ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
98295                 case 170 /* ConstructSignature */:
98296                 case 175 /* ConstructorType */:
98297                     // Interfaces cannot have parameter types that cannot be named
98298                     return symbolAccessibilityResult.errorModuleName ?
98299                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
98300                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
98301                 case 169 /* CallSignature */:
98302                     // Interfaces cannot have parameter types that cannot be named
98303                     return symbolAccessibilityResult.errorModuleName ?
98304                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
98305                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
98306                 case 171 /* IndexSignature */:
98307                     // Interfaces cannot have parameter types that cannot be named
98308                     return symbolAccessibilityResult.errorModuleName ?
98309                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
98310                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
98311                 case 165 /* MethodDeclaration */:
98312                 case 164 /* MethodSignature */:
98313                     if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) {
98314                         return symbolAccessibilityResult.errorModuleName ?
98315                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98316                                 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 :
98317                                 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
98318                             ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
98319                     }
98320                     else if (node.parent.parent.kind === 252 /* ClassDeclaration */) {
98321                         return symbolAccessibilityResult.errorModuleName ?
98322                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98323                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
98324                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
98325                             ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
98326                     }
98327                     else {
98328                         // Interfaces cannot have parameter types that cannot be named
98329                         return symbolAccessibilityResult.errorModuleName ?
98330                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
98331                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
98332                     }
98333                 case 251 /* FunctionDeclaration */:
98334                 case 174 /* FunctionType */:
98335                     return symbolAccessibilityResult.errorModuleName ?
98336                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98337                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
98338                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
98339                         ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
98340                 case 168 /* SetAccessor */:
98341                 case 167 /* GetAccessor */:
98342                     return symbolAccessibilityResult.errorModuleName ?
98343                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
98344                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
98345                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 :
98346                         ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1;
98347                 default:
98348                     return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]);
98349             }
98350         }
98351         function getTypeParameterConstraintVisibilityError() {
98352             // Type parameter constraints are named by user so we should always be able to name it
98353             var diagnosticMessage;
98354             switch (node.parent.kind) {
98355                 case 252 /* ClassDeclaration */:
98356                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
98357                     break;
98358                 case 253 /* InterfaceDeclaration */:
98359                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
98360                     break;
98361                 case 190 /* MappedType */:
98362                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
98363                     break;
98364                 case 175 /* ConstructorType */:
98365                 case 170 /* ConstructSignature */:
98366                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
98367                     break;
98368                 case 169 /* CallSignature */:
98369                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
98370                     break;
98371                 case 165 /* MethodDeclaration */:
98372                 case 164 /* MethodSignature */:
98373                     if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) {
98374                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
98375                     }
98376                     else if (node.parent.parent.kind === 252 /* ClassDeclaration */) {
98377                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
98378                     }
98379                     else {
98380                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
98381                     }
98382                     break;
98383                 case 174 /* FunctionType */:
98384                 case 251 /* FunctionDeclaration */:
98385                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
98386                     break;
98387                 case 254 /* TypeAliasDeclaration */:
98388                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
98389                     break;
98390                 default:
98391                     return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
98392             }
98393             return {
98394                 diagnosticMessage: diagnosticMessage,
98395                 errorNode: node,
98396                 typeName: node.name
98397             };
98398         }
98399         function getHeritageClauseVisibilityError() {
98400             var diagnosticMessage;
98401             // Heritage clause is written by user so it can always be named
98402             if (ts.isClassDeclaration(node.parent.parent)) {
98403                 // Class or Interface implemented/extended is inaccessible
98404                 diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 116 /* ImplementsKeyword */ ?
98405                     ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 :
98406                     node.parent.parent.name ? ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1 :
98407                         ts.Diagnostics.extends_clause_of_exported_class_has_or_is_using_private_name_0;
98408             }
98409             else {
98410                 // interface is inaccessible
98411                 diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
98412             }
98413             return {
98414                 diagnosticMessage: diagnosticMessage,
98415                 errorNode: node,
98416                 typeName: ts.getNameOfDeclaration(node.parent.parent)
98417             };
98418         }
98419         function getImportEntityNameVisibilityError() {
98420             return {
98421                 diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1,
98422                 errorNode: node,
98423                 typeName: node.name
98424             };
98425         }
98426         function getTypeAliasDeclarationVisibilityError(symbolAccessibilityResult) {
98427             return {
98428                 diagnosticMessage: symbolAccessibilityResult.errorModuleName
98429                     ? ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1_from_module_2
98430                     : ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
98431                 errorNode: ts.isJSDocTypeAlias(node) ? ts.Debug.checkDefined(node.typeExpression) : node.type,
98432                 typeName: ts.isJSDocTypeAlias(node) ? ts.getNameOfDeclaration(node) : node.name,
98433             };
98434         }
98435     }
98436     ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode;
98437 })(ts || (ts = {}));
98438 /*@internal*/
98439 var ts;
98440 (function (ts) {
98441     function getDeclarationDiagnostics(host, resolver, file) {
98442         var compilerOptions = host.getCompilerOptions();
98443         var result = ts.transformNodes(resolver, host, ts.factory, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJson), [transformDeclarations], /*allowDtsFiles*/ false);
98444         return result.diagnostics;
98445     }
98446     ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
98447     function hasInternalAnnotation(range, currentSourceFile) {
98448         var comment = currentSourceFile.text.substring(range.pos, range.end);
98449         return ts.stringContains(comment, "@internal");
98450     }
98451     function isInternalDeclaration(node, currentSourceFile) {
98452         var parseTreeNode = ts.getParseTreeNode(node);
98453         if (parseTreeNode && parseTreeNode.kind === 160 /* Parameter */) {
98454             var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
98455             var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
98456             var text = currentSourceFile.text;
98457             var commentRanges = previousSibling
98458                 ? ts.concatenate(
98459                 // to handle
98460                 // ... parameters, /* @internal */
98461                 // public param: string
98462                 ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
98463                 : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
98464             return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
98465         }
98466         var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
98467         return !!ts.forEach(leadingCommentRanges, function (range) {
98468             return hasInternalAnnotation(range, currentSourceFile);
98469         });
98470     }
98471     ts.isInternalDeclaration = isInternalDeclaration;
98472     var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
98473         2048 /* WriteClassExpressionAsTypeLiteral */ |
98474         4096 /* UseTypeOfFunction */ |
98475         8 /* UseStructuralFallback */ |
98476         524288 /* AllowEmptyTuple */ |
98477         4 /* GenerateNamesForShadowedTypeParams */ |
98478         1 /* NoTruncation */;
98479     /**
98480      * Transforms a ts file into a .d.ts file
98481      * This process requires type information, which is retrieved through the emit resolver. Because of this,
98482      * in many places this transformer assumes it will be operating on parse tree nodes directly.
98483      * This means that _no transforms should be allowed to occur before this one_.
98484      */
98485     function transformDeclarations(context) {
98486         var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); };
98487         var getSymbolAccessibilityDiagnostic = throwDiagnostic;
98488         var needsDeclare = true;
98489         var isBundledEmit = false;
98490         var resultHasExternalModuleIndicator = false;
98491         var needsScopeFixMarker = false;
98492         var resultHasScopeMarker = false;
98493         var enclosingDeclaration;
98494         var necessaryTypeReferences;
98495         var lateMarkedStatements;
98496         var lateStatementReplacementMap;
98497         var suppressNewDiagnosticContexts;
98498         var exportedModulesFromDeclarationEmit;
98499         var factory = context.factory;
98500         var host = context.getEmitHost();
98501         var symbolTracker = {
98502             trackSymbol: trackSymbol,
98503             reportInaccessibleThisError: reportInaccessibleThisError,
98504             reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
98505             reportCyclicStructureError: reportCyclicStructureError,
98506             reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
98507             reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
98508             reportTruncationError: reportTruncationError,
98509             moduleResolverHost: host,
98510             trackReferencedAmbientModule: trackReferencedAmbientModule,
98511             trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode,
98512             reportNonlocalAugmentation: reportNonlocalAugmentation
98513         };
98514         var errorNameNode;
98515         var errorFallbackNode;
98516         var currentSourceFile;
98517         var refs;
98518         var libs;
98519         var emittedImports; // must be declared in container so it can be `undefined` while transformer's first pass
98520         var resolver = context.getEmitResolver();
98521         var options = context.getCompilerOptions();
98522         var noResolve = options.noResolve, stripInternal = options.stripInternal;
98523         return transformRoot;
98524         function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
98525             if (!typeReferenceDirectives) {
98526                 return;
98527             }
98528             necessaryTypeReferences = necessaryTypeReferences || new ts.Set();
98529             for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
98530                 var ref = typeReferenceDirectives_2[_i];
98531                 necessaryTypeReferences.add(ref);
98532             }
98533         }
98534         function trackReferencedAmbientModule(node, symbol) {
98535             // If it is visible via `// <reference types="..."/>`, then we should just use that
98536             var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */);
98537             if (ts.length(directives)) {
98538                 return recordTypeReferenceDirectivesIfNecessary(directives);
98539             }
98540             // Otherwise we should emit a path-based reference
98541             var container = ts.getSourceFileOfNode(node);
98542             refs.set(ts.getOriginalNodeId(container), container);
98543         }
98544         function handleSymbolAccessibilityError(symbolAccessibilityResult) {
98545             if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
98546                 // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
98547                 if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
98548                     if (!lateMarkedStatements) {
98549                         lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
98550                     }
98551                     else {
98552                         for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) {
98553                             var ref = _a[_i];
98554                             ts.pushIfUnique(lateMarkedStatements, ref);
98555                         }
98556                     }
98557                 }
98558                 // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible
98559             }
98560             else {
98561                 // Report error
98562                 var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
98563                 if (errorInfo) {
98564                     if (errorInfo.typeName) {
98565                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
98566                     }
98567                     else {
98568                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
98569                     }
98570                 }
98571             }
98572         }
98573         function trackExternalModuleSymbolOfImportTypeNode(symbol) {
98574             if (!isBundledEmit) {
98575                 (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
98576             }
98577         }
98578         function trackSymbol(symbol, enclosingDeclaration, meaning) {
98579             if (symbol.flags & 262144 /* TypeParameter */)
98580                 return;
98581             handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
98582             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
98583         }
98584         function reportPrivateInBaseOfClassExpression(propertyName) {
98585             if (errorNameNode || errorFallbackNode) {
98586                 context.addDiagnostic(ts.createDiagnosticForNode((errorNameNode || errorFallbackNode), ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
98587             }
98588         }
98589         function reportInaccessibleUniqueSymbolError() {
98590             if (errorNameNode) {
98591                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "unique symbol"));
98592             }
98593         }
98594         function reportCyclicStructureError() {
98595             if (errorNameNode) {
98596                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_a_type_with_a_cyclic_structure_which_cannot_be_trivially_serialized_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode)));
98597             }
98598         }
98599         function reportInaccessibleThisError() {
98600             if (errorNameNode) {
98601                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), "this"));
98602             }
98603         }
98604         function reportLikelyUnsafeImportRequiredError(specifier) {
98605             if (errorNameNode) {
98606                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary, ts.declarationNameToString(errorNameNode), specifier));
98607             }
98608         }
98609         function reportTruncationError() {
98610             if (errorNameNode || errorFallbackNode) {
98611                 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));
98612             }
98613         }
98614         function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) {
98615             var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; });
98616             var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; });
98617             for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) {
98618                 var augmentations = augmentingDeclarations_1[_i];
98619                 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)));
98620             }
98621         }
98622         function transformDeclarationsForJS(sourceFile, bundled) {
98623             var oldDiag = getSymbolAccessibilityDiagnostic;
98624             getSymbolAccessibilityDiagnostic = function (s) { return (s.errorNode && ts.canProduceDiagnostics(s.errorNode) ? ts.createGetSymbolAccessibilityDiagnosticForNode(s.errorNode)(s) : ({
98625                 diagnosticMessage: s.errorModuleName
98626                     ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit
98627                     : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit,
98628                 errorNode: s.errorNode || sourceFile
98629             })); };
98630             var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled);
98631             getSymbolAccessibilityDiagnostic = oldDiag;
98632             return result;
98633         }
98634         function transformRoot(node) {
98635             if (node.kind === 297 /* SourceFile */ && node.isDeclarationFile) {
98636                 return node;
98637             }
98638             if (node.kind === 298 /* Bundle */) {
98639                 isBundledEmit = true;
98640                 refs = new ts.Map();
98641                 libs = new ts.Map();
98642                 var hasNoDefaultLib_1 = false;
98643                 var bundle = factory.createBundle(ts.map(node.sourceFiles, function (sourceFile) {
98644                     if (sourceFile.isDeclarationFile)
98645                         return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217
98646                     hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib;
98647                     currentSourceFile = sourceFile;
98648                     enclosingDeclaration = sourceFile;
98649                     lateMarkedStatements = undefined;
98650                     suppressNewDiagnosticContexts = false;
98651                     lateStatementReplacementMap = new ts.Map();
98652                     getSymbolAccessibilityDiagnostic = throwDiagnostic;
98653                     needsScopeFixMarker = false;
98654                     resultHasScopeMarker = false;
98655                     collectReferences(sourceFile, refs);
98656                     collectLibs(sourceFile, libs);
98657                     if (ts.isExternalOrCommonJsModule(sourceFile) || ts.isJsonSourceFile(sourceFile)) {
98658                         resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
98659                         needsDeclare = false;
98660                         var statements = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
98661                         var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([], [factory.createModifier(133 /* DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
98662                         return newFile;
98663                     }
98664                     needsDeclare = true;
98665                     var updated = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
98666                     return factory.updateSourceFile(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
98667                 }), ts.mapDefined(node.prepends, function (prepend) {
98668                     if (prepend.kind === 300 /* InputFiles */) {
98669                         var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
98670                         hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
98671                         collectReferences(sourceFile, refs);
98672                         recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
98673                         collectLibs(sourceFile, libs);
98674                         return sourceFile;
98675                     }
98676                     return prepend;
98677                 }));
98678                 bundle.syntheticFileReferences = [];
98679                 bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
98680                 bundle.syntheticLibReferences = getLibReferences();
98681                 bundle.hasNoDefaultLib = hasNoDefaultLib_1;
98682                 var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
98683                 var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1);
98684                 refs.forEach(referenceVisitor_1);
98685                 return bundle;
98686             }
98687             // Single source file
98688             needsDeclare = true;
98689             needsScopeFixMarker = false;
98690             resultHasScopeMarker = false;
98691             enclosingDeclaration = node;
98692             currentSourceFile = node;
98693             getSymbolAccessibilityDiagnostic = throwDiagnostic;
98694             isBundledEmit = false;
98695             resultHasExternalModuleIndicator = false;
98696             suppressNewDiagnosticContexts = false;
98697             lateMarkedStatements = undefined;
98698             lateStatementReplacementMap = new ts.Map();
98699             necessaryTypeReferences = undefined;
98700             refs = collectReferences(currentSourceFile, new ts.Map());
98701             libs = collectLibs(currentSourceFile, new ts.Map());
98702             var references = [];
98703             var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
98704             var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
98705             var combinedStatements;
98706             if (ts.isSourceFileJS(currentSourceFile)) {
98707                 combinedStatements = factory.createNodeArray(transformDeclarationsForJS(node));
98708                 refs.forEach(referenceVisitor);
98709                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
98710             }
98711             else {
98712                 var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
98713                 combinedStatements = ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
98714                 refs.forEach(referenceVisitor);
98715                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
98716                 if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
98717                     combinedStatements = ts.setTextRange(factory.createNodeArray(__spreadArray(__spreadArray([], combinedStatements), [ts.createEmptyExports(factory)])), combinedStatements);
98718                 }
98719             }
98720             var updated = factory.updateSourceFile(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
98721             updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
98722             return updated;
98723             function getLibReferences() {
98724                 return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
98725             }
98726             function getFileReferencesForUsedTypeReferences() {
98727                 return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
98728             }
98729             function getFileReferenceForTypeName(typeName) {
98730                 // Elide type references for which we have imports
98731                 if (emittedImports) {
98732                     for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
98733                         var importStatement = emittedImports_1[_i];
98734                         if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
98735                             var expr = importStatement.moduleReference.expression;
98736                             if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
98737                                 return undefined;
98738                             }
98739                         }
98740                         else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
98741                             return undefined;
98742                         }
98743                     }
98744                 }
98745                 return { fileName: typeName, pos: -1, end: -1 };
98746             }
98747             function mapReferencesIntoArray(references, outputFilePath) {
98748                 return function (file) {
98749                     var declFileName;
98750                     if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed
98751                         declFileName = file.fileName;
98752                     }
98753                     else {
98754                         if (isBundledEmit && ts.contains(node.sourceFiles, file))
98755                             return; // Omit references to files which are being merged
98756                         var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true);
98757                         declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName;
98758                     }
98759                     if (declFileName) {
98760                         var specifier = ts.moduleSpecifiers.getModuleSpecifier(__assign(__assign({}, options), { baseUrl: options.baseUrl && ts.toPath(options.baseUrl, host.getCurrentDirectory(), host.getCanonicalFileName) }), currentSourceFile, ts.toPath(outputFilePath, host.getCurrentDirectory(), host.getCanonicalFileName), ts.toPath(declFileName, host.getCurrentDirectory(), host.getCanonicalFileName), host, 
98761                         /*preferences*/ undefined);
98762                         if (!ts.pathIsRelative(specifier)) {
98763                             // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration
98764                             // via a non-relative name, emit a type reference directive to that non-relative name, rather than
98765                             // a relative path to the declaration file
98766                             recordTypeReferenceDirectivesIfNecessary([specifier]);
98767                             return;
98768                         }
98769                         var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
98770                         /*isAbsolutePathAnUrl*/ false);
98771                         if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) {
98772                             fileName = fileName.substring(2);
98773                         }
98774                         // omit references to files from node_modules (npm may disambiguate module
98775                         // references when installing this package, making the path is unreliable).
98776                         if (ts.startsWith(fileName, "node_modules/") || ts.pathContainsNodeModules(fileName)) {
98777                             return;
98778                         }
98779                         references.push({ pos: -1, end: -1, fileName: fileName });
98780                     }
98781                 };
98782             }
98783         }
98784         function collectReferences(sourceFile, ret) {
98785             if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
98786                 return ret;
98787             ts.forEach(sourceFile.referencedFiles, function (f) {
98788                 var elem = host.getSourceFileFromReference(sourceFile, f);
98789                 if (elem) {
98790                     ret.set(ts.getOriginalNodeId(elem), elem);
98791                 }
98792             });
98793             return ret;
98794         }
98795         function collectLibs(sourceFile, ret) {
98796             ts.forEach(sourceFile.libReferenceDirectives, function (ref) {
98797                 var lib = host.getLibFileFromReference(ref);
98798                 if (lib) {
98799                     ret.set(ts.toFileNameLowerCase(ref.fileName), true);
98800                 }
98801             });
98802             return ret;
98803         }
98804         function filterBindingPatternInitializers(name) {
98805             if (name.kind === 78 /* Identifier */) {
98806                 return name;
98807             }
98808             else {
98809                 if (name.kind === 197 /* ArrayBindingPattern */) {
98810                     return factory.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
98811                 }
98812                 else {
98813                     return factory.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
98814                 }
98815             }
98816             function visitBindingElement(elem) {
98817                 if (elem.kind === 222 /* OmittedExpression */) {
98818                     return elem;
98819                 }
98820                 return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined);
98821             }
98822         }
98823         function ensureParameter(p, modifierMask, type) {
98824             var oldDiag;
98825             if (!suppressNewDiagnosticContexts) {
98826                 oldDiag = getSymbolAccessibilityDiagnostic;
98827                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p);
98828             }
98829             var newParam = factory.updateParameterDeclaration(p, 
98830             /*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
98831             ensureNoInitializer(p));
98832             if (!suppressNewDiagnosticContexts) {
98833                 getSymbolAccessibilityDiagnostic = oldDiag;
98834             }
98835             return newParam;
98836         }
98837         function shouldPrintWithInitializer(node) {
98838             return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe
98839         }
98840         function ensureNoInitializer(node) {
98841             if (shouldPrintWithInitializer(node)) {
98842                 return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe
98843             }
98844             return undefined;
98845         }
98846         function ensureType(node, type, ignorePrivate) {
98847             if (!ignorePrivate && ts.hasEffectiveModifier(node, 8 /* Private */)) {
98848                 // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible)
98849                 return;
98850             }
98851             if (shouldPrintWithInitializer(node)) {
98852                 // Literal const declarations will have an initializer ensured rather than a type
98853                 return;
98854             }
98855             var shouldUseResolverType = node.kind === 160 /* Parameter */ &&
98856                 (resolver.isRequiredInitializedParameter(node) ||
98857                     resolver.isOptionalUninitializedParameterProperty(node));
98858             if (type && !shouldUseResolverType) {
98859                 return ts.visitNode(type, visitDeclarationSubtree);
98860             }
98861             if (!ts.getParseTreeNode(node)) {
98862                 return type ? ts.visitNode(type, visitDeclarationSubtree) : factory.createKeywordTypeNode(128 /* AnyKeyword */);
98863             }
98864             if (node.kind === 168 /* SetAccessor */) {
98865                 // 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
98866                 // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that)
98867                 return factory.createKeywordTypeNode(128 /* AnyKeyword */);
98868             }
98869             errorNameNode = node.name;
98870             var oldDiag;
98871             if (!suppressNewDiagnosticContexts) {
98872                 oldDiag = getSymbolAccessibilityDiagnostic;
98873                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node);
98874             }
98875             if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) {
98876                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
98877             }
98878             if (node.kind === 160 /* Parameter */
98879                 || node.kind === 163 /* PropertyDeclaration */
98880                 || node.kind === 162 /* PropertySignature */) {
98881                 if (!node.initializer)
98882                     return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType));
98883                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
98884             }
98885             return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
98886             function cleanup(returnValue) {
98887                 errorNameNode = undefined;
98888                 if (!suppressNewDiagnosticContexts) {
98889                     getSymbolAccessibilityDiagnostic = oldDiag;
98890                 }
98891                 return returnValue || factory.createKeywordTypeNode(128 /* AnyKeyword */);
98892             }
98893         }
98894         function isDeclarationAndNotVisible(node) {
98895             node = ts.getParseTreeNode(node);
98896             switch (node.kind) {
98897                 case 251 /* FunctionDeclaration */:
98898                 case 256 /* ModuleDeclaration */:
98899                 case 253 /* InterfaceDeclaration */:
98900                 case 252 /* ClassDeclaration */:
98901                 case 254 /* TypeAliasDeclaration */:
98902                 case 255 /* EnumDeclaration */:
98903                     return !resolver.isDeclarationVisible(node);
98904                 // The following should be doing their own visibility checks based on filtering their members
98905                 case 249 /* VariableDeclaration */:
98906                     return !getBindingNameVisible(node);
98907                 case 260 /* ImportEqualsDeclaration */:
98908                 case 261 /* ImportDeclaration */:
98909                 case 267 /* ExportDeclaration */:
98910                 case 266 /* ExportAssignment */:
98911                     return false;
98912             }
98913             return false;
98914         }
98915         function getBindingNameVisible(elem) {
98916             if (ts.isOmittedExpression(elem)) {
98917                 return false;
98918             }
98919             if (ts.isBindingPattern(elem.name)) {
98920                 // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible
98921                 return ts.some(elem.name.elements, getBindingNameVisible);
98922             }
98923             else {
98924                 return resolver.isDeclarationVisible(elem);
98925             }
98926         }
98927         function updateParamsList(node, params, modifierMask) {
98928             if (ts.hasEffectiveModifier(node, 8 /* Private */)) {
98929                 return undefined; // TODO: GH#18217
98930             }
98931             var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); });
98932             if (!newParams) {
98933                 return undefined; // TODO: GH#18217
98934             }
98935             return factory.createNodeArray(newParams, params.hasTrailingComma);
98936         }
98937         function updateAccessorParamsList(input, isPrivate) {
98938             var newParams;
98939             if (!isPrivate) {
98940                 var thisParameter = ts.getThisParameter(input);
98941                 if (thisParameter) {
98942                     newParams = [ensureParameter(thisParameter)];
98943                 }
98944             }
98945             if (ts.isSetAccessorDeclaration(input)) {
98946                 var newValueParameter = void 0;
98947                 if (!isPrivate) {
98948                     var valueParameter = ts.getSetAccessorValueParameter(input);
98949                     if (valueParameter) {
98950                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
98951                         newValueParameter = ensureParameter(valueParameter, /*modifierMask*/ undefined, accessorType);
98952                     }
98953                 }
98954                 if (!newValueParameter) {
98955                     newValueParameter = factory.createParameterDeclaration(
98956                     /*decorators*/ undefined, 
98957                     /*modifiers*/ undefined, 
98958                     /*dotDotDotToken*/ undefined, "value");
98959                 }
98960                 newParams = ts.append(newParams, newValueParameter);
98961             }
98962             return factory.createNodeArray(newParams || ts.emptyArray);
98963         }
98964         function ensureTypeParams(node, params) {
98965             return ts.hasEffectiveModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree);
98966         }
98967         function isEnclosingDeclaration(node) {
98968             return ts.isSourceFile(node)
98969                 || ts.isTypeAliasDeclaration(node)
98970                 || ts.isModuleDeclaration(node)
98971                 || ts.isClassDeclaration(node)
98972                 || ts.isInterfaceDeclaration(node)
98973                 || ts.isFunctionLike(node)
98974                 || ts.isIndexSignatureDeclaration(node)
98975                 || ts.isMappedTypeNode(node);
98976         }
98977         function checkEntityNameVisibility(entityName, enclosingDeclaration) {
98978             var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration);
98979             handleSymbolAccessibilityError(visibilityResult);
98980             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
98981         }
98982         function preserveJsDoc(updated, original) {
98983             if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) {
98984                 updated.jsDoc = original.jsDoc;
98985             }
98986             return ts.setCommentRange(updated, ts.getCommentRange(original));
98987         }
98988         function rewriteModuleSpecifier(parent, input) {
98989             if (!input)
98990                 return undefined; // TODO: GH#18217
98991             resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 256 /* ModuleDeclaration */ && parent.kind !== 195 /* ImportType */);
98992             if (ts.isStringLiteralLike(input)) {
98993                 if (isBundledEmit) {
98994                     var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
98995                     if (newName) {
98996                         return factory.createStringLiteral(newName);
98997                     }
98998                 }
98999                 else {
99000                     var symbol = resolver.getSymbolOfExternalModuleSpecifier(input);
99001                     if (symbol) {
99002                         (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
99003                     }
99004                 }
99005             }
99006             return input;
99007         }
99008         function transformImportEqualsDeclaration(decl) {
99009             if (!resolver.isDeclarationVisible(decl))
99010                 return;
99011             if (decl.moduleReference.kind === 272 /* ExternalModuleReference */) {
99012                 // Rewrite external module names if necessary
99013                 var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl);
99014                 return factory.updateImportEqualsDeclaration(decl, 
99015                 /*decorators*/ undefined, decl.modifiers, decl.isTypeOnly, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
99016             }
99017             else {
99018                 var oldDiag = getSymbolAccessibilityDiagnostic;
99019                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl);
99020                 checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
99021                 getSymbolAccessibilityDiagnostic = oldDiag;
99022                 return decl;
99023             }
99024         }
99025         function transformImportDeclaration(decl) {
99026             if (!decl.importClause) {
99027                 // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc)
99028                 return factory.updateImportDeclaration(decl, 
99029                 /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
99030             }
99031             // The `importClause` visibility corresponds to the default's visibility.
99032             var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined;
99033             if (!decl.importClause.namedBindings) {
99034                 // No named bindings (either namespace or list), meaning the import is just default or should be elided
99035                 return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, 
99036                 /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
99037             }
99038             if (decl.importClause.namedBindings.kind === 263 /* NamespaceImport */) {
99039                 // Namespace import (optionally with visible default)
99040                 var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined;
99041                 return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined;
99042             }
99043             // Named imports (optionally with visible default)
99044             var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; });
99045             if ((bindingList && bindingList.length) || visibleDefaultBinding) {
99046                 return factory.updateImportDeclaration(decl, 
99047                 /*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));
99048             }
99049             // Augmentation of export depends on import
99050             if (resolver.isImportRequiredByAugmentation(decl)) {
99051                 return factory.updateImportDeclaration(decl, 
99052                 /*decorators*/ undefined, decl.modifiers, 
99053                 /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
99054             }
99055             // Nothing visible
99056         }
99057         function transformAndReplaceLatePaintedStatements(statements) {
99058             // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
99059             // error handling which must now be included in the output and themselves checked for errors.
99060             // For example:
99061             // ```
99062             // module A {
99063             //   export module Q {}
99064             //   import B = Q;
99065             //   import C = B;
99066             //   export import D = C;
99067             // }
99068             // ```
99069             // 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
99070             // 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
99071             // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
99072             while (ts.length(lateMarkedStatements)) {
99073                 var i = lateMarkedStatements.shift();
99074                 if (!ts.isLateVisibilityPaintedStatement(i)) {
99075                     return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind));
99076                 }
99077                 var priorNeedsDeclare = needsDeclare;
99078                 needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit);
99079                 var result = transformTopLevelDeclaration(i);
99080                 needsDeclare = priorNeedsDeclare;
99081                 lateStatementReplacementMap.set(ts.getOriginalNodeId(i), result);
99082             }
99083             // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
99084             // (and remove them from the set to examine for outter declarations)
99085             return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
99086             function visitLateVisibilityMarkedStatements(statement) {
99087                 if (ts.isLateVisibilityPaintedStatement(statement)) {
99088                     var key = ts.getOriginalNodeId(statement);
99089                     if (lateStatementReplacementMap.has(key)) {
99090                         var result = lateStatementReplacementMap.get(key);
99091                         lateStatementReplacementMap.delete(key);
99092                         if (result) {
99093                             if (ts.isArray(result) ? ts.some(result, ts.needsScopeMarker) : ts.needsScopeMarker(result)) {
99094                                 // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
99095                                 needsScopeFixMarker = true;
99096                             }
99097                             if (ts.isSourceFile(statement.parent) && (ts.isArray(result) ? ts.some(result, ts.isExternalModuleIndicator) : ts.isExternalModuleIndicator(result))) {
99098                                 resultHasExternalModuleIndicator = true;
99099                             }
99100                         }
99101                         return result;
99102                     }
99103                 }
99104                 return statement;
99105             }
99106         }
99107         function visitDeclarationSubtree(input) {
99108             if (shouldStripInternal(input))
99109                 return;
99110             if (ts.isDeclaration(input)) {
99111                 if (isDeclarationAndNotVisible(input))
99112                     return;
99113                 if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) {
99114                     return;
99115                 }
99116             }
99117             // Elide implementation signatures from overload sets
99118             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
99119                 return;
99120             // Elide semicolon class statements
99121             if (ts.isSemicolonClassElement(input))
99122                 return;
99123             var previousEnclosingDeclaration;
99124             if (isEnclosingDeclaration(input)) {
99125                 previousEnclosingDeclaration = enclosingDeclaration;
99126                 enclosingDeclaration = input;
99127             }
99128             var oldDiag = getSymbolAccessibilityDiagnostic;
99129             // Setup diagnostic-related flags before first potential `cleanup` call, otherwise
99130             // We'd see a TDZ violation at runtime
99131             var canProduceDiagnostic = ts.canProduceDiagnostics(input);
99132             var oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
99133             var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 177 /* TypeLiteral */ || input.kind === 190 /* MappedType */) && input.parent.kind !== 254 /* TypeAliasDeclaration */);
99134             // Emit methods which are private as properties with no type information
99135             if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) {
99136                 if (ts.hasEffectiveModifier(input, 8 /* Private */)) {
99137                     if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input)
99138                         return; // Elide all but the first overload
99139                     return cleanup(factory.createPropertyDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
99140                 }
99141             }
99142             if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
99143                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
99144             }
99145             if (ts.isTypeQueryNode(input)) {
99146                 checkEntityNameVisibility(input.exprName, enclosingDeclaration);
99147             }
99148             if (shouldEnterSuppressNewDiagnosticsContextContext) {
99149                 // 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.
99150                 suppressNewDiagnosticContexts = true;
99151             }
99152             if (isProcessedComponent(input)) {
99153                 switch (input.kind) {
99154                     case 223 /* ExpressionWithTypeArguments */: {
99155                         if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) {
99156                             checkEntityNameVisibility(input.expression, enclosingDeclaration);
99157                         }
99158                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
99159                         return cleanup(factory.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments));
99160                     }
99161                     case 173 /* TypeReference */: {
99162                         checkEntityNameVisibility(input.typeName, enclosingDeclaration);
99163                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
99164                         return cleanup(factory.updateTypeReferenceNode(node, node.typeName, node.typeArguments));
99165                     }
99166                     case 170 /* ConstructSignature */:
99167                         return cleanup(factory.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
99168                     case 166 /* Constructor */: {
99169                         // A constructor declaration may not have a type annotation
99170                         var ctor = factory.createConstructorDeclaration(
99171                         /*decorators*/ undefined, 
99172                         /*modifiers*/ ensureModifiers(input), updateParamsList(input, input.parameters, 0 /* None */), 
99173                         /*body*/ undefined);
99174                         return cleanup(ctor);
99175                     }
99176                     case 165 /* MethodDeclaration */: {
99177                         if (ts.isPrivateIdentifier(input.name)) {
99178                             return cleanup(/*returnValue*/ undefined);
99179                         }
99180                         var sig = factory.createMethodDeclaration(
99181                         /*decorators*/ undefined, ensureModifiers(input), 
99182                         /*asteriskToken*/ undefined, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), 
99183                         /*body*/ undefined);
99184                         return cleanup(sig);
99185                     }
99186                     case 167 /* GetAccessor */: {
99187                         if (ts.isPrivateIdentifier(input.name)) {
99188                             return cleanup(/*returnValue*/ undefined);
99189                         }
99190                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
99191                         return cleanup(factory.updateGetAccessorDeclaration(input, 
99192                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), ensureType(input, accessorType), 
99193                         /*body*/ undefined));
99194                     }
99195                     case 168 /* SetAccessor */: {
99196                         if (ts.isPrivateIdentifier(input.name)) {
99197                             return cleanup(/*returnValue*/ undefined);
99198                         }
99199                         return cleanup(factory.updateSetAccessorDeclaration(input, 
99200                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), 
99201                         /*body*/ undefined));
99202                     }
99203                     case 163 /* PropertyDeclaration */:
99204                         if (ts.isPrivateIdentifier(input.name)) {
99205                             return cleanup(/*returnValue*/ undefined);
99206                         }
99207                         return cleanup(factory.updatePropertyDeclaration(input, 
99208                         /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
99209                     case 162 /* PropertySignature */:
99210                         if (ts.isPrivateIdentifier(input.name)) {
99211                             return cleanup(/*returnValue*/ undefined);
99212                         }
99213                         return cleanup(factory.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type)));
99214                     case 164 /* MethodSignature */: {
99215                         if (ts.isPrivateIdentifier(input.name)) {
99216                             return cleanup(/*returnValue*/ undefined);
99217                         }
99218                         return cleanup(factory.updateMethodSignature(input, ensureModifiers(input), input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
99219                     }
99220                     case 169 /* CallSignature */: {
99221                         return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
99222                     }
99223                     case 171 /* IndexSignature */: {
99224                         return cleanup(factory.updateIndexSignature(input, 
99225                         /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(128 /* AnyKeyword */)));
99226                     }
99227                     case 249 /* VariableDeclaration */: {
99228                         if (ts.isBindingPattern(input.name)) {
99229                             return recreateBindingPattern(input.name);
99230                         }
99231                         shouldEnterSuppressNewDiagnosticsContextContext = true;
99232                         suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types
99233                         return cleanup(factory.updateVariableDeclaration(input, input.name, /*exclamationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input)));
99234                     }
99235                     case 159 /* TypeParameter */: {
99236                         if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
99237                             return cleanup(factory.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined));
99238                         }
99239                         return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
99240                     }
99241                     case 184 /* ConditionalType */: {
99242                         // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration
99243                         // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type.
99244                         var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree);
99245                         var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree);
99246                         var oldEnclosingDecl = enclosingDeclaration;
99247                         enclosingDeclaration = input.trueType;
99248                         var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree);
99249                         enclosingDeclaration = oldEnclosingDecl;
99250                         var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree);
99251                         return cleanup(factory.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
99252                     }
99253                     case 174 /* FunctionType */: {
99254                         return cleanup(factory.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
99255                     }
99256                     case 175 /* ConstructorType */: {
99257                         return cleanup(factory.updateConstructorTypeNode(input, ensureModifiers(input), ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
99258                     }
99259                     case 195 /* ImportType */: {
99260                         if (!ts.isLiteralImportTypeNode(input))
99261                             return cleanup(input);
99262                         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));
99263                     }
99264                     default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]);
99265                 }
99266             }
99267             if (ts.isTupleTypeNode(input) && (ts.getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === ts.getLineAndCharacterOfPosition(currentSourceFile, input.end).line)) {
99268                 ts.setEmitFlags(input, 1 /* SingleLine */);
99269             }
99270             return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
99271             function cleanup(returnValue) {
99272                 if (returnValue && canProduceDiagnostic && ts.hasDynamicName(input)) {
99273                     checkName(input);
99274                 }
99275                 if (isEnclosingDeclaration(input)) {
99276                     enclosingDeclaration = previousEnclosingDeclaration;
99277                 }
99278                 if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
99279                     getSymbolAccessibilityDiagnostic = oldDiag;
99280                 }
99281                 if (shouldEnterSuppressNewDiagnosticsContextContext) {
99282                     suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
99283                 }
99284                 if (returnValue === input) {
99285                     return returnValue;
99286                 }
99287                 return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
99288             }
99289         }
99290         function isPrivateMethodTypeParameter(node) {
99291             return node.parent.kind === 165 /* MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* Private */);
99292         }
99293         function visitDeclarationStatements(input) {
99294             if (!isPreservedDeclarationStatement(input)) {
99295                 // return undefined for unmatched kinds to omit them from the tree
99296                 return;
99297             }
99298             if (shouldStripInternal(input))
99299                 return;
99300             switch (input.kind) {
99301                 case 267 /* ExportDeclaration */: {
99302                     if (ts.isSourceFile(input.parent)) {
99303                         resultHasExternalModuleIndicator = true;
99304                     }
99305                     resultHasScopeMarker = true;
99306                     // Always visible if the parent node isn't dropped for being not visible
99307                     // Rewrite external module names if necessary
99308                     return factory.updateExportDeclaration(input, 
99309                     /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier));
99310                 }
99311                 case 266 /* ExportAssignment */: {
99312                     // Always visible if the parent node isn't dropped for being not visible
99313                     if (ts.isSourceFile(input.parent)) {
99314                         resultHasExternalModuleIndicator = true;
99315                     }
99316                     resultHasScopeMarker = true;
99317                     if (input.expression.kind === 78 /* Identifier */) {
99318                         return input;
99319                     }
99320                     else {
99321                         var newId = factory.createUniqueName("_default", 16 /* Optimistic */);
99322                         getSymbolAccessibilityDiagnostic = function () { return ({
99323                             diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
99324                             errorNode: input
99325                         }); };
99326                         errorFallbackNode = input;
99327                         var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
99328                         errorFallbackNode = undefined;
99329                         var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */));
99330                         return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
99331                     }
99332                 }
99333             }
99334             var result = transformTopLevelDeclaration(input);
99335             // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
99336             lateStatementReplacementMap.set(ts.getOriginalNodeId(input), result);
99337             return input;
99338         }
99339         function stripExportModifiers(statement) {
99340             if (ts.isImportEqualsDeclaration(statement) || ts.hasEffectiveModifier(statement, 512 /* Default */) || !ts.canHaveModifiers(statement)) {
99341                 // `export import` statements should remain as-is, as imports are _not_ implicitly exported in an ambient namespace
99342                 // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too
99343                 return statement;
99344             }
99345             var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (11263 /* All */ ^ 1 /* Export */));
99346             return factory.updateModifiers(statement, modifiers);
99347         }
99348         function transformTopLevelDeclaration(input) {
99349             if (shouldStripInternal(input))
99350                 return;
99351             switch (input.kind) {
99352                 case 260 /* ImportEqualsDeclaration */: {
99353                     return transformImportEqualsDeclaration(input);
99354                 }
99355                 case 261 /* ImportDeclaration */: {
99356                     return transformImportDeclaration(input);
99357                 }
99358             }
99359             if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
99360                 return;
99361             // Elide implementation signatures from overload sets
99362             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
99363                 return;
99364             var previousEnclosingDeclaration;
99365             if (isEnclosingDeclaration(input)) {
99366                 previousEnclosingDeclaration = enclosingDeclaration;
99367                 enclosingDeclaration = input;
99368             }
99369             var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
99370             var oldDiag = getSymbolAccessibilityDiagnostic;
99371             if (canProdiceDiagnostic) {
99372                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
99373             }
99374             var previousNeedsDeclare = needsDeclare;
99375             switch (input.kind) {
99376                 case 254 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
99377                     return cleanup(factory.updateTypeAliasDeclaration(input, 
99378                     /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
99379                 case 253 /* InterfaceDeclaration */: {
99380                     return cleanup(factory.updateInterfaceDeclaration(input, 
99381                     /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
99382                 }
99383                 case 251 /* FunctionDeclaration */: {
99384                     // Generators lose their generator-ness, excepting their return type
99385                     var clean = cleanup(factory.updateFunctionDeclaration(input, 
99386                     /*decorators*/ undefined, ensureModifiers(input), 
99387                     /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), 
99388                     /*body*/ undefined));
99389                     if (clean && resolver.isExpandoFunctionDeclaration(input)) {
99390                         var props = resolver.getPropertiesOfContainerFunction(input);
99391                         // Use parseNodeFactory so it is usable as an enclosing declaration
99392                         var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* Namespace */);
99393                         ts.setParent(fakespace_1, enclosingDeclaration);
99394                         fakespace_1.locals = ts.createSymbolTable(props);
99395                         fakespace_1.symbol = props[0].parent;
99396                         var exportMappings_1 = [];
99397                         var declarations = ts.mapDefined(props, function (p) {
99398                             if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
99399                                 return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them)
99400                             }
99401                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
99402                             var type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace_1, declarationEmitNodeBuilderFlags, symbolTracker);
99403                             getSymbolAccessibilityDiagnostic = oldDiag;
99404                             var nameStr = ts.unescapeLeadingUnderscores(p.escapedName);
99405                             var isNonContextualKeywordName = ts.isStringANonContextualKeyword(nameStr);
99406                             var name = isNonContextualKeywordName ? factory.getGeneratedNameForNode(p.valueDeclaration) : factory.createIdentifier(nameStr);
99407                             if (isNonContextualKeywordName) {
99408                                 exportMappings_1.push([name, nameStr]);
99409                             }
99410                             var varDecl = factory.createVariableDeclaration(name, /*exclamationToken*/ undefined, type, /*initializer*/ undefined);
99411                             return factory.createVariableStatement(isNonContextualKeywordName ? undefined : [factory.createToken(92 /* ExportKeyword */)], factory.createVariableDeclarationList([varDecl]));
99412                         });
99413                         if (!exportMappings_1.length) {
99414                             declarations = ts.mapDefined(declarations, function (declaration) { return factory.updateModifiers(declaration, 0 /* None */); });
99415                         }
99416                         else {
99417                             declarations.push(factory.createExportDeclaration(
99418                             /*decorators*/ undefined, 
99419                             /*modifiers*/ undefined, 
99420                             /*isTypeOnly*/ false, factory.createNamedExports(ts.map(exportMappings_1, function (_a) {
99421                                 var gen = _a[0], exp = _a[1];
99422                                 return factory.createExportSpecifier(gen, exp);
99423                             }))));
99424                         }
99425                         var namespaceDecl = factory.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* Namespace */);
99426                         if (!ts.hasEffectiveModifier(clean, 512 /* Default */)) {
99427                             return [clean, namespaceDecl];
99428                         }
99429                         var modifiers = factory.createModifiersFromModifierFlags((ts.getEffectiveModifierFlags(clean) & ~513 /* ExportDefault */) | 2 /* Ambient */);
99430                         var cleanDeclaration = factory.updateFunctionDeclaration(clean, 
99431                         /*decorators*/ undefined, modifiers, 
99432                         /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, 
99433                         /*body*/ undefined);
99434                         var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, 
99435                         /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body);
99436                         var exportDefaultDeclaration = factory.createExportAssignment(
99437                         /*decorators*/ undefined, 
99438                         /*modifiers*/ undefined, 
99439                         /*isExportEquals*/ false, namespaceDecl.name);
99440                         if (ts.isSourceFile(input.parent)) {
99441                             resultHasExternalModuleIndicator = true;
99442                         }
99443                         resultHasScopeMarker = true;
99444                         return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration];
99445                     }
99446                     else {
99447                         return clean;
99448                     }
99449                 }
99450                 case 256 /* ModuleDeclaration */: {
99451                     needsDeclare = false;
99452                     var inner = input.body;
99453                     if (inner && inner.kind === 257 /* ModuleBlock */) {
99454                         var oldNeedsScopeFix = needsScopeFixMarker;
99455                         var oldHasScopeFix = resultHasScopeMarker;
99456                         resultHasScopeMarker = false;
99457                         needsScopeFixMarker = false;
99458                         var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
99459                         var lateStatements = transformAndReplaceLatePaintedStatements(statements);
99460                         if (input.flags & 8388608 /* Ambient */) {
99461                             needsScopeFixMarker = false; // If it was `declare`'d everything is implicitly exported already, ignore late printed "privates"
99462                         }
99463                         // With the final list of statements, there are 3 possibilities:
99464                         // 1. There's an export assignment or export declaration in the namespace - do nothing
99465                         // 2. Everything is exported and there are no export assignments or export declarations - strip all export modifiers
99466                         // 3. Some things are exported, some are not, and there's no marker - add an empty marker
99467                         if (!ts.isGlobalScopeAugmentation(input) && !hasScopeMarker(lateStatements) && !resultHasScopeMarker) {
99468                             if (needsScopeFixMarker) {
99469                                 lateStatements = factory.createNodeArray(__spreadArray(__spreadArray([], lateStatements), [ts.createEmptyExports(factory)]));
99470                             }
99471                             else {
99472                                 lateStatements = ts.visitNodes(lateStatements, stripExportModifiers);
99473                             }
99474                         }
99475                         var body = factory.updateModuleBlock(inner, lateStatements);
99476                         needsDeclare = previousNeedsDeclare;
99477                         needsScopeFixMarker = oldNeedsScopeFix;
99478                         resultHasScopeMarker = oldHasScopeFix;
99479                         var mods = ensureModifiers(input);
99480                         return cleanup(factory.updateModuleDeclaration(input, 
99481                         /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
99482                     }
99483                     else {
99484                         needsDeclare = previousNeedsDeclare;
99485                         var mods = ensureModifiers(input);
99486                         needsDeclare = false;
99487                         ts.visitNode(inner, visitDeclarationStatements);
99488                         // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
99489                         var id = ts.getOriginalNodeId(inner); // TODO: GH#18217
99490                         var body = lateStatementReplacementMap.get(id);
99491                         lateStatementReplacementMap.delete(id);
99492                         return cleanup(factory.updateModuleDeclaration(input, 
99493                         /*decorators*/ undefined, mods, input.name, body));
99494                     }
99495                 }
99496                 case 252 /* ClassDeclaration */: {
99497                     errorNameNode = input.name;
99498                     errorFallbackNode = input;
99499                     var modifiers = factory.createNodeArray(ensureModifiers(input));
99500                     var typeParameters = ensureTypeParams(input, input.typeParameters);
99501                     var ctor = ts.getFirstConstructorWithBody(input);
99502                     var parameterProperties = void 0;
99503                     if (ctor) {
99504                         var oldDiag_1 = getSymbolAccessibilityDiagnostic;
99505                         parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
99506                             if (!ts.hasSyntacticModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
99507                                 return;
99508                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
99509                             if (param.name.kind === 78 /* Identifier */) {
99510                                 return preserveJsDoc(factory.createPropertyDeclaration(
99511                                 /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param);
99512                             }
99513                             else {
99514                                 // Pattern - this is currently an error, but we emit declarations for it somewhat correctly
99515                                 return walkBindingPattern(param.name);
99516                             }
99517                             function walkBindingPattern(pattern) {
99518                                 var elems;
99519                                 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
99520                                     var elem = _a[_i];
99521                                     if (ts.isOmittedExpression(elem))
99522                                         continue;
99523                                     if (ts.isBindingPattern(elem.name)) {
99524                                         elems = ts.concatenate(elems, walkBindingPattern(elem.name));
99525                                     }
99526                                     elems = elems || [];
99527                                     elems.push(factory.createPropertyDeclaration(
99528                                     /*decorators*/ undefined, ensureModifiers(param), elem.name, 
99529                                     /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), 
99530                                     /*initializer*/ undefined));
99531                                 }
99532                                 return elems;
99533                             }
99534                         }));
99535                         getSymbolAccessibilityDiagnostic = oldDiag_1;
99536                     }
99537                     var hasPrivateIdentifier = ts.some(input.members, function (member) { return !!member.name && ts.isPrivateIdentifier(member.name); });
99538                     // When the class has at least one private identifier, create a unique constant identifier to retain the nominal typing behavior
99539                     // Prevents other classes with the same public members from being used in place of the current class
99540                     var privateIdentifier = hasPrivateIdentifier ? [
99541                         factory.createPropertyDeclaration(
99542                         /*decorators*/ undefined, 
99543                         /*modifiers*/ undefined, factory.createPrivateIdentifier("#private"), 
99544                         /*questionToken*/ undefined, 
99545                         /*type*/ undefined, 
99546                         /*initializer*/ undefined)
99547                     ] : undefined;
99548                     var memberNodes = ts.concatenate(ts.concatenate(privateIdentifier, parameterProperties), ts.visitNodes(input.members, visitDeclarationSubtree));
99549                     var members = factory.createNodeArray(memberNodes);
99550                     var extendsClause_1 = ts.getEffectiveBaseTypeNode(input);
99551                     if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 103 /* NullKeyword */) {
99552                         // We must add a temporary declaration for the extends clause expression
99553                         var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default";
99554                         var newId_1 = factory.createUniqueName(oldId + "_base", 16 /* Optimistic */);
99555                         getSymbolAccessibilityDiagnostic = function () { return ({
99556                             diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
99557                             errorNode: extendsClause_1,
99558                             typeName: input.name
99559                         }); };
99560                         var varDecl = factory.createVariableDeclaration(newId_1, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
99561                         var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */));
99562                         var heritageClauses = factory.createNodeArray(ts.map(input.heritageClauses, function (clause) {
99563                             if (clause.token === 93 /* ExtendsKeyword */) {
99564                                 var oldDiag_2 = getSymbolAccessibilityDiagnostic;
99565                                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
99566                                 var newClause = factory.updateHeritageClause(clause, ts.map(clause.types, function (t) { return factory.updateExpressionWithTypeArguments(t, newId_1, ts.visitNodes(t.typeArguments, visitDeclarationSubtree)); }));
99567                                 getSymbolAccessibilityDiagnostic = oldDiag_2;
99568                                 return newClause;
99569                             }
99570                             return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 103 /* NullKeyword */; })), visitDeclarationSubtree));
99571                         }));
99572                         return [statement, cleanup(factory.updateClassDeclaration(input, 
99573                             /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217
99574                     }
99575                     else {
99576                         var heritageClauses = transformHeritageClauses(input.heritageClauses);
99577                         return cleanup(factory.updateClassDeclaration(input, 
99578                         /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members));
99579                     }
99580                 }
99581                 case 232 /* VariableStatement */: {
99582                     return cleanup(transformVariableStatement(input));
99583                 }
99584                 case 255 /* EnumDeclaration */: {
99585                     return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) {
99586                         if (shouldStripInternal(m))
99587                             return;
99588                         // Rewrite enum values to their constants, if available
99589                         var constValue = resolver.getConstantValue(m);
99590                         return preserveJsDoc(factory.updateEnumMember(m, m.name, constValue !== undefined ? typeof constValue === "string" ? factory.createStringLiteral(constValue) : factory.createNumericLiteral(constValue) : undefined), m);
99591                     }))));
99592                 }
99593             }
99594             // Anything left unhandled is an error, so this should be unreachable
99595             return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
99596             function cleanup(node) {
99597                 if (isEnclosingDeclaration(input)) {
99598                     enclosingDeclaration = previousEnclosingDeclaration;
99599                 }
99600                 if (canProdiceDiagnostic) {
99601                     getSymbolAccessibilityDiagnostic = oldDiag;
99602                 }
99603                 if (input.kind === 256 /* ModuleDeclaration */) {
99604                     needsDeclare = previousNeedsDeclare;
99605                 }
99606                 if (node === input) {
99607                     return node;
99608                 }
99609                 errorFallbackNode = undefined;
99610                 errorNameNode = undefined;
99611                 return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
99612             }
99613         }
99614         function transformVariableStatement(input) {
99615             if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible))
99616                 return;
99617             var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree);
99618             if (!ts.length(nodes))
99619                 return;
99620             return factory.updateVariableStatement(input, factory.createNodeArray(ensureModifiers(input)), factory.updateVariableDeclarationList(input.declarationList, nodes));
99621         }
99622         function recreateBindingPattern(d) {
99623             return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); }));
99624         }
99625         function recreateBindingElement(e) {
99626             if (e.kind === 222 /* OmittedExpression */) {
99627                 return;
99628             }
99629             if (e.name) {
99630                 if (!getBindingNameVisible(e))
99631                     return;
99632                 if (ts.isBindingPattern(e.name)) {
99633                     return recreateBindingPattern(e.name);
99634                 }
99635                 else {
99636                     return factory.createVariableDeclaration(e.name, /*exclamationToken*/ undefined, ensureType(e, /*type*/ undefined), /*initializer*/ undefined);
99637                 }
99638             }
99639         }
99640         function checkName(node) {
99641             var oldDiag;
99642             if (!suppressNewDiagnosticContexts) {
99643                 oldDiag = getSymbolAccessibilityDiagnostic;
99644                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node);
99645             }
99646             errorNameNode = node.name;
99647             ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names
99648             var decl = node;
99649             var entityName = decl.name.expression;
99650             checkEntityNameVisibility(entityName, enclosingDeclaration);
99651             if (!suppressNewDiagnosticContexts) {
99652                 getSymbolAccessibilityDiagnostic = oldDiag;
99653             }
99654             errorNameNode = undefined;
99655         }
99656         function shouldStripInternal(node) {
99657             return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
99658         }
99659         function isScopeMarker(node) {
99660             return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
99661         }
99662         function hasScopeMarker(statements) {
99663             return ts.some(statements, isScopeMarker);
99664         }
99665         function ensureModifiers(node) {
99666             var currentFlags = ts.getEffectiveModifierFlags(node);
99667             var newFlags = ensureModifierFlags(node);
99668             if (currentFlags === newFlags) {
99669                 return node.modifiers;
99670             }
99671             return factory.createModifiersFromModifierFlags(newFlags);
99672         }
99673         function ensureModifierFlags(node) {
99674             var mask = 11263 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
99675             var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
99676             var parentIsFile = node.parent.kind === 297 /* SourceFile */;
99677             if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
99678                 mask ^= 2 /* Ambient */;
99679                 additions = 0 /* None */;
99680             }
99681             return maskModifierFlags(node, mask, additions);
99682         }
99683         function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) {
99684             var accessorType = getTypeAnnotationFromAccessor(node);
99685             if (!accessorType && node !== accessors.firstAccessor) {
99686                 accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor);
99687                 // 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
99688                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.firstAccessor);
99689             }
99690             if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) {
99691                 accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
99692                 // 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
99693                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor);
99694             }
99695             return accessorType;
99696         }
99697         function transformHeritageClauses(nodes) {
99698             return factory.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) {
99699                 return ts.isEntityNameExpression(t.expression) || (clause.token === 93 /* ExtendsKeyword */ && t.expression.kind === 103 /* NullKeyword */);
99700             })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; }));
99701         }
99702     }
99703     ts.transformDeclarations = transformDeclarations;
99704     function isAlwaysType(node) {
99705         if (node.kind === 253 /* InterfaceDeclaration */) {
99706             return true;
99707         }
99708         return false;
99709     }
99710     // Elide "public" modifier, as it is the default
99711     function maskModifiers(node, modifierMask, modifierAdditions) {
99712         return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
99713     }
99714     function maskModifierFlags(node, modifierMask, modifierAdditions) {
99715         if (modifierMask === void 0) { modifierMask = 11263 /* All */ ^ 4 /* Public */; }
99716         if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; }
99717         var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions;
99718         if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) {
99719             // A non-exported default is a nonsequitor - we usually try to remove all export modifiers
99720             // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid
99721             flags ^= 1 /* Export */;
99722         }
99723         if (flags & 512 /* Default */ && flags & 2 /* Ambient */) {
99724             flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed)
99725         }
99726         return flags;
99727     }
99728     function getTypeAnnotationFromAccessor(accessor) {
99729         if (accessor) {
99730             return accessor.kind === 167 /* GetAccessor */
99731                 ? accessor.type // Getter - return type
99732                 : accessor.parameters.length > 0
99733                     ? accessor.parameters[0].type // Setter parameter type
99734                     : undefined;
99735         }
99736     }
99737     function canHaveLiteralInitializer(node) {
99738         switch (node.kind) {
99739             case 163 /* PropertyDeclaration */:
99740             case 162 /* PropertySignature */:
99741                 return !ts.hasEffectiveModifier(node, 8 /* Private */);
99742             case 160 /* Parameter */:
99743             case 249 /* VariableDeclaration */:
99744                 return true;
99745         }
99746         return false;
99747     }
99748     function isPreservedDeclarationStatement(node) {
99749         switch (node.kind) {
99750             case 251 /* FunctionDeclaration */:
99751             case 256 /* ModuleDeclaration */:
99752             case 260 /* ImportEqualsDeclaration */:
99753             case 253 /* InterfaceDeclaration */:
99754             case 252 /* ClassDeclaration */:
99755             case 254 /* TypeAliasDeclaration */:
99756             case 255 /* EnumDeclaration */:
99757             case 232 /* VariableStatement */:
99758             case 261 /* ImportDeclaration */:
99759             case 267 /* ExportDeclaration */:
99760             case 266 /* ExportAssignment */:
99761                 return true;
99762         }
99763         return false;
99764     }
99765     function isProcessedComponent(node) {
99766         switch (node.kind) {
99767             case 170 /* ConstructSignature */:
99768             case 166 /* Constructor */:
99769             case 165 /* MethodDeclaration */:
99770             case 167 /* GetAccessor */:
99771             case 168 /* SetAccessor */:
99772             case 163 /* PropertyDeclaration */:
99773             case 162 /* PropertySignature */:
99774             case 164 /* MethodSignature */:
99775             case 169 /* CallSignature */:
99776             case 171 /* IndexSignature */:
99777             case 249 /* VariableDeclaration */:
99778             case 159 /* TypeParameter */:
99779             case 223 /* ExpressionWithTypeArguments */:
99780             case 173 /* TypeReference */:
99781             case 184 /* ConditionalType */:
99782             case 174 /* FunctionType */:
99783             case 175 /* ConstructorType */:
99784             case 195 /* ImportType */:
99785                 return true;
99786         }
99787         return false;
99788     }
99789 })(ts || (ts = {}));
99790 /* @internal */
99791 var ts;
99792 (function (ts) {
99793     function getModuleTransformer(moduleKind) {
99794         switch (moduleKind) {
99795             case ts.ModuleKind.ESNext:
99796             case ts.ModuleKind.ES2020:
99797             case ts.ModuleKind.ES2015:
99798                 return ts.transformECMAScriptModule;
99799             case ts.ModuleKind.System:
99800                 return ts.transformSystemModule;
99801             default:
99802                 return ts.transformModule;
99803         }
99804     }
99805     var TransformationState;
99806     (function (TransformationState) {
99807         TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized";
99808         TransformationState[TransformationState["Initialized"] = 1] = "Initialized";
99809         TransformationState[TransformationState["Completed"] = 2] = "Completed";
99810         TransformationState[TransformationState["Disposed"] = 3] = "Disposed";
99811     })(TransformationState || (TransformationState = {}));
99812     var SyntaxKindFeatureFlags;
99813     (function (SyntaxKindFeatureFlags) {
99814         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution";
99815         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications";
99816     })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {}));
99817     ts.noTransformers = { scriptTransformers: ts.emptyArray, declarationTransformers: ts.emptyArray };
99818     function getTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
99819         return {
99820             scriptTransformers: getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles),
99821             declarationTransformers: getDeclarationTransformers(customTransformers),
99822         };
99823     }
99824     ts.getTransformers = getTransformers;
99825     function getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
99826         if (emitOnlyDtsFiles)
99827             return ts.emptyArray;
99828         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
99829         var moduleKind = ts.getEmitModuleKind(compilerOptions);
99830         var transformers = [];
99831         ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory));
99832         transformers.push(ts.transformTypeScript);
99833         transformers.push(ts.transformClassFields);
99834         if (ts.getJSXTransformEnabled(compilerOptions)) {
99835             transformers.push(ts.transformJsx);
99836         }
99837         if (languageVersion < 99 /* ESNext */) {
99838             transformers.push(ts.transformESNext);
99839         }
99840         if (languageVersion < 7 /* ES2020 */) {
99841             transformers.push(ts.transformES2020);
99842         }
99843         if (languageVersion < 6 /* ES2019 */) {
99844             transformers.push(ts.transformES2019);
99845         }
99846         if (languageVersion < 5 /* ES2018 */) {
99847             transformers.push(ts.transformES2018);
99848         }
99849         if (languageVersion < 4 /* ES2017 */) {
99850             transformers.push(ts.transformES2017);
99851         }
99852         if (languageVersion < 3 /* ES2016 */) {
99853             transformers.push(ts.transformES2016);
99854         }
99855         if (languageVersion < 2 /* ES2015 */) {
99856             transformers.push(ts.transformES2015);
99857             transformers.push(ts.transformGenerators);
99858         }
99859         transformers.push(getModuleTransformer(moduleKind));
99860         // The ES5 transformer is last so that it can substitute expressions like `exports.default`
99861         // for ES3.
99862         if (languageVersion < 1 /* ES5 */) {
99863             transformers.push(ts.transformES5);
99864         }
99865         ts.addRange(transformers, customTransformers && ts.map(customTransformers.after, wrapScriptTransformerFactory));
99866         return transformers;
99867     }
99868     function getDeclarationTransformers(customTransformers) {
99869         var transformers = [];
99870         transformers.push(ts.transformDeclarations);
99871         ts.addRange(transformers, customTransformers && ts.map(customTransformers.afterDeclarations, wrapDeclarationTransformerFactory));
99872         return transformers;
99873     }
99874     /**
99875      * Wrap a custom script or declaration transformer object in a `Transformer` callback with fallback support for transforming bundles.
99876      */
99877     function wrapCustomTransformer(transformer) {
99878         return function (node) { return ts.isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node); };
99879     }
99880     /**
99881      * Wrap a transformer factory that may return a custom script or declaration transformer object.
99882      */
99883     function wrapCustomTransformerFactory(transformer, handleDefault) {
99884         return function (context) {
99885             var customTransformer = transformer(context);
99886             return typeof customTransformer === "function"
99887                 ? handleDefault(context, customTransformer)
99888                 : wrapCustomTransformer(customTransformer);
99889         };
99890     }
99891     function wrapScriptTransformerFactory(transformer) {
99892         return wrapCustomTransformerFactory(transformer, ts.chainBundle);
99893     }
99894     function wrapDeclarationTransformerFactory(transformer) {
99895         return wrapCustomTransformerFactory(transformer, function (_, node) { return node; });
99896     }
99897     function noEmitSubstitution(_hint, node) {
99898         return node;
99899     }
99900     ts.noEmitSubstitution = noEmitSubstitution;
99901     function noEmitNotification(hint, node, callback) {
99902         callback(hint, node);
99903     }
99904     ts.noEmitNotification = noEmitNotification;
99905     /**
99906      * Transforms an array of SourceFiles by passing them through each transformer.
99907      *
99908      * @param resolver The emit resolver provided by the checker.
99909      * @param host The emit host object used to interact with the file system.
99910      * @param options Compiler options to surface in the `TransformationContext`.
99911      * @param nodes An array of nodes to transform.
99912      * @param transforms An array of `TransformerFactory` callbacks.
99913      * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
99914      */
99915     function transformNodes(resolver, host, factory, options, nodes, transformers, allowDtsFiles) {
99916         var enabledSyntaxKindFeatures = new Array(341 /* Count */);
99917         var lexicalEnvironmentVariableDeclarations;
99918         var lexicalEnvironmentFunctionDeclarations;
99919         var lexicalEnvironmentStatements;
99920         var lexicalEnvironmentFlags = 0 /* None */;
99921         var lexicalEnvironmentVariableDeclarationsStack = [];
99922         var lexicalEnvironmentFunctionDeclarationsStack = [];
99923         var lexicalEnvironmentStatementsStack = [];
99924         var lexicalEnvironmentFlagsStack = [];
99925         var lexicalEnvironmentStackOffset = 0;
99926         var lexicalEnvironmentSuspended = false;
99927         var emitHelpers;
99928         var onSubstituteNode = noEmitSubstitution;
99929         var onEmitNode = noEmitNotification;
99930         var state = 0 /* Uninitialized */;
99931         var diagnostics = [];
99932         // The transformation context is provided to each transformer as part of transformer
99933         // initialization.
99934         var context = {
99935             factory: factory,
99936             getCompilerOptions: function () { return options; },
99937             getEmitResolver: function () { return resolver; },
99938             getEmitHost: function () { return host; },
99939             getEmitHelperFactory: ts.memoize(function () { return ts.createEmitHelperFactory(context); }),
99940             startLexicalEnvironment: startLexicalEnvironment,
99941             suspendLexicalEnvironment: suspendLexicalEnvironment,
99942             resumeLexicalEnvironment: resumeLexicalEnvironment,
99943             endLexicalEnvironment: endLexicalEnvironment,
99944             setLexicalEnvironmentFlags: setLexicalEnvironmentFlags,
99945             getLexicalEnvironmentFlags: getLexicalEnvironmentFlags,
99946             hoistVariableDeclaration: hoistVariableDeclaration,
99947             hoistFunctionDeclaration: hoistFunctionDeclaration,
99948             addInitializationStatement: addInitializationStatement,
99949             requestEmitHelper: requestEmitHelper,
99950             readEmitHelpers: readEmitHelpers,
99951             enableSubstitution: enableSubstitution,
99952             enableEmitNotification: enableEmitNotification,
99953             isSubstitutionEnabled: isSubstitutionEnabled,
99954             isEmitNotificationEnabled: isEmitNotificationEnabled,
99955             get onSubstituteNode() { return onSubstituteNode; },
99956             set onSubstituteNode(value) {
99957                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
99958                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
99959                 onSubstituteNode = value;
99960             },
99961             get onEmitNode() { return onEmitNode; },
99962             set onEmitNode(value) {
99963                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
99964                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
99965                 onEmitNode = value;
99966             },
99967             addDiagnostic: function (diag) {
99968                 diagnostics.push(diag);
99969             }
99970         };
99971         // Ensure the parse tree is clean before applying transformations
99972         for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
99973             var node = nodes_2[_i];
99974             ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
99975         }
99976         ts.performance.mark("beforeTransform");
99977         // Chain together and initialize each transformer.
99978         var transformersWithContext = transformers.map(function (t) { return t(context); });
99979         var transformation = function (node) {
99980             for (var _i = 0, transformersWithContext_1 = transformersWithContext; _i < transformersWithContext_1.length; _i++) {
99981                 var transform = transformersWithContext_1[_i];
99982                 node = transform(node);
99983             }
99984             return node;
99985         };
99986         // prevent modification of transformation hooks.
99987         state = 1 /* Initialized */;
99988         // Transform each node.
99989         var transformed = [];
99990         for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) {
99991             var node = nodes_3[_a];
99992             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end });
99993             transformed.push((allowDtsFiles ? transformation : transformRoot)(node));
99994             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
99995         }
99996         // prevent modification of the lexical environment.
99997         state = 2 /* Completed */;
99998         ts.performance.mark("afterTransform");
99999         ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
100000         return {
100001             transformed: transformed,
100002             substituteNode: substituteNode,
100003             emitNodeWithNotification: emitNodeWithNotification,
100004             isEmitNotificationEnabled: isEmitNotificationEnabled,
100005             dispose: dispose,
100006             diagnostics: diagnostics
100007         };
100008         function transformRoot(node) {
100009             return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
100010         }
100011         /**
100012          * Enables expression substitutions in the pretty printer for the provided SyntaxKind.
100013          */
100014         function enableSubstitution(kind) {
100015             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
100016             enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
100017         }
100018         /**
100019          * Determines whether expression substitutions are enabled for the provided node.
100020          */
100021         function isSubstitutionEnabled(node) {
100022             return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0
100023                 && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0;
100024         }
100025         /**
100026          * Emits a node with possible substitution.
100027          *
100028          * @param hint A hint as to the intended usage of the node.
100029          * @param node The node to emit.
100030          * @param emitCallback The callback used to emit the node or its substitute.
100031          */
100032         function substituteNode(hint, node) {
100033             ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
100034             return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
100035         }
100036         /**
100037          * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
100038          */
100039         function enableEmitNotification(kind) {
100040             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
100041             enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
100042         }
100043         /**
100044          * Determines whether before/after emit notifications should be raised in the pretty
100045          * printer when it emits a node.
100046          */
100047         function isEmitNotificationEnabled(node) {
100048             return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0
100049                 || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0;
100050         }
100051         /**
100052          * Emits a node with possible emit notification.
100053          *
100054          * @param hint A hint as to the intended usage of the node.
100055          * @param node The node to emit.
100056          * @param emitCallback The callback used to emit the node.
100057          */
100058         function emitNodeWithNotification(hint, node, emitCallback) {
100059             ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
100060             if (node) {
100061                 // TODO: Remove check and unconditionally use onEmitNode when API is breakingly changed
100062                 // (see https://github.com/microsoft/TypeScript/pull/36248/files/5062623f39120171b98870c71344b3242eb03d23#r369766739)
100063                 if (isEmitNotificationEnabled(node)) {
100064                     onEmitNode(hint, node, emitCallback);
100065                 }
100066                 else {
100067                     emitCallback(hint, node);
100068                 }
100069             }
100070         }
100071         /**
100072          * Records a hoisted variable declaration for the provided name within a lexical environment.
100073          */
100074         function hoistVariableDeclaration(name) {
100075             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
100076             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
100077             var decl = ts.setEmitFlags(factory.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */);
100078             if (!lexicalEnvironmentVariableDeclarations) {
100079                 lexicalEnvironmentVariableDeclarations = [decl];
100080             }
100081             else {
100082                 lexicalEnvironmentVariableDeclarations.push(decl);
100083             }
100084             if (lexicalEnvironmentFlags & 1 /* InParameters */) {
100085                 lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */;
100086             }
100087         }
100088         /**
100089          * Records a hoisted function declaration within a lexical environment.
100090          */
100091         function hoistFunctionDeclaration(func) {
100092             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
100093             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
100094             ts.setEmitFlags(func, 1048576 /* CustomPrologue */);
100095             if (!lexicalEnvironmentFunctionDeclarations) {
100096                 lexicalEnvironmentFunctionDeclarations = [func];
100097             }
100098             else {
100099                 lexicalEnvironmentFunctionDeclarations.push(func);
100100             }
100101         }
100102         /**
100103          * Adds an initialization statement to the top of the lexical environment.
100104          */
100105         function addInitializationStatement(node) {
100106             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
100107             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
100108             ts.setEmitFlags(node, 1048576 /* CustomPrologue */);
100109             if (!lexicalEnvironmentStatements) {
100110                 lexicalEnvironmentStatements = [node];
100111             }
100112             else {
100113                 lexicalEnvironmentStatements.push(node);
100114             }
100115         }
100116         /**
100117          * Starts a new lexical environment. Any existing hoisted variable or function declarations
100118          * are pushed onto a stack, and the related storage variables are reset.
100119          */
100120         function startLexicalEnvironment() {
100121             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
100122             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
100123             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
100124             // Save the current lexical environment. Rather than resizing the array we adjust the
100125             // stack size variable. This allows us to reuse existing array slots we've
100126             // already allocated between transformations to avoid allocation and GC overhead during
100127             // transformation.
100128             lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
100129             lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
100130             lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements;
100131             lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags;
100132             lexicalEnvironmentStackOffset++;
100133             lexicalEnvironmentVariableDeclarations = undefined;
100134             lexicalEnvironmentFunctionDeclarations = undefined;
100135             lexicalEnvironmentStatements = undefined;
100136             lexicalEnvironmentFlags = 0 /* None */;
100137         }
100138         /** Suspends the current lexical environment, usually after visiting a parameter list. */
100139         function suspendLexicalEnvironment() {
100140             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
100141             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
100142             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
100143             lexicalEnvironmentSuspended = true;
100144         }
100145         /** Resumes a suspended lexical environment, usually before visiting a function body. */
100146         function resumeLexicalEnvironment() {
100147             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
100148             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
100149             ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
100150             lexicalEnvironmentSuspended = false;
100151         }
100152         /**
100153          * Ends a lexical environment. The previous set of hoisted declarations are restored and
100154          * any hoisted declarations added in this environment are returned.
100155          */
100156         function endLexicalEnvironment() {
100157             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
100158             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
100159             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
100160             var statements;
100161             if (lexicalEnvironmentVariableDeclarations ||
100162                 lexicalEnvironmentFunctionDeclarations ||
100163                 lexicalEnvironmentStatements) {
100164                 if (lexicalEnvironmentFunctionDeclarations) {
100165                     statements = __spreadArray([], lexicalEnvironmentFunctionDeclarations);
100166                 }
100167                 if (lexicalEnvironmentVariableDeclarations) {
100168                     var statement = factory.createVariableStatement(
100169                     /*modifiers*/ undefined, factory.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations));
100170                     ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
100171                     if (!statements) {
100172                         statements = [statement];
100173                     }
100174                     else {
100175                         statements.push(statement);
100176                     }
100177                 }
100178                 if (lexicalEnvironmentStatements) {
100179                     if (!statements) {
100180                         statements = __spreadArray([], lexicalEnvironmentStatements);
100181                     }
100182                     else {
100183                         statements = __spreadArray(__spreadArray([], statements), lexicalEnvironmentStatements);
100184                     }
100185                 }
100186             }
100187             // Restore the previous lexical environment.
100188             lexicalEnvironmentStackOffset--;
100189             lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
100190             lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
100191             lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset];
100192             lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset];
100193             if (lexicalEnvironmentStackOffset === 0) {
100194                 lexicalEnvironmentVariableDeclarationsStack = [];
100195                 lexicalEnvironmentFunctionDeclarationsStack = [];
100196                 lexicalEnvironmentStatementsStack = [];
100197                 lexicalEnvironmentFlagsStack = [];
100198             }
100199             return statements;
100200         }
100201         function setLexicalEnvironmentFlags(flags, value) {
100202             lexicalEnvironmentFlags = value ?
100203                 lexicalEnvironmentFlags | flags :
100204                 lexicalEnvironmentFlags & ~flags;
100205         }
100206         function getLexicalEnvironmentFlags() {
100207             return lexicalEnvironmentFlags;
100208         }
100209         function requestEmitHelper(helper) {
100210             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
100211             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
100212             ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
100213             if (helper.dependencies) {
100214                 for (var _i = 0, _a = helper.dependencies; _i < _a.length; _i++) {
100215                     var h = _a[_i];
100216                     requestEmitHelper(h);
100217                 }
100218             }
100219             emitHelpers = ts.append(emitHelpers, helper);
100220         }
100221         function readEmitHelpers() {
100222             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
100223             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
100224             var helpers = emitHelpers;
100225             emitHelpers = undefined;
100226             return helpers;
100227         }
100228         function dispose() {
100229             if (state < 3 /* Disposed */) {
100230                 // Clean up emit nodes on parse tree
100231                 for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
100232                     var node = nodes_4[_i];
100233                     ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
100234                 }
100235                 // Release references to external entries for GC purposes.
100236                 lexicalEnvironmentVariableDeclarations = undefined;
100237                 lexicalEnvironmentVariableDeclarationsStack = undefined;
100238                 lexicalEnvironmentFunctionDeclarations = undefined;
100239                 lexicalEnvironmentFunctionDeclarationsStack = undefined;
100240                 onSubstituteNode = undefined;
100241                 onEmitNode = undefined;
100242                 emitHelpers = undefined;
100243                 // Prevent further use of the transformation result.
100244                 state = 3 /* Disposed */;
100245             }
100246         }
100247     }
100248     ts.transformNodes = transformNodes;
100249     ts.nullTransformationContext = {
100250         get factory() { return ts.factory; },
100251         enableEmitNotification: ts.noop,
100252         enableSubstitution: ts.noop,
100253         endLexicalEnvironment: ts.returnUndefined,
100254         getCompilerOptions: function () { return ({}); },
100255         getEmitHost: ts.notImplemented,
100256         getEmitResolver: ts.notImplemented,
100257         getEmitHelperFactory: ts.notImplemented,
100258         setLexicalEnvironmentFlags: ts.noop,
100259         getLexicalEnvironmentFlags: function () { return 0; },
100260         hoistFunctionDeclaration: ts.noop,
100261         hoistVariableDeclaration: ts.noop,
100262         addInitializationStatement: ts.noop,
100263         isEmitNotificationEnabled: ts.notImplemented,
100264         isSubstitutionEnabled: ts.notImplemented,
100265         onEmitNode: ts.noop,
100266         onSubstituteNode: ts.notImplemented,
100267         readEmitHelpers: ts.notImplemented,
100268         requestEmitHelper: ts.noop,
100269         resumeLexicalEnvironment: ts.noop,
100270         startLexicalEnvironment: ts.noop,
100271         suspendLexicalEnvironment: ts.noop,
100272         addDiagnostic: ts.noop,
100273     };
100274 })(ts || (ts = {}));
100275 var ts;
100276 (function (ts) {
100277     var brackets = createBracketsMap();
100278     var syntheticParent = { pos: -1, end: -1 };
100279     /*@internal*/
100280     function isBuildInfoFile(file) {
100281         return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
100282     }
100283     ts.isBuildInfoFile = isBuildInfoFile;
100284     /*@internal*/
100285     /**
100286      * Iterates over the source files that are expected to have an emit output.
100287      *
100288      * @param host An EmitHost.
100289      * @param action The action to execute.
100290      * @param sourceFilesOrTargetSourceFile
100291      *   If an array, the full list of source files to emit.
100292      *   Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
100293      */
100294     function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit, onlyBuildInfo, includeBuildInfo) {
100295         if (forceDtsEmit === void 0) { forceDtsEmit = false; }
100296         var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit);
100297         var options = host.getCompilerOptions();
100298         if (ts.outFile(options)) {
100299             var prepends = host.getPrependNodes();
100300             if (sourceFiles.length || prepends.length) {
100301                 var bundle = ts.factory.createBundle(sourceFiles, prepends);
100302                 var result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle);
100303                 if (result) {
100304                     return result;
100305                 }
100306             }
100307         }
100308         else {
100309             if (!onlyBuildInfo) {
100310                 for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
100311                     var sourceFile = sourceFiles_1[_a];
100312                     var result = action(getOutputPathsFor(sourceFile, host, forceDtsEmit), sourceFile);
100313                     if (result) {
100314                         return result;
100315                     }
100316                 }
100317             }
100318             if (includeBuildInfo) {
100319                 var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
100320                 if (buildInfoPath)
100321                     return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
100322             }
100323         }
100324     }
100325     ts.forEachEmittedFile = forEachEmittedFile;
100326     function getTsBuildInfoEmitOutputFilePath(options) {
100327         var configFile = options.configFilePath;
100328         if (!ts.isIncrementalCompilation(options))
100329             return undefined;
100330         if (options.tsBuildInfoFile)
100331             return options.tsBuildInfoFile;
100332         var outPath = ts.outFile(options);
100333         var buildInfoExtensionLess;
100334         if (outPath) {
100335             buildInfoExtensionLess = ts.removeFileExtension(outPath);
100336         }
100337         else {
100338             if (!configFile)
100339                 return undefined;
100340             var configFileExtensionLess = ts.removeFileExtension(configFile);
100341             buildInfoExtensionLess = options.outDir ?
100342                 options.rootDir ?
100343                     ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
100344                     ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
100345                 configFileExtensionLess;
100346         }
100347         return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
100348     }
100349     ts.getTsBuildInfoEmitOutputFilePath = getTsBuildInfoEmitOutputFilePath;
100350     /*@internal*/
100351     function getOutputPathsForBundle(options, forceDtsPaths) {
100352         var outPath = ts.outFile(options);
100353         var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
100354         var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
100355         var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
100356         var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
100357         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
100358         return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
100359     }
100360     ts.getOutputPathsForBundle = getOutputPathsForBundle;
100361     /*@internal*/
100362     function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
100363         var options = host.getCompilerOptions();
100364         if (sourceFile.kind === 298 /* Bundle */) {
100365             return getOutputPathsForBundle(options, forceDtsPaths);
100366         }
100367         else {
100368             var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
100369             var isJsonFile = ts.isJsonSourceFile(sourceFile);
100370             // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it
100371             var isJsonEmittedToSameLocation = isJsonFile &&
100372                 ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
100373             var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath;
100374             var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
100375             var declarationFilePath = (forceDtsPaths || (ts.getEmitDeclarations(options) && !isJsonFile)) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
100376             var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
100377             return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
100378         }
100379     }
100380     ts.getOutputPathsFor = getOutputPathsFor;
100381     function getSourceMapFilePath(jsFilePath, options) {
100382         return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
100383     }
100384     // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
100385     // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
100386     // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
100387     /* @internal */
100388     function getOutputExtension(sourceFile, options) {
100389         if (ts.isJsonSourceFile(sourceFile)) {
100390             return ".json" /* Json */;
100391         }
100392         if (options.jsx === 1 /* Preserve */) {
100393             if (ts.isSourceFileJS(sourceFile)) {
100394                 if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
100395                     return ".jsx" /* Jsx */;
100396                 }
100397             }
100398             else if (sourceFile.languageVariant === 1 /* JSX */) {
100399                 // TypeScript source file preserving JSX syntax
100400                 return ".jsx" /* Jsx */;
100401             }
100402         }
100403         return ".js" /* Js */;
100404     }
100405     ts.getOutputExtension = getOutputExtension;
100406     function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir, getCommonSourceDirectory) {
100407         return outputDir ?
100408             ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(getCommonSourceDirectory ? getCommonSourceDirectory() : getCommonSourceDirectoryOfConfig(configFile, ignoreCase), inputFileName, ignoreCase)) :
100409             inputFileName;
100410     }
100411     /* @internal */
100412     function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory) {
100413         ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */));
100414         return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir, getCommonSourceDirectory), ".d.ts" /* Dts */);
100415     }
100416     ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
100417     function getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory) {
100418         if (configFile.options.emitDeclarationOnly)
100419             return undefined;
100420         var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
100421         var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir, getCommonSourceDirectory), isJsonFile ?
100422             ".json" /* Json */ :
100423             configFile.options.jsx === 1 /* Preserve */ && (ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) || ts.fileExtensionIs(inputFileName, ".jsx" /* Jsx */)) ?
100424                 ".jsx" /* Jsx */ :
100425                 ".js" /* Js */);
100426         return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
100427             outputFileName :
100428             undefined;
100429     }
100430     function createAddOutput() {
100431         var outputs;
100432         return { addOutput: addOutput, getOutputs: getOutputs };
100433         function addOutput(path) {
100434             if (path) {
100435                 (outputs || (outputs = [])).push(path);
100436             }
100437         }
100438         function getOutputs() {
100439             return outputs || ts.emptyArray;
100440         }
100441     }
100442     function getSingleOutputFileNames(configFile, addOutput) {
100443         var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
100444         addOutput(jsFilePath);
100445         addOutput(sourceMapFilePath);
100446         addOutput(declarationFilePath);
100447         addOutput(declarationMapPath);
100448         addOutput(buildInfoPath);
100449     }
100450     function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput, getCommonSourceDirectory) {
100451         if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
100452             return;
100453         var js = getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory);
100454         addOutput(js);
100455         if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
100456             return;
100457         if (js && configFile.options.sourceMap) {
100458             addOutput(js + ".map");
100459         }
100460         if (ts.getEmitDeclarations(configFile.options)) {
100461             var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory);
100462             addOutput(dts);
100463             if (configFile.options.declarationMap) {
100464                 addOutput(dts + ".map");
100465             }
100466         }
100467     }
100468     /*@internal*/
100469     function getCommonSourceDirectory(options, emittedFiles, currentDirectory, getCanonicalFileName, checkSourceFilesBelongToPath) {
100470         var commonSourceDirectory;
100471         if (options.rootDir) {
100472             // If a rootDir is specified use it as the commonSourceDirectory
100473             commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
100474             checkSourceFilesBelongToPath === null || checkSourceFilesBelongToPath === void 0 ? void 0 : checkSourceFilesBelongToPath(options.rootDir);
100475         }
100476         else if (options.composite && options.configFilePath) {
100477             // Project compilations never infer their root from the input source paths
100478             commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
100479             checkSourceFilesBelongToPath === null || checkSourceFilesBelongToPath === void 0 ? void 0 : checkSourceFilesBelongToPath(commonSourceDirectory);
100480         }
100481         else {
100482             commonSourceDirectory = ts.computeCommonSourceDirectoryOfFilenames(emittedFiles(), currentDirectory, getCanonicalFileName);
100483         }
100484         if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
100485             // Make sure directory path ends with directory separator so this string can directly
100486             // used to replace with "" to get the relative path of the source file and the relative path doesn't
100487             // start with / making it rooted path
100488             commonSourceDirectory += ts.directorySeparator;
100489         }
100490         return commonSourceDirectory;
100491     }
100492     ts.getCommonSourceDirectory = getCommonSourceDirectory;
100493     /*@internal*/
100494     function getCommonSourceDirectoryOfConfig(_a, ignoreCase) {
100495         var options = _a.options, fileNames = _a.fileNames;
100496         return getCommonSourceDirectory(options, function () { return ts.filter(fileNames, function (file) { return !(options.noEmitForJsFiles && ts.fileExtensionIsOneOf(file, ts.supportedJSExtensions)) && !ts.fileExtensionIs(file, ".d.ts" /* Dts */); }); }, ts.getDirectoryPath(ts.normalizeSlashes(ts.Debug.checkDefined(options.configFilePath))), ts.createGetCanonicalFileName(!ignoreCase));
100497     }
100498     ts.getCommonSourceDirectoryOfConfig = getCommonSourceDirectoryOfConfig;
100499     /*@internal*/
100500     function getAllProjectOutputs(configFile, ignoreCase) {
100501         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
100502         if (ts.outFile(configFile.options)) {
100503             getSingleOutputFileNames(configFile, addOutput);
100504         }
100505         else {
100506             var getCommonSourceDirectory_1 = ts.memoize(function () { return getCommonSourceDirectoryOfConfig(configFile, ignoreCase); });
100507             for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
100508                 var inputFileName = _c[_b];
100509                 getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput, getCommonSourceDirectory_1);
100510             }
100511             addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options));
100512         }
100513         return getOutputs();
100514     }
100515     ts.getAllProjectOutputs = getAllProjectOutputs;
100516     function getOutputFileNames(commandLine, inputFileName, ignoreCase) {
100517         inputFileName = ts.normalizePath(inputFileName);
100518         ts.Debug.assert(ts.contains(commandLine.fileNames, inputFileName), "Expected fileName to be present in command line");
100519         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
100520         if (ts.outFile(commandLine.options)) {
100521             getSingleOutputFileNames(commandLine, addOutput);
100522         }
100523         else {
100524             getOwnOutputFileNames(commandLine, inputFileName, ignoreCase, addOutput);
100525         }
100526         return getOutputs();
100527     }
100528     ts.getOutputFileNames = getOutputFileNames;
100529     /*@internal*/
100530     function getFirstProjectOutput(configFile, ignoreCase) {
100531         if (ts.outFile(configFile.options)) {
100532             var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
100533             return ts.Debug.checkDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
100534         }
100535         var getCommonSourceDirectory = ts.memoize(function () { return getCommonSourceDirectoryOfConfig(configFile, ignoreCase); });
100536         for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
100537             var inputFileName = _b[_a];
100538             if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
100539                 continue;
100540             var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory);
100541             if (jsFilePath)
100542                 return jsFilePath;
100543             if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
100544                 continue;
100545             if (ts.getEmitDeclarations(configFile.options)) {
100546                 return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase, getCommonSourceDirectory);
100547             }
100548         }
100549         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options);
100550         if (buildInfoPath)
100551             return buildInfoPath;
100552         return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
100553     }
100554     ts.getFirstProjectOutput = getFirstProjectOutput;
100555     /*@internal*/
100556     // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
100557     function emitFiles(resolver, host, targetSourceFile, _a, emitOnlyDtsFiles, onlyBuildInfo, forceDtsEmit) {
100558         var scriptTransformers = _a.scriptTransformers, declarationTransformers = _a.declarationTransformers;
100559         var compilerOptions = host.getCompilerOptions();
100560         var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
100561         var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
100562         var emitterDiagnostics = ts.createDiagnosticCollection();
100563         var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
100564         var writer = ts.createTextWriter(newLine);
100565         var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit;
100566         var bundleBuildInfo;
100567         var emitSkipped = false;
100568         var exportedModulesFromDeclarationEmit;
100569         // Emit each output file
100570         enter();
100571         forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile);
100572         exit();
100573         return {
100574             emitSkipped: emitSkipped,
100575             diagnostics: emitterDiagnostics.getDiagnostics(),
100576             emittedFiles: emittedFilesList,
100577             sourceMaps: sourceMapDataList,
100578             exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
100579         };
100580         function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
100581             var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
100582             var buildInfoDirectory;
100583             if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
100584                 buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
100585                 bundleBuildInfo = {
100586                     commonSourceDirectory: relativeToBuildInfo(host.getCommonSourceDirectory()),
100587                     sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); })
100588                 };
100589             }
100590             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath });
100591             emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo);
100592             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
100593             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath });
100594             emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo);
100595             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
100596             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath });
100597             emitBuildInfo(bundleBuildInfo, buildInfoPath);
100598             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
100599             if (!emitSkipped && emittedFilesList) {
100600                 if (!emitOnlyDtsFiles) {
100601                     if (jsFilePath) {
100602                         emittedFilesList.push(jsFilePath);
100603                     }
100604                     if (sourceMapFilePath) {
100605                         emittedFilesList.push(sourceMapFilePath);
100606                     }
100607                     if (buildInfoPath) {
100608                         emittedFilesList.push(buildInfoPath);
100609                     }
100610                 }
100611                 if (declarationFilePath) {
100612                     emittedFilesList.push(declarationFilePath);
100613                 }
100614                 if (declarationMapPath) {
100615                     emittedFilesList.push(declarationMapPath);
100616                 }
100617             }
100618             function relativeToBuildInfo(path) {
100619                 return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, host.getCanonicalFileName));
100620             }
100621         }
100622         function emitBuildInfo(bundle, buildInfoPath) {
100623             // Write build information if applicable
100624             if (!buildInfoPath || targetSourceFile || emitSkipped)
100625                 return;
100626             var program = host.getProgramBuildInfo();
100627             if (host.isEmitBlocked(buildInfoPath)) {
100628                 emitSkipped = true;
100629                 return;
100630             }
100631             var version = ts.version; // Extracted into a const so the form is stable between namespace and module
100632             ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false);
100633         }
100634         function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) {
100635             if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
100636                 return;
100637             }
100638             // Make sure not to write js file and source map file if any of them cannot be written
100639             if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
100640                 emitSkipped = true;
100641                 return;
100642             }
100643             // Transform the source files
100644             var transform = ts.transformNodes(resolver, host, ts.factory, compilerOptions, [sourceFileOrBundle], scriptTransformers, /*allowDtsFiles*/ false);
100645             var printerOptions = {
100646                 removeComments: compilerOptions.removeComments,
100647                 newLine: compilerOptions.newLine,
100648                 noEmitHelpers: compilerOptions.noEmitHelpers,
100649                 module: compilerOptions.module,
100650                 target: compilerOptions.target,
100651                 sourceMap: compilerOptions.sourceMap,
100652                 inlineSourceMap: compilerOptions.inlineSourceMap,
100653                 inlineSources: compilerOptions.inlineSources,
100654                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
100655                 writeBundleFileInfo: !!bundleBuildInfo,
100656                 relativeToBuildInfo: relativeToBuildInfo
100657             };
100658             // Create a printer to print the nodes
100659             var printer = createPrinter(printerOptions, {
100660                 // resolver hooks
100661                 hasGlobalName: resolver.hasGlobalName,
100662                 // transform hooks
100663                 onEmitNode: transform.emitNodeWithNotification,
100664                 isEmitNotificationEnabled: transform.isEmitNotificationEnabled,
100665                 substituteNode: transform.substituteNode,
100666             });
100667             ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
100668             printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
100669             // Clean up emit nodes on parse tree
100670             transform.dispose();
100671             if (bundleBuildInfo)
100672                 bundleBuildInfo.js = printer.bundleFileInfo;
100673         }
100674         function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) {
100675             if (!sourceFileOrBundle)
100676                 return;
100677             if (!declarationFilePath) {
100678                 if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly)
100679                     emitSkipped = true;
100680                 return;
100681             }
100682             var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
100683             var filesForEmit = forceDtsEmit ? sourceFiles : ts.filter(sourceFiles, ts.isSourceFileNotJson);
100684             // Setup and perform the transformation to retrieve declarations from the input files
100685             var inputListOrBundle = ts.outFile(compilerOptions) ? [ts.factory.createBundle(filesForEmit, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : filesForEmit;
100686             if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) {
100687                 // Checker wont collect the linked aliases since thats only done when declaration is enabled.
100688                 // Do that here when emitting only dts files
100689                 filesForEmit.forEach(collectLinkedAliases);
100690             }
100691             var declarationTransform = ts.transformNodes(resolver, host, ts.factory, compilerOptions, inputListOrBundle, declarationTransformers, /*allowDtsFiles*/ false);
100692             if (ts.length(declarationTransform.diagnostics)) {
100693                 for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
100694                     var diagnostic = _b[_a];
100695                     emitterDiagnostics.add(diagnostic);
100696                 }
100697             }
100698             var printerOptions = {
100699                 removeComments: compilerOptions.removeComments,
100700                 newLine: compilerOptions.newLine,
100701                 noEmitHelpers: true,
100702                 module: compilerOptions.module,
100703                 target: compilerOptions.target,
100704                 sourceMap: compilerOptions.sourceMap,
100705                 inlineSourceMap: compilerOptions.inlineSourceMap,
100706                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
100707                 onlyPrintJsDocStyle: true,
100708                 writeBundleFileInfo: !!bundleBuildInfo,
100709                 recordInternalSection: !!bundleBuildInfo,
100710                 relativeToBuildInfo: relativeToBuildInfo
100711             };
100712             var declarationPrinter = createPrinter(printerOptions, {
100713                 // resolver hooks
100714                 hasGlobalName: resolver.hasGlobalName,
100715                 // transform hooks
100716                 onEmitNode: declarationTransform.emitNodeWithNotification,
100717                 isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled,
100718                 substituteNode: declarationTransform.substituteNode,
100719             });
100720             var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
100721             emitSkipped = emitSkipped || declBlocked;
100722             if (!declBlocked || forceDtsEmit) {
100723                 ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
100724                 printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
100725                     sourceMap: compilerOptions.declarationMap,
100726                     sourceRoot: compilerOptions.sourceRoot,
100727                     mapRoot: compilerOptions.mapRoot,
100728                     extendedDiagnostics: compilerOptions.extendedDiagnostics,
100729                     // Explicitly do not passthru either `inline` option
100730                 });
100731                 if (forceDtsEmit && declarationTransform.transformed[0].kind === 297 /* SourceFile */) {
100732                     var sourceFile = declarationTransform.transformed[0];
100733                     exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
100734                 }
100735             }
100736             declarationTransform.dispose();
100737             if (bundleBuildInfo)
100738                 bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
100739         }
100740         function collectLinkedAliases(node) {
100741             if (ts.isExportAssignment(node)) {
100742                 if (node.expression.kind === 78 /* Identifier */) {
100743                     resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true);
100744                 }
100745                 return;
100746             }
100747             else if (ts.isExportSpecifier(node)) {
100748                 resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
100749                 return;
100750             }
100751             ts.forEachChild(node, collectLinkedAliases);
100752         }
100753         function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
100754             var bundle = sourceFileOrBundle.kind === 298 /* Bundle */ ? sourceFileOrBundle : undefined;
100755             var sourceFile = sourceFileOrBundle.kind === 297 /* SourceFile */ ? sourceFileOrBundle : undefined;
100756             var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
100757             var sourceMapGenerator;
100758             if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
100759                 sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
100760             }
100761             if (bundle) {
100762                 printer.writeBundle(bundle, writer, sourceMapGenerator);
100763             }
100764             else {
100765                 printer.writeFile(sourceFile, writer, sourceMapGenerator);
100766             }
100767             if (sourceMapGenerator) {
100768                 if (sourceMapDataList) {
100769                     sourceMapDataList.push({
100770                         inputSourceFileNames: sourceMapGenerator.getSources(),
100771                         sourceMap: sourceMapGenerator.toJSON()
100772                     });
100773                 }
100774                 var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile);
100775                 if (sourceMappingURL) {
100776                     if (!writer.isAtStartOfLine())
100777                         writer.rawWrite(newLine);
100778                     writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment
100779                 }
100780                 // Write the source map
100781                 if (sourceMapFilePath) {
100782                     var sourceMap = sourceMapGenerator.toString();
100783                     ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles);
100784                 }
100785             }
100786             else {
100787                 writer.writeLine();
100788             }
100789             // Write the output file
100790             ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
100791             // Reset state
100792             writer.clear();
100793         }
100794         function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
100795             return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
100796                 && (sourceFileOrBundle.kind !== 297 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
100797         }
100798         function getSourceRoot(mapOptions) {
100799             // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
100800             // relative paths of the sources list in the sourcemap
100801             var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || "");
100802             return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot;
100803         }
100804         function getSourceMapDirectory(mapOptions, filePath, sourceFile) {
100805             if (mapOptions.sourceRoot)
100806                 return host.getCommonSourceDirectory();
100807             if (mapOptions.mapRoot) {
100808                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
100809                 if (sourceFile) {
100810                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
100811                     // 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
100812                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
100813                 }
100814                 if (ts.getRootLength(sourceMapDir) === 0) {
100815                     // The relative paths are relative to the common directory
100816                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
100817                 }
100818                 return sourceMapDir;
100819             }
100820             return ts.getDirectoryPath(ts.normalizePath(filePath));
100821         }
100822         function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) {
100823             if (mapOptions.inlineSourceMap) {
100824                 // Encode the sourceMap into the sourceMap url
100825                 var sourceMapText = sourceMapGenerator.toString();
100826                 var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText);
100827                 return "data:application/json;base64," + base64SourceMapText;
100828             }
100829             var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.checkDefined(sourceMapFilePath)));
100830             if (mapOptions.mapRoot) {
100831                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
100832                 if (sourceFile) {
100833                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
100834                     // 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
100835                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
100836                 }
100837                 if (ts.getRootLength(sourceMapDir) === 0) {
100838                     // The relative paths are relative to the common directory
100839                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
100840                     return encodeURI(ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
100841                     ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap
100842                     host.getCurrentDirectory(), host.getCanonicalFileName, 
100843                     /*isAbsolutePathAnUrl*/ true));
100844                 }
100845                 else {
100846                     return encodeURI(ts.combinePaths(sourceMapDir, sourceMapFile));
100847                 }
100848             }
100849             return encodeURI(sourceMapFile);
100850         }
100851     }
100852     ts.emitFiles = emitFiles;
100853     /*@internal*/
100854     function getBuildInfoText(buildInfo) {
100855         return JSON.stringify(buildInfo, undefined, 2);
100856     }
100857     ts.getBuildInfoText = getBuildInfoText;
100858     /*@internal*/
100859     function getBuildInfo(buildInfoText) {
100860         return JSON.parse(buildInfoText);
100861     }
100862     ts.getBuildInfo = getBuildInfo;
100863     /*@internal*/
100864     ts.notImplementedResolver = {
100865         hasGlobalName: ts.notImplemented,
100866         getReferencedExportContainer: ts.notImplemented,
100867         getReferencedImportDeclaration: ts.notImplemented,
100868         getReferencedDeclarationWithCollidingName: ts.notImplemented,
100869         isDeclarationWithCollidingName: ts.notImplemented,
100870         isValueAliasDeclaration: ts.notImplemented,
100871         isReferencedAliasDeclaration: ts.notImplemented,
100872         isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
100873         getNodeCheckFlags: ts.notImplemented,
100874         isDeclarationVisible: ts.notImplemented,
100875         isLateBound: function (_node) { return false; },
100876         collectLinkedAliases: ts.notImplemented,
100877         isImplementationOfOverload: ts.notImplemented,
100878         isRequiredInitializedParameter: ts.notImplemented,
100879         isOptionalUninitializedParameterProperty: ts.notImplemented,
100880         isExpandoFunctionDeclaration: ts.notImplemented,
100881         getPropertiesOfContainerFunction: ts.notImplemented,
100882         createTypeOfDeclaration: ts.notImplemented,
100883         createReturnTypeOfSignatureDeclaration: ts.notImplemented,
100884         createTypeOfExpression: ts.notImplemented,
100885         createLiteralConstValue: ts.notImplemented,
100886         isSymbolAccessible: ts.notImplemented,
100887         isEntityNameVisible: ts.notImplemented,
100888         // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
100889         getConstantValue: ts.notImplemented,
100890         getReferencedValueDeclaration: ts.notImplemented,
100891         getTypeReferenceSerializationKind: ts.notImplemented,
100892         isOptionalParameter: ts.notImplemented,
100893         moduleExportsSomeValue: ts.notImplemented,
100894         isArgumentsLocalBinding: ts.notImplemented,
100895         getExternalModuleFileFromDeclaration: ts.notImplemented,
100896         getTypeReferenceDirectivesForEntityName: ts.notImplemented,
100897         getTypeReferenceDirectivesForSymbol: ts.notImplemented,
100898         isLiteralConstDeclaration: ts.notImplemented,
100899         getJsxFactoryEntity: ts.notImplemented,
100900         getJsxFragmentFactoryEntity: ts.notImplemented,
100901         getAllAccessorDeclarations: ts.notImplemented,
100902         getSymbolOfExternalModuleSpecifier: ts.notImplemented,
100903         isBindingCapturedByNode: ts.notImplemented,
100904         getDeclarationStatementsForSourceFile: ts.notImplemented,
100905         isImportRequiredByAugmentation: ts.notImplemented,
100906     };
100907     function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) {
100908         var _a;
100909         var jsBundle = ts.Debug.checkDefined(bundle.js);
100910         var prologueMap = ((_a = jsBundle.sources) === null || _a === void 0 ? void 0 : _a.prologues) && ts.arrayToMap(jsBundle.sources.prologues, function (prologueInfo) { return prologueInfo.file; });
100911         return bundle.sourceFiles.map(function (fileName, index) {
100912             var _a, _b;
100913             var prologueInfo = prologueMap === null || prologueMap === void 0 ? void 0 : prologueMap.get(index);
100914             var statements = prologueInfo === null || prologueInfo === void 0 ? void 0 : prologueInfo.directives.map(function (directive) {
100915                 var literal = ts.setTextRange(ts.factory.createStringLiteral(directive.expression.text), directive.expression);
100916                 var statement = ts.setTextRange(ts.factory.createExpressionStatement(literal), directive);
100917                 ts.setParent(literal, statement);
100918                 return statement;
100919             });
100920             var eofToken = ts.factory.createToken(1 /* EndOfFileToken */);
100921             var sourceFile = ts.factory.createSourceFile(statements !== null && statements !== void 0 ? statements : [], eofToken, 0 /* None */);
100922             sourceFile.fileName = ts.getRelativePathFromDirectory(host.getCurrentDirectory(), ts.getNormalizedAbsolutePath(fileName, buildInfoDirectory), !host.useCaseSensitiveFileNames());
100923             sourceFile.text = (_a = prologueInfo === null || prologueInfo === void 0 ? void 0 : prologueInfo.text) !== null && _a !== void 0 ? _a : "";
100924             ts.setTextRangePosWidth(sourceFile, 0, (_b = prologueInfo === null || prologueInfo === void 0 ? void 0 : prologueInfo.text.length) !== null && _b !== void 0 ? _b : 0);
100925             ts.setEachParent(sourceFile.statements, sourceFile);
100926             ts.setTextRangePosWidth(eofToken, sourceFile.end, 0);
100927             ts.setParent(eofToken, sourceFile);
100928             return sourceFile;
100929         });
100930     }
100931     /*@internal*/
100932     function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) {
100933         var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
100934         var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath));
100935         if (!buildInfoText)
100936             return buildInfoPath;
100937         var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath));
100938         if (!jsFileText)
100939             return jsFilePath;
100940         var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
100941         // error if no source map or for now if inline sourcemap
100942         if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
100943             return sourceMapFilePath || "inline sourcemap decoding";
100944         // read declaration text
100945         var declarationText = declarationFilePath && host.readFile(declarationFilePath);
100946         if (declarationFilePath && !declarationText)
100947             return declarationFilePath;
100948         var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
100949         // error if no source map or for now if inline sourcemap
100950         if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
100951             return declarationMapPath || "inline sourcemap decoding";
100952         var buildInfo = getBuildInfo(buildInfoText);
100953         if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
100954             return buildInfoPath;
100955         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
100956         var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, 
100957         /*onlyOwnText*/ true);
100958         var outputFiles = [];
100959         var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
100960         var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host);
100961         var emitHost = {
100962             getPrependNodes: ts.memoize(function () { return __spreadArray(__spreadArray([], prependNodes), [ownPrependInput]); }),
100963             getCanonicalFileName: host.getCanonicalFileName,
100964             getCommonSourceDirectory: function () { return ts.getNormalizedAbsolutePath(buildInfo.bundle.commonSourceDirectory, buildInfoDirectory); },
100965             getCompilerOptions: function () { return config.options; },
100966             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
100967             getNewLine: function () { return host.getNewLine(); },
100968             getSourceFile: ts.returnUndefined,
100969             getSourceFileByPath: ts.returnUndefined,
100970             getSourceFiles: function () { return sourceFilesForJsEmit; },
100971             getLibFileFromReference: ts.notImplemented,
100972             isSourceFileFromExternalLibrary: ts.returnFalse,
100973             getResolvedProjectReferenceToRedirect: ts.returnUndefined,
100974             getProjectReferenceRedirect: ts.returnUndefined,
100975             isSourceOfProjectReferenceRedirect: ts.returnFalse,
100976             writeFile: function (name, text, writeByteOrderMark) {
100977                 switch (name) {
100978                     case jsFilePath:
100979                         if (jsFileText === text)
100980                             return;
100981                         break;
100982                     case sourceMapFilePath:
100983                         if (sourceMapText === text)
100984                             return;
100985                         break;
100986                     case buildInfoPath:
100987                         var newBuildInfo = getBuildInfo(text);
100988                         newBuildInfo.program = buildInfo.program;
100989                         // Update sourceFileInfo
100990                         var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
100991                         newBuildInfo.bundle.js.sources = js.sources;
100992                         if (dts) {
100993                             newBuildInfo.bundle.dts.sources = dts.sources;
100994                         }
100995                         newBuildInfo.bundle.sourceFiles = sourceFiles;
100996                         outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
100997                         return;
100998                     case declarationFilePath:
100999                         if (declarationText === text)
101000                             return;
101001                         break;
101002                     case declarationMapPath:
101003                         if (declarationMapText === text)
101004                             return;
101005                         break;
101006                     default:
101007                         ts.Debug.fail("Unexpected path: " + name);
101008                 }
101009                 outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
101010             },
101011             isEmitBlocked: ts.returnFalse,
101012             readFile: function (f) { return host.readFile(f); },
101013             fileExists: function (f) { return host.fileExists(f); },
101014             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
101015             getProgramBuildInfo: ts.returnUndefined,
101016             getSourceFileFromReference: ts.returnUndefined,
101017             redirectTargetsMap: ts.createMultiMap(),
101018             getFileIncludeReasons: ts.notImplemented,
101019         };
101020         emitFiles(ts.notImplementedResolver, emitHost, 
101021         /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers));
101022         return outputFiles;
101023     }
101024     ts.emitUsingBuildInfo = emitUsingBuildInfo;
101025     var PipelinePhase;
101026     (function (PipelinePhase) {
101027         PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
101028         PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution";
101029         PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments";
101030         PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps";
101031         PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit";
101032     })(PipelinePhase || (PipelinePhase = {}));
101033     function createPrinter(printerOptions, handlers) {
101034         if (printerOptions === void 0) { printerOptions = {}; }
101035         if (handlers === void 0) { handlers = {}; }
101036         var hasGlobalName = handlers.hasGlobalName, _a = handlers.onEmitNode, onEmitNode = _a === void 0 ? ts.noEmitNotification : _a, isEmitNotificationEnabled = handlers.isEmitNotificationEnabled, _b = handlers.substituteNode, substituteNode = _b === void 0 ? ts.noEmitSubstitution : _b, onBeforeEmitNodeArray = handlers.onBeforeEmitNodeArray, onAfterEmitNodeArray = handlers.onAfterEmitNodeArray, onBeforeEmitToken = handlers.onBeforeEmitToken, onAfterEmitToken = handlers.onAfterEmitToken;
101037         var extendedDiagnostics = !!printerOptions.extendedDiagnostics;
101038         var newLine = ts.getNewLineCharacter(printerOptions);
101039         var moduleKind = ts.getEmitModuleKind(printerOptions);
101040         var bundledHelpers = new ts.Map();
101041         var currentSourceFile;
101042         var nodeIdToGeneratedName; // Map of generated names for specific nodes.
101043         var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
101044         var generatedNames; // Set of names generated by the NameGenerator.
101045         var tempFlagsStack; // Stack of enclosing name generation scopes.
101046         var tempFlags; // TempFlags for the current name generation scope.
101047         var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes.
101048         var reservedNames; // TempFlags to reserve in nested name generation scopes.
101049         var preserveSourceNewlines = printerOptions.preserveSourceNewlines; // Can be overridden inside nodes with the `IgnoreSourceNewlines` emit flag.
101050         var nextListElementPos; // See comment in `getLeadingLineTerminatorCount`.
101051         var writer;
101052         var ownWriter; // Reusable `EmitTextWriter` for basic printing.
101053         var write = writeBase;
101054         var isOwnFileEmit;
101055         var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
101056         var relativeToBuildInfo = bundleFileInfo ? ts.Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined;
101057         var recordInternalSection = printerOptions.recordInternalSection;
101058         var sourceFileTextPos = 0;
101059         var sourceFileTextKind = "text" /* Text */;
101060         // Source Maps
101061         var sourceMapsDisabled = true;
101062         var sourceMapGenerator;
101063         var sourceMapSource;
101064         var sourceMapSourceIndex = -1;
101065         var mostRecentlyAddedSourceMapSource;
101066         var mostRecentlyAddedSourceMapSourceIndex = -1;
101067         // Comments
101068         var containerPos = -1;
101069         var containerEnd = -1;
101070         var declarationListContainerEnd = -1;
101071         var currentLineMap;
101072         var detachedCommentsInfo;
101073         var hasWrittenComment = false;
101074         var commentsDisabled = !!printerOptions.removeComments;
101075         var lastNode;
101076         var lastSubstitution;
101077         var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit;
101078         reset();
101079         return {
101080             // public API
101081             printNode: printNode,
101082             printList: printList,
101083             printFile: printFile,
101084             printBundle: printBundle,
101085             // internal API
101086             writeNode: writeNode,
101087             writeList: writeList,
101088             writeFile: writeFile,
101089             writeBundle: writeBundle,
101090             bundleFileInfo: bundleFileInfo
101091         };
101092         function printNode(hint, node, sourceFile) {
101093             switch (hint) {
101094                 case 0 /* SourceFile */:
101095                     ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
101096                     break;
101097                 case 2 /* IdentifierName */:
101098                     ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
101099                     break;
101100                 case 1 /* Expression */:
101101                     ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
101102                     break;
101103             }
101104             switch (node.kind) {
101105                 case 297 /* SourceFile */: return printFile(node);
101106                 case 298 /* Bundle */: return printBundle(node);
101107                 case 299 /* UnparsedSource */: return printUnparsedSource(node);
101108             }
101109             writeNode(hint, node, sourceFile, beginPrint());
101110             return endPrint();
101111         }
101112         function printList(format, nodes, sourceFile) {
101113             writeList(format, nodes, sourceFile, beginPrint());
101114             return endPrint();
101115         }
101116         function printBundle(bundle) {
101117             writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
101118             return endPrint();
101119         }
101120         function printFile(sourceFile) {
101121             writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined);
101122             return endPrint();
101123         }
101124         function printUnparsedSource(unparsed) {
101125             writeUnparsedSource(unparsed, beginPrint());
101126             return endPrint();
101127         }
101128         function writeNode(hint, node, sourceFile, output) {
101129             var previousWriter = writer;
101130             setWriter(output, /*_sourceMapGenerator*/ undefined);
101131             print(hint, node, sourceFile);
101132             reset();
101133             writer = previousWriter;
101134         }
101135         function writeList(format, nodes, sourceFile, output) {
101136             var previousWriter = writer;
101137             setWriter(output, /*_sourceMapGenerator*/ undefined);
101138             if (sourceFile) {
101139                 setSourceFile(sourceFile);
101140             }
101141             emitList(syntheticParent, nodes, format);
101142             reset();
101143             writer = previousWriter;
101144         }
101145         function getTextPosWithWriteLine() {
101146             return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
101147         }
101148         function updateOrPushBundleFileTextLike(pos, end, kind) {
101149             var last = ts.lastOrUndefined(bundleFileInfo.sections);
101150             if (last && last.kind === kind) {
101151                 last.end = end;
101152             }
101153             else {
101154                 bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
101155             }
101156         }
101157         function recordBundleFileInternalSectionStart(node) {
101158             if (recordInternalSection &&
101159                 bundleFileInfo &&
101160                 currentSourceFile &&
101161                 (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
101162                 ts.isInternalDeclaration(node, currentSourceFile) &&
101163                 sourceFileTextKind !== "internal" /* Internal */) {
101164                 var prevSourceFileTextKind = sourceFileTextKind;
101165                 recordBundleFileTextLikeSection(writer.getTextPos());
101166                 sourceFileTextPos = getTextPosWithWriteLine();
101167                 sourceFileTextKind = "internal" /* Internal */;
101168                 return prevSourceFileTextKind;
101169             }
101170             return undefined;
101171         }
101172         function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
101173             if (prevSourceFileTextKind) {
101174                 recordBundleFileTextLikeSection(writer.getTextPos());
101175                 sourceFileTextPos = getTextPosWithWriteLine();
101176                 sourceFileTextKind = prevSourceFileTextKind;
101177             }
101178         }
101179         function recordBundleFileTextLikeSection(end) {
101180             if (sourceFileTextPos < end) {
101181                 updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
101182                 return true;
101183             }
101184             return false;
101185         }
101186         function writeBundle(bundle, output, sourceMapGenerator) {
101187             var _a;
101188             isOwnFileEmit = false;
101189             var previousWriter = writer;
101190             setWriter(output, sourceMapGenerator);
101191             emitShebangIfNeeded(bundle);
101192             emitPrologueDirectivesIfNeeded(bundle);
101193             emitHelpers(bundle);
101194             emitSyntheticTripleSlashReferencesIfNeeded(bundle);
101195             for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
101196                 var prepend = _c[_b];
101197                 writeLine();
101198                 var pos = writer.getTextPos();
101199                 var savedSections = bundleFileInfo && bundleFileInfo.sections;
101200                 if (savedSections)
101201                     bundleFileInfo.sections = [];
101202                 print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
101203                 if (bundleFileInfo) {
101204                     var newSections = bundleFileInfo.sections;
101205                     bundleFileInfo.sections = savedSections;
101206                     if (prepend.oldFileOfCurrentEmit)
101207                         (_a = bundleFileInfo.sections).push.apply(_a, newSections);
101208                     else {
101209                         newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
101210                         bundleFileInfo.sections.push({
101211                             pos: pos,
101212                             end: writer.getTextPos(),
101213                             kind: "prepend" /* Prepend */,
101214                             data: relativeToBuildInfo(prepend.fileName),
101215                             texts: newSections
101216                         });
101217                     }
101218                 }
101219             }
101220             sourceFileTextPos = getTextPosWithWriteLine();
101221             for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
101222                 var sourceFile = _e[_d];
101223                 print(0 /* SourceFile */, sourceFile, sourceFile);
101224             }
101225             if (bundleFileInfo && bundle.sourceFiles.length) {
101226                 var end = writer.getTextPos();
101227                 if (recordBundleFileTextLikeSection(end)) {
101228                     // Store prologues
101229                     var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
101230                     if (prologues) {
101231                         if (!bundleFileInfo.sources)
101232                             bundleFileInfo.sources = {};
101233                         bundleFileInfo.sources.prologues = prologues;
101234                     }
101235                     // Store helpes
101236                     var helpers = getHelpersFromBundledSourceFiles(bundle);
101237                     if (helpers) {
101238                         if (!bundleFileInfo.sources)
101239                             bundleFileInfo.sources = {};
101240                         bundleFileInfo.sources.helpers = helpers;
101241                     }
101242                 }
101243             }
101244             reset();
101245             writer = previousWriter;
101246         }
101247         function writeUnparsedSource(unparsed, output) {
101248             var previousWriter = writer;
101249             setWriter(output, /*_sourceMapGenerator*/ undefined);
101250             print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
101251             reset();
101252             writer = previousWriter;
101253         }
101254         function writeFile(sourceFile, output, sourceMapGenerator) {
101255             isOwnFileEmit = true;
101256             var previousWriter = writer;
101257             setWriter(output, sourceMapGenerator);
101258             emitShebangIfNeeded(sourceFile);
101259             emitPrologueDirectivesIfNeeded(sourceFile);
101260             print(0 /* SourceFile */, sourceFile, sourceFile);
101261             reset();
101262             writer = previousWriter;
101263         }
101264         function beginPrint() {
101265             return ownWriter || (ownWriter = ts.createTextWriter(newLine));
101266         }
101267         function endPrint() {
101268             var text = ownWriter.getText();
101269             ownWriter.clear();
101270             return text;
101271         }
101272         function print(hint, node, sourceFile) {
101273             if (sourceFile) {
101274                 setSourceFile(sourceFile);
101275             }
101276             pipelineEmit(hint, node);
101277         }
101278         function setSourceFile(sourceFile) {
101279             currentSourceFile = sourceFile;
101280             currentLineMap = undefined;
101281             detachedCommentsInfo = undefined;
101282             if (sourceFile) {
101283                 setSourceMapSource(sourceFile);
101284             }
101285         }
101286         function setWriter(_writer, _sourceMapGenerator) {
101287             if (_writer && printerOptions.omitTrailingSemicolon) {
101288                 _writer = ts.getTrailingSemicolonDeferringWriter(_writer);
101289             }
101290             writer = _writer; // TODO: GH#18217
101291             sourceMapGenerator = _sourceMapGenerator;
101292             sourceMapsDisabled = !writer || !sourceMapGenerator;
101293         }
101294         function reset() {
101295             nodeIdToGeneratedName = [];
101296             autoGeneratedIdToGeneratedName = [];
101297             generatedNames = new ts.Set();
101298             tempFlagsStack = [];
101299             tempFlags = 0 /* Auto */;
101300             reservedNamesStack = [];
101301             currentSourceFile = undefined;
101302             currentLineMap = undefined;
101303             detachedCommentsInfo = undefined;
101304             lastNode = undefined;
101305             lastSubstitution = undefined;
101306             setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined);
101307         }
101308         function getCurrentLineMap() {
101309             return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile));
101310         }
101311         function emit(node) {
101312             if (node === undefined)
101313                 return;
101314             var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
101315             var substitute = pipelineEmit(4 /* Unspecified */, node);
101316             recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
101317             return substitute;
101318         }
101319         function emitIdentifierName(node) {
101320             if (node === undefined)
101321                 return;
101322             return pipelineEmit(2 /* IdentifierName */, node);
101323         }
101324         function emitExpression(node) {
101325             if (node === undefined)
101326                 return;
101327             return pipelineEmit(1 /* Expression */, node);
101328         }
101329         function emitJsxAttributeValue(node) {
101330             return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node);
101331         }
101332         function pipelineEmit(emitHint, node) {
101333             var savedLastNode = lastNode;
101334             var savedLastSubstitution = lastSubstitution;
101335             var savedPreserveSourceNewlines = preserveSourceNewlines;
101336             lastNode = node;
101337             lastSubstitution = undefined;
101338             if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) {
101339                 preserveSourceNewlines = false;
101340             }
101341             var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node);
101342             pipelinePhase(emitHint, node);
101343             ts.Debug.assert(lastNode === node);
101344             var substitute = lastSubstitution;
101345             lastNode = savedLastNode;
101346             lastSubstitution = savedLastSubstitution;
101347             preserveSourceNewlines = savedPreserveSourceNewlines;
101348             return substitute || node;
101349         }
101350         function getPipelinePhase(phase, emitHint, node) {
101351             switch (phase) {
101352                 case 0 /* Notification */:
101353                     if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) {
101354                         return pipelineEmitWithNotification;
101355                     }
101356                 // falls through
101357                 case 1 /* Substitution */:
101358                     if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) {
101359                         return pipelineEmitWithSubstitution;
101360                     }
101361                 // falls through
101362                 case 2 /* Comments */:
101363                     if (!commentsDisabled && node.kind !== 297 /* SourceFile */) {
101364                         return pipelineEmitWithComments;
101365                     }
101366                 // falls through
101367                 case 3 /* SourceMaps */:
101368                     if (!sourceMapsDisabled && node.kind !== 297 /* SourceFile */ && !ts.isInJsonFile(node)) {
101369                         return pipelineEmitWithSourceMap;
101370                     }
101371                 // falls through
101372                 case 4 /* Emit */:
101373                     return pipelineEmitWithHint;
101374                 default:
101375                     return ts.Debug.assertNever(phase);
101376             }
101377         }
101378         function getNextPipelinePhase(currentPhase, emitHint, node) {
101379             return getPipelinePhase(currentPhase + 1, emitHint, node);
101380         }
101381         function pipelineEmitWithNotification(hint, node) {
101382             ts.Debug.assert(lastNode === node);
101383             var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node);
101384             onEmitNode(hint, node, pipelinePhase);
101385             ts.Debug.assert(lastNode === node);
101386         }
101387         function pipelineEmitWithHint(hint, node) {
101388             ts.Debug.assert(lastNode === node || lastSubstitution === node);
101389             if (hint === 0 /* SourceFile */)
101390                 return emitSourceFile(ts.cast(node, ts.isSourceFile));
101391             if (hint === 2 /* IdentifierName */)
101392                 return emitIdentifier(ts.cast(node, ts.isIdentifier));
101393             if (hint === 6 /* JsxAttributeValue */)
101394                 return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true);
101395             if (hint === 3 /* MappedTypeParameter */)
101396                 return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
101397             if (hint === 5 /* EmbeddedStatement */) {
101398                 ts.Debug.assertNode(node, ts.isEmptyStatement);
101399                 return emitEmptyStatement(/*isEmbeddedStatement*/ true);
101400             }
101401             if (hint === 4 /* Unspecified */) {
101402                 if (ts.isKeyword(node.kind))
101403                     return writeTokenNode(node, writeKeyword);
101404                 switch (node.kind) {
101405                     // Pseudo-literals
101406                     case 15 /* TemplateHead */:
101407                     case 16 /* TemplateMiddle */:
101408                     case 17 /* TemplateTail */:
101409                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
101410                     case 299 /* UnparsedSource */:
101411                     case 293 /* UnparsedPrepend */:
101412                         return emitUnparsedSourceOrPrepend(node);
101413                     case 292 /* UnparsedPrologue */:
101414                         return writeUnparsedNode(node);
101415                     case 294 /* UnparsedText */:
101416                     case 295 /* UnparsedInternalText */:
101417                         return emitUnparsedTextLike(node);
101418                     case 296 /* UnparsedSyntheticReference */:
101419                         return emitUnparsedSyntheticReference(node);
101420                     // Identifiers
101421                     case 78 /* Identifier */:
101422                         return emitIdentifier(node);
101423                     // PrivateIdentifiers
101424                     case 79 /* PrivateIdentifier */:
101425                         return emitPrivateIdentifier(node);
101426                     // Parse tree nodes
101427                     // Names
101428                     case 157 /* QualifiedName */:
101429                         return emitQualifiedName(node);
101430                     case 158 /* ComputedPropertyName */:
101431                         return emitComputedPropertyName(node);
101432                     // Signature elements
101433                     case 159 /* TypeParameter */:
101434                         return emitTypeParameter(node);
101435                     case 160 /* Parameter */:
101436                         return emitParameter(node);
101437                     case 161 /* Decorator */:
101438                         return emitDecorator(node);
101439                     // Type members
101440                     case 162 /* PropertySignature */:
101441                         return emitPropertySignature(node);
101442                     case 163 /* PropertyDeclaration */:
101443                         return emitPropertyDeclaration(node);
101444                     case 164 /* MethodSignature */:
101445                         return emitMethodSignature(node);
101446                     case 165 /* MethodDeclaration */:
101447                         return emitMethodDeclaration(node);
101448                     case 166 /* Constructor */:
101449                         return emitConstructor(node);
101450                     case 167 /* GetAccessor */:
101451                     case 168 /* SetAccessor */:
101452                         return emitAccessorDeclaration(node);
101453                     case 169 /* CallSignature */:
101454                         return emitCallSignature(node);
101455                     case 170 /* ConstructSignature */:
101456                         return emitConstructSignature(node);
101457                     case 171 /* IndexSignature */:
101458                         return emitIndexSignature(node);
101459                     case 194 /* TemplateLiteralTypeSpan */:
101460                         return emitTemplateTypeSpan(node);
101461                     // Types
101462                     case 172 /* TypePredicate */:
101463                         return emitTypePredicate(node);
101464                     case 173 /* TypeReference */:
101465                         return emitTypeReference(node);
101466                     case 174 /* FunctionType */:
101467                         return emitFunctionType(node);
101468                     case 308 /* JSDocFunctionType */:
101469                         return emitJSDocFunctionType(node);
101470                     case 175 /* ConstructorType */:
101471                         return emitConstructorType(node);
101472                     case 176 /* TypeQuery */:
101473                         return emitTypeQuery(node);
101474                     case 177 /* TypeLiteral */:
101475                         return emitTypeLiteral(node);
101476                     case 178 /* ArrayType */:
101477                         return emitArrayType(node);
101478                     case 179 /* TupleType */:
101479                         return emitTupleType(node);
101480                     case 180 /* OptionalType */:
101481                         return emitOptionalType(node);
101482                     case 182 /* UnionType */:
101483                         return emitUnionType(node);
101484                     case 183 /* IntersectionType */:
101485                         return emitIntersectionType(node);
101486                     case 184 /* ConditionalType */:
101487                         return emitConditionalType(node);
101488                     case 185 /* InferType */:
101489                         return emitInferType(node);
101490                     case 186 /* ParenthesizedType */:
101491                         return emitParenthesizedType(node);
101492                     case 223 /* ExpressionWithTypeArguments */:
101493                         return emitExpressionWithTypeArguments(node);
101494                     case 187 /* ThisType */:
101495                         return emitThisType();
101496                     case 188 /* TypeOperator */:
101497                         return emitTypeOperator(node);
101498                     case 189 /* IndexedAccessType */:
101499                         return emitIndexedAccessType(node);
101500                     case 190 /* MappedType */:
101501                         return emitMappedType(node);
101502                     case 191 /* LiteralType */:
101503                         return emitLiteralType(node);
101504                     case 193 /* TemplateLiteralType */:
101505                         return emitTemplateType(node);
101506                     case 195 /* ImportType */:
101507                         return emitImportTypeNode(node);
101508                     case 303 /* JSDocAllType */:
101509                         writePunctuation("*");
101510                         return;
101511                     case 304 /* JSDocUnknownType */:
101512                         writePunctuation("?");
101513                         return;
101514                     case 305 /* JSDocNullableType */:
101515                         return emitJSDocNullableType(node);
101516                     case 306 /* JSDocNonNullableType */:
101517                         return emitJSDocNonNullableType(node);
101518                     case 307 /* JSDocOptionalType */:
101519                         return emitJSDocOptionalType(node);
101520                     case 181 /* RestType */:
101521                     case 309 /* JSDocVariadicType */:
101522                         return emitRestOrJSDocVariadicType(node);
101523                     case 192 /* NamedTupleMember */:
101524                         return emitNamedTupleMember(node);
101525                     // Binding patterns
101526                     case 196 /* ObjectBindingPattern */:
101527                         return emitObjectBindingPattern(node);
101528                     case 197 /* ArrayBindingPattern */:
101529                         return emitArrayBindingPattern(node);
101530                     case 198 /* BindingElement */:
101531                         return emitBindingElement(node);
101532                     // Misc
101533                     case 228 /* TemplateSpan */:
101534                         return emitTemplateSpan(node);
101535                     case 229 /* SemicolonClassElement */:
101536                         return emitSemicolonClassElement();
101537                     // Statements
101538                     case 230 /* Block */:
101539                         return emitBlock(node);
101540                     case 232 /* VariableStatement */:
101541                         return emitVariableStatement(node);
101542                     case 231 /* EmptyStatement */:
101543                         return emitEmptyStatement(/*isEmbeddedStatement*/ false);
101544                     case 233 /* ExpressionStatement */:
101545                         return emitExpressionStatement(node);
101546                     case 234 /* IfStatement */:
101547                         return emitIfStatement(node);
101548                     case 235 /* DoStatement */:
101549                         return emitDoStatement(node);
101550                     case 236 /* WhileStatement */:
101551                         return emitWhileStatement(node);
101552                     case 237 /* ForStatement */:
101553                         return emitForStatement(node);
101554                     case 238 /* ForInStatement */:
101555                         return emitForInStatement(node);
101556                     case 239 /* ForOfStatement */:
101557                         return emitForOfStatement(node);
101558                     case 240 /* ContinueStatement */:
101559                         return emitContinueStatement(node);
101560                     case 241 /* BreakStatement */:
101561                         return emitBreakStatement(node);
101562                     case 242 /* ReturnStatement */:
101563                         return emitReturnStatement(node);
101564                     case 243 /* WithStatement */:
101565                         return emitWithStatement(node);
101566                     case 244 /* SwitchStatement */:
101567                         return emitSwitchStatement(node);
101568                     case 245 /* LabeledStatement */:
101569                         return emitLabeledStatement(node);
101570                     case 246 /* ThrowStatement */:
101571                         return emitThrowStatement(node);
101572                     case 247 /* TryStatement */:
101573                         return emitTryStatement(node);
101574                     case 248 /* DebuggerStatement */:
101575                         return emitDebuggerStatement(node);
101576                     // Declarations
101577                     case 249 /* VariableDeclaration */:
101578                         return emitVariableDeclaration(node);
101579                     case 250 /* VariableDeclarationList */:
101580                         return emitVariableDeclarationList(node);
101581                     case 251 /* FunctionDeclaration */:
101582                         return emitFunctionDeclaration(node);
101583                     case 252 /* ClassDeclaration */:
101584                         return emitClassDeclaration(node);
101585                     case 253 /* InterfaceDeclaration */:
101586                         return emitInterfaceDeclaration(node);
101587                     case 254 /* TypeAliasDeclaration */:
101588                         return emitTypeAliasDeclaration(node);
101589                     case 255 /* EnumDeclaration */:
101590                         return emitEnumDeclaration(node);
101591                     case 256 /* ModuleDeclaration */:
101592                         return emitModuleDeclaration(node);
101593                     case 257 /* ModuleBlock */:
101594                         return emitModuleBlock(node);
101595                     case 258 /* CaseBlock */:
101596                         return emitCaseBlock(node);
101597                     case 259 /* NamespaceExportDeclaration */:
101598                         return emitNamespaceExportDeclaration(node);
101599                     case 260 /* ImportEqualsDeclaration */:
101600                         return emitImportEqualsDeclaration(node);
101601                     case 261 /* ImportDeclaration */:
101602                         return emitImportDeclaration(node);
101603                     case 262 /* ImportClause */:
101604                         return emitImportClause(node);
101605                     case 263 /* NamespaceImport */:
101606                         return emitNamespaceImport(node);
101607                     case 269 /* NamespaceExport */:
101608                         return emitNamespaceExport(node);
101609                     case 264 /* NamedImports */:
101610                         return emitNamedImports(node);
101611                     case 265 /* ImportSpecifier */:
101612                         return emitImportSpecifier(node);
101613                     case 266 /* ExportAssignment */:
101614                         return emitExportAssignment(node);
101615                     case 267 /* ExportDeclaration */:
101616                         return emitExportDeclaration(node);
101617                     case 268 /* NamedExports */:
101618                         return emitNamedExports(node);
101619                     case 270 /* ExportSpecifier */:
101620                         return emitExportSpecifier(node);
101621                     case 271 /* MissingDeclaration */:
101622                         return;
101623                     // Module references
101624                     case 272 /* ExternalModuleReference */:
101625                         return emitExternalModuleReference(node);
101626                     // JSX (non-expression)
101627                     case 11 /* JsxText */:
101628                         return emitJsxText(node);
101629                     case 275 /* JsxOpeningElement */:
101630                     case 278 /* JsxOpeningFragment */:
101631                         return emitJsxOpeningElementOrFragment(node);
101632                     case 276 /* JsxClosingElement */:
101633                     case 279 /* JsxClosingFragment */:
101634                         return emitJsxClosingElementOrFragment(node);
101635                     case 280 /* JsxAttribute */:
101636                         return emitJsxAttribute(node);
101637                     case 281 /* JsxAttributes */:
101638                         return emitJsxAttributes(node);
101639                     case 282 /* JsxSpreadAttribute */:
101640                         return emitJsxSpreadAttribute(node);
101641                     case 283 /* JsxExpression */:
101642                         return emitJsxExpression(node);
101643                     // Clauses
101644                     case 284 /* CaseClause */:
101645                         return emitCaseClause(node);
101646                     case 285 /* DefaultClause */:
101647                         return emitDefaultClause(node);
101648                     case 286 /* HeritageClause */:
101649                         return emitHeritageClause(node);
101650                     case 287 /* CatchClause */:
101651                         return emitCatchClause(node);
101652                     // Property assignments
101653                     case 288 /* PropertyAssignment */:
101654                         return emitPropertyAssignment(node);
101655                     case 289 /* ShorthandPropertyAssignment */:
101656                         return emitShorthandPropertyAssignment(node);
101657                     case 290 /* SpreadAssignment */:
101658                         return emitSpreadAssignment(node);
101659                     // Enum
101660                     case 291 /* EnumMember */:
101661                         return emitEnumMember(node);
101662                     // JSDoc nodes (only used in codefixes currently)
101663                     case 326 /* JSDocParameterTag */:
101664                     case 333 /* JSDocPropertyTag */:
101665                         return emitJSDocPropertyLikeTag(node);
101666                     case 327 /* JSDocReturnTag */:
101667                     case 329 /* JSDocTypeTag */:
101668                     case 328 /* JSDocThisTag */:
101669                     case 325 /* JSDocEnumTag */:
101670                         return emitJSDocSimpleTypedTag(node);
101671                     case 316 /* JSDocImplementsTag */:
101672                     case 315 /* JSDocAugmentsTag */:
101673                         return emitJSDocHeritageTag(node);
101674                     case 330 /* JSDocTemplateTag */:
101675                         return emitJSDocTemplateTag(node);
101676                     case 331 /* JSDocTypedefTag */:
101677                         return emitJSDocTypedefTag(node);
101678                     case 324 /* JSDocCallbackTag */:
101679                         return emitJSDocCallbackTag(node);
101680                     case 313 /* JSDocSignature */:
101681                         return emitJSDocSignature(node);
101682                     case 312 /* JSDocTypeLiteral */:
101683                         return emitJSDocTypeLiteral(node);
101684                     case 319 /* JSDocClassTag */:
101685                     case 314 /* JSDocTag */:
101686                         return emitJSDocSimpleTag(node);
101687                     case 332 /* JSDocSeeTag */:
101688                         return emitJSDocSeeTag(node);
101689                     case 302 /* JSDocNameReference */:
101690                         return emitJSDocNameReference(node);
101691                     case 311 /* JSDocComment */:
101692                         return emitJSDoc(node);
101693                     // Transformation nodes (ignored)
101694                 }
101695                 if (ts.isExpression(node)) {
101696                     hint = 1 /* Expression */;
101697                     if (substituteNode !== ts.noEmitSubstitution) {
101698                         lastSubstitution = node = substituteNode(hint, node);
101699                     }
101700                 }
101701                 else if (ts.isToken(node)) {
101702                     return writeTokenNode(node, writePunctuation);
101703                 }
101704             }
101705             if (hint === 1 /* Expression */) {
101706                 switch (node.kind) {
101707                     // Literals
101708                     case 8 /* NumericLiteral */:
101709                     case 9 /* BigIntLiteral */:
101710                         return emitNumericOrBigIntLiteral(node);
101711                     case 10 /* StringLiteral */:
101712                     case 13 /* RegularExpressionLiteral */:
101713                     case 14 /* NoSubstitutionTemplateLiteral */:
101714                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
101715                     // Identifiers
101716                     case 78 /* Identifier */:
101717                         return emitIdentifier(node);
101718                     // Reserved words
101719                     case 94 /* FalseKeyword */:
101720                     case 103 /* NullKeyword */:
101721                     case 105 /* SuperKeyword */:
101722                     case 109 /* TrueKeyword */:
101723                     case 107 /* ThisKeyword */:
101724                     case 99 /* ImportKeyword */:
101725                         writeTokenNode(node, writeKeyword);
101726                         return;
101727                     // Expressions
101728                     case 199 /* ArrayLiteralExpression */:
101729                         return emitArrayLiteralExpression(node);
101730                     case 200 /* ObjectLiteralExpression */:
101731                         return emitObjectLiteralExpression(node);
101732                     case 201 /* PropertyAccessExpression */:
101733                         return emitPropertyAccessExpression(node);
101734                     case 202 /* ElementAccessExpression */:
101735                         return emitElementAccessExpression(node);
101736                     case 203 /* CallExpression */:
101737                         return emitCallExpression(node);
101738                     case 204 /* NewExpression */:
101739                         return emitNewExpression(node);
101740                     case 205 /* TaggedTemplateExpression */:
101741                         return emitTaggedTemplateExpression(node);
101742                     case 206 /* TypeAssertionExpression */:
101743                         return emitTypeAssertionExpression(node);
101744                     case 207 /* ParenthesizedExpression */:
101745                         return emitParenthesizedExpression(node);
101746                     case 208 /* FunctionExpression */:
101747                         return emitFunctionExpression(node);
101748                     case 209 /* ArrowFunction */:
101749                         return emitArrowFunction(node);
101750                     case 210 /* DeleteExpression */:
101751                         return emitDeleteExpression(node);
101752                     case 211 /* TypeOfExpression */:
101753                         return emitTypeOfExpression(node);
101754                     case 212 /* VoidExpression */:
101755                         return emitVoidExpression(node);
101756                     case 213 /* AwaitExpression */:
101757                         return emitAwaitExpression(node);
101758                     case 214 /* PrefixUnaryExpression */:
101759                         return emitPrefixUnaryExpression(node);
101760                     case 215 /* PostfixUnaryExpression */:
101761                         return emitPostfixUnaryExpression(node);
101762                     case 216 /* BinaryExpression */:
101763                         return emitBinaryExpression(node);
101764                     case 217 /* ConditionalExpression */:
101765                         return emitConditionalExpression(node);
101766                     case 218 /* TemplateExpression */:
101767                         return emitTemplateExpression(node);
101768                     case 219 /* YieldExpression */:
101769                         return emitYieldExpression(node);
101770                     case 220 /* SpreadElement */:
101771                         return emitSpreadExpression(node);
101772                     case 221 /* ClassExpression */:
101773                         return emitClassExpression(node);
101774                     case 222 /* OmittedExpression */:
101775                         return;
101776                     case 224 /* AsExpression */:
101777                         return emitAsExpression(node);
101778                     case 225 /* NonNullExpression */:
101779                         return emitNonNullExpression(node);
101780                     case 226 /* MetaProperty */:
101781                         return emitMetaProperty(node);
101782                     // JSX
101783                     case 273 /* JsxElement */:
101784                         return emitJsxElement(node);
101785                     case 274 /* JsxSelfClosingElement */:
101786                         return emitJsxSelfClosingElement(node);
101787                     case 277 /* JsxFragment */:
101788                         return emitJsxFragment(node);
101789                     // Transformation nodes
101790                     case 336 /* PartiallyEmittedExpression */:
101791                         return emitPartiallyEmittedExpression(node);
101792                     case 337 /* CommaListExpression */:
101793                         return emitCommaList(node);
101794                 }
101795             }
101796         }
101797         function emitMappedTypeParameter(node) {
101798             emit(node.name);
101799             writeSpace();
101800             writeKeyword("in");
101801             writeSpace();
101802             emit(node.constraint);
101803         }
101804         function pipelineEmitWithSubstitution(hint, node) {
101805             ts.Debug.assert(lastNode === node || lastSubstitution === node);
101806             var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node);
101807             pipelinePhase(hint, lastSubstitution);
101808             ts.Debug.assert(lastNode === node || lastSubstitution === node);
101809         }
101810         function getHelpersFromBundledSourceFiles(bundle) {
101811             var result;
101812             if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
101813                 return undefined;
101814             }
101815             var bundledHelpers = new ts.Map();
101816             for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
101817                 var sourceFile = _b[_a];
101818                 var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
101819                 var helpers = getSortedEmitHelpers(sourceFile);
101820                 if (!helpers)
101821                     continue;
101822                 for (var _c = 0, helpers_5 = helpers; _c < helpers_5.length; _c++) {
101823                     var helper = helpers_5[_c];
101824                     if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
101825                         bundledHelpers.set(helper.name, true);
101826                         (result || (result = [])).push(helper.name);
101827                     }
101828                 }
101829             }
101830             return result;
101831         }
101832         function emitHelpers(node) {
101833             var helpersEmitted = false;
101834             var bundle = node.kind === 298 /* Bundle */ ? node : undefined;
101835             if (bundle && moduleKind === ts.ModuleKind.None) {
101836                 return;
101837             }
101838             var numPrepends = bundle ? bundle.prepends.length : 0;
101839             var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
101840             for (var i = 0; i < numNodes; i++) {
101841                 var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
101842                 var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
101843                 var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.hasRecordedExternalHelpers(sourceFile));
101844                 var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
101845                 var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
101846                 if (helpers) {
101847                     for (var _a = 0, helpers_6 = helpers; _a < helpers_6.length; _a++) {
101848                         var helper = helpers_6[_a];
101849                         if (!helper.scoped) {
101850                             // Skip the helper if it can be skipped and the noEmitHelpers compiler
101851                             // option is set, or if it can be imported and the importHelpers compiler
101852                             // option is set.
101853                             if (shouldSkip)
101854                                 continue;
101855                             // Skip the helper if it can be bundled but hasn't already been emitted and we
101856                             // are emitting a bundled module.
101857                             if (shouldBundle) {
101858                                 if (bundledHelpers.get(helper.name)) {
101859                                     continue;
101860                                 }
101861                                 bundledHelpers.set(helper.name, true);
101862                             }
101863                         }
101864                         else if (bundle) {
101865                             // Skip the helper if it is scoped and we are emitting bundled helpers
101866                             continue;
101867                         }
101868                         var pos = getTextPosWithWriteLine();
101869                         if (typeof helper.text === "string") {
101870                             writeLines(helper.text);
101871                         }
101872                         else {
101873                             writeLines(helper.text(makeFileLevelOptimisticUniqueName));
101874                         }
101875                         if (bundleFileInfo)
101876                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
101877                         helpersEmitted = true;
101878                     }
101879                 }
101880             }
101881             return helpersEmitted;
101882         }
101883         function getSortedEmitHelpers(node) {
101884             var helpers = ts.getEmitHelpers(node);
101885             return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
101886         }
101887         //
101888         // Literals/Pseudo-literals
101889         //
101890         // SyntaxKind.NumericLiteral
101891         // SyntaxKind.BigIntLiteral
101892         function emitNumericOrBigIntLiteral(node) {
101893             emitLiteral(node, /*jsxAttributeEscape*/ false);
101894         }
101895         // SyntaxKind.StringLiteral
101896         // SyntaxKind.RegularExpressionLiteral
101897         // SyntaxKind.NoSubstitutionTemplateLiteral
101898         // SyntaxKind.TemplateHead
101899         // SyntaxKind.TemplateMiddle
101900         // SyntaxKind.TemplateTail
101901         function emitLiteral(node, jsxAttributeEscape) {
101902             var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape);
101903             if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
101904                 && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {
101905                 writeLiteral(text);
101906             }
101907             else {
101908                 // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals
101909                 writeStringLiteral(text);
101910             }
101911         }
101912         // SyntaxKind.UnparsedSource
101913         // SyntaxKind.UnparsedPrepend
101914         function emitUnparsedSourceOrPrepend(unparsed) {
101915             for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
101916                 var text = _b[_a];
101917                 writeLine();
101918                 emit(text);
101919             }
101920         }
101921         // SyntaxKind.UnparsedPrologue
101922         // SyntaxKind.UnparsedText
101923         // SyntaxKind.UnparsedInternal
101924         // SyntaxKind.UnparsedSyntheticReference
101925         function writeUnparsedNode(unparsed) {
101926             writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
101927         }
101928         // SyntaxKind.UnparsedText
101929         // SyntaxKind.UnparsedInternal
101930         function emitUnparsedTextLike(unparsed) {
101931             var pos = getTextPosWithWriteLine();
101932             writeUnparsedNode(unparsed);
101933             if (bundleFileInfo) {
101934                 updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 294 /* UnparsedText */ ?
101935                     "text" /* Text */ :
101936                     "internal" /* Internal */);
101937             }
101938         }
101939         // SyntaxKind.UnparsedSyntheticReference
101940         function emitUnparsedSyntheticReference(unparsed) {
101941             var pos = getTextPosWithWriteLine();
101942             writeUnparsedNode(unparsed);
101943             if (bundleFileInfo) {
101944                 var section = ts.clone(unparsed.section);
101945                 section.pos = pos;
101946                 section.end = writer.getTextPos();
101947                 bundleFileInfo.sections.push(section);
101948             }
101949         }
101950         //
101951         // Identifiers
101952         //
101953         function emitIdentifier(node) {
101954             var writeText = node.symbol ? writeSymbol : write;
101955             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
101956             emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments
101957         }
101958         //
101959         // Names
101960         //
101961         function emitPrivateIdentifier(node) {
101962             var writeText = node.symbol ? writeSymbol : write;
101963             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
101964         }
101965         function emitQualifiedName(node) {
101966             emitEntityName(node.left);
101967             writePunctuation(".");
101968             emit(node.right);
101969         }
101970         function emitEntityName(node) {
101971             if (node.kind === 78 /* Identifier */) {
101972                 emitExpression(node);
101973             }
101974             else {
101975                 emit(node);
101976             }
101977         }
101978         function emitComputedPropertyName(node) {
101979             writePunctuation("[");
101980             emitExpression(node.expression);
101981             writePunctuation("]");
101982         }
101983         //
101984         // Signature elements
101985         //
101986         function emitTypeParameter(node) {
101987             emit(node.name);
101988             if (node.constraint) {
101989                 writeSpace();
101990                 writeKeyword("extends");
101991                 writeSpace();
101992                 emit(node.constraint);
101993             }
101994             if (node.default) {
101995                 writeSpace();
101996                 writeOperator("=");
101997                 writeSpace();
101998                 emit(node.default);
101999             }
102000         }
102001         function emitParameter(node) {
102002             emitDecorators(node, node.decorators);
102003             emitModifiers(node, node.modifiers);
102004             emit(node.dotDotDotToken);
102005             emitNodeWithWriter(node.name, writeParameter);
102006             emit(node.questionToken);
102007             if (node.parent && node.parent.kind === 308 /* JSDocFunctionType */ && !node.name) {
102008                 emit(node.type);
102009             }
102010             else {
102011                 emitTypeAnnotation(node.type);
102012             }
102013             // 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.
102014             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);
102015         }
102016         function emitDecorator(decorator) {
102017             writePunctuation("@");
102018             emitExpression(decorator.expression);
102019         }
102020         //
102021         // Type members
102022         //
102023         function emitPropertySignature(node) {
102024             emitDecorators(node, node.decorators);
102025             emitModifiers(node, node.modifiers);
102026             emitNodeWithWriter(node.name, writeProperty);
102027             emit(node.questionToken);
102028             emitTypeAnnotation(node.type);
102029             writeTrailingSemicolon();
102030         }
102031         function emitPropertyDeclaration(node) {
102032             emitDecorators(node, node.decorators);
102033             emitModifiers(node, node.modifiers);
102034             emit(node.name);
102035             emit(node.questionToken);
102036             emit(node.exclamationToken);
102037             emitTypeAnnotation(node.type);
102038             emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
102039             writeTrailingSemicolon();
102040         }
102041         function emitMethodSignature(node) {
102042             pushNameGenerationScope(node);
102043             emitDecorators(node, node.decorators);
102044             emitModifiers(node, node.modifiers);
102045             emit(node.name);
102046             emit(node.questionToken);
102047             emitTypeParameters(node, node.typeParameters);
102048             emitParameters(node, node.parameters);
102049             emitTypeAnnotation(node.type);
102050             writeTrailingSemicolon();
102051             popNameGenerationScope(node);
102052         }
102053         function emitMethodDeclaration(node) {
102054             emitDecorators(node, node.decorators);
102055             emitModifiers(node, node.modifiers);
102056             emit(node.asteriskToken);
102057             emit(node.name);
102058             emit(node.questionToken);
102059             emitSignatureAndBody(node, emitSignatureHead);
102060         }
102061         function emitConstructor(node) {
102062             emitModifiers(node, node.modifiers);
102063             writeKeyword("constructor");
102064             emitSignatureAndBody(node, emitSignatureHead);
102065         }
102066         function emitAccessorDeclaration(node) {
102067             emitDecorators(node, node.decorators);
102068             emitModifiers(node, node.modifiers);
102069             writeKeyword(node.kind === 167 /* GetAccessor */ ? "get" : "set");
102070             writeSpace();
102071             emit(node.name);
102072             emitSignatureAndBody(node, emitSignatureHead);
102073         }
102074         function emitCallSignature(node) {
102075             pushNameGenerationScope(node);
102076             emitDecorators(node, node.decorators);
102077             emitModifiers(node, node.modifiers);
102078             emitTypeParameters(node, node.typeParameters);
102079             emitParameters(node, node.parameters);
102080             emitTypeAnnotation(node.type);
102081             writeTrailingSemicolon();
102082             popNameGenerationScope(node);
102083         }
102084         function emitConstructSignature(node) {
102085             pushNameGenerationScope(node);
102086             emitDecorators(node, node.decorators);
102087             emitModifiers(node, node.modifiers);
102088             writeKeyword("new");
102089             writeSpace();
102090             emitTypeParameters(node, node.typeParameters);
102091             emitParameters(node, node.parameters);
102092             emitTypeAnnotation(node.type);
102093             writeTrailingSemicolon();
102094             popNameGenerationScope(node);
102095         }
102096         function emitIndexSignature(node) {
102097             emitDecorators(node, node.decorators);
102098             emitModifiers(node, node.modifiers);
102099             emitParametersForIndexSignature(node, node.parameters);
102100             emitTypeAnnotation(node.type);
102101             writeTrailingSemicolon();
102102         }
102103         function emitTemplateTypeSpan(node) {
102104             emit(node.type);
102105             emit(node.literal);
102106         }
102107         function emitSemicolonClassElement() {
102108             writeTrailingSemicolon();
102109         }
102110         //
102111         // Types
102112         //
102113         function emitTypePredicate(node) {
102114             if (node.assertsModifier) {
102115                 emit(node.assertsModifier);
102116                 writeSpace();
102117             }
102118             emit(node.parameterName);
102119             if (node.type) {
102120                 writeSpace();
102121                 writeKeyword("is");
102122                 writeSpace();
102123                 emit(node.type);
102124             }
102125         }
102126         function emitTypeReference(node) {
102127             emit(node.typeName);
102128             emitTypeArguments(node, node.typeArguments);
102129         }
102130         function emitFunctionType(node) {
102131             pushNameGenerationScope(node);
102132             emitTypeParameters(node, node.typeParameters);
102133             emitParametersForArrow(node, node.parameters);
102134             writeSpace();
102135             writePunctuation("=>");
102136             writeSpace();
102137             emit(node.type);
102138             popNameGenerationScope(node);
102139         }
102140         function emitJSDocFunctionType(node) {
102141             writeKeyword("function");
102142             emitParameters(node, node.parameters);
102143             writePunctuation(":");
102144             emit(node.type);
102145         }
102146         function emitJSDocNullableType(node) {
102147             writePunctuation("?");
102148             emit(node.type);
102149         }
102150         function emitJSDocNonNullableType(node) {
102151             writePunctuation("!");
102152             emit(node.type);
102153         }
102154         function emitJSDocOptionalType(node) {
102155             emit(node.type);
102156             writePunctuation("=");
102157         }
102158         function emitConstructorType(node) {
102159             pushNameGenerationScope(node);
102160             emitModifiers(node, node.modifiers);
102161             writeKeyword("new");
102162             writeSpace();
102163             emitTypeParameters(node, node.typeParameters);
102164             emitParameters(node, node.parameters);
102165             writeSpace();
102166             writePunctuation("=>");
102167             writeSpace();
102168             emit(node.type);
102169             popNameGenerationScope(node);
102170         }
102171         function emitTypeQuery(node) {
102172             writeKeyword("typeof");
102173             writeSpace();
102174             emit(node.exprName);
102175         }
102176         function emitTypeLiteral(node) {
102177             writePunctuation("{");
102178             var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */;
102179             emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */);
102180             writePunctuation("}");
102181         }
102182         function emitArrayType(node) {
102183             emit(node.elementType);
102184             writePunctuation("[");
102185             writePunctuation("]");
102186         }
102187         function emitRestOrJSDocVariadicType(node) {
102188             writePunctuation("...");
102189             emit(node.type);
102190         }
102191         function emitTupleType(node) {
102192             emitTokenWithComment(22 /* OpenBracketToken */, node.pos, writePunctuation, node);
102193             var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 528 /* SingleLineTupleTypeElements */ : 657 /* MultiLineTupleTypeElements */;
102194             emitList(node, node.elements, flags | 524288 /* NoSpaceIfEmpty */);
102195             emitTokenWithComment(23 /* CloseBracketToken */, node.elements.end, writePunctuation, node);
102196         }
102197         function emitNamedTupleMember(node) {
102198             emit(node.dotDotDotToken);
102199             emit(node.name);
102200             emit(node.questionToken);
102201             emitTokenWithComment(58 /* ColonToken */, node.name.end, writePunctuation, node);
102202             writeSpace();
102203             emit(node.type);
102204         }
102205         function emitOptionalType(node) {
102206             emit(node.type);
102207             writePunctuation("?");
102208         }
102209         function emitUnionType(node) {
102210             emitList(node, node.types, 516 /* UnionTypeConstituents */);
102211         }
102212         function emitIntersectionType(node) {
102213             emitList(node, node.types, 520 /* IntersectionTypeConstituents */);
102214         }
102215         function emitConditionalType(node) {
102216             emit(node.checkType);
102217             writeSpace();
102218             writeKeyword("extends");
102219             writeSpace();
102220             emit(node.extendsType);
102221             writeSpace();
102222             writePunctuation("?");
102223             writeSpace();
102224             emit(node.trueType);
102225             writeSpace();
102226             writePunctuation(":");
102227             writeSpace();
102228             emit(node.falseType);
102229         }
102230         function emitInferType(node) {
102231             writeKeyword("infer");
102232             writeSpace();
102233             emit(node.typeParameter);
102234         }
102235         function emitParenthesizedType(node) {
102236             writePunctuation("(");
102237             emit(node.type);
102238             writePunctuation(")");
102239         }
102240         function emitThisType() {
102241             writeKeyword("this");
102242         }
102243         function emitTypeOperator(node) {
102244             writeTokenText(node.operator, writeKeyword);
102245             writeSpace();
102246             emit(node.type);
102247         }
102248         function emitIndexedAccessType(node) {
102249             emit(node.objectType);
102250             writePunctuation("[");
102251             emit(node.indexType);
102252             writePunctuation("]");
102253         }
102254         function emitMappedType(node) {
102255             var emitFlags = ts.getEmitFlags(node);
102256             writePunctuation("{");
102257             if (emitFlags & 1 /* SingleLine */) {
102258                 writeSpace();
102259             }
102260             else {
102261                 writeLine();
102262                 increaseIndent();
102263             }
102264             if (node.readonlyToken) {
102265                 emit(node.readonlyToken);
102266                 if (node.readonlyToken.kind !== 142 /* ReadonlyKeyword */) {
102267                     writeKeyword("readonly");
102268                 }
102269                 writeSpace();
102270             }
102271             writePunctuation("[");
102272             pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter);
102273             if (node.nameType) {
102274                 writeSpace();
102275                 writeKeyword("as");
102276                 writeSpace();
102277                 emit(node.nameType);
102278             }
102279             writePunctuation("]");
102280             if (node.questionToken) {
102281                 emit(node.questionToken);
102282                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
102283                     writePunctuation("?");
102284                 }
102285             }
102286             writePunctuation(":");
102287             writeSpace();
102288             emit(node.type);
102289             writeTrailingSemicolon();
102290             if (emitFlags & 1 /* SingleLine */) {
102291                 writeSpace();
102292             }
102293             else {
102294                 writeLine();
102295                 decreaseIndent();
102296             }
102297             writePunctuation("}");
102298         }
102299         function emitLiteralType(node) {
102300             emitExpression(node.literal);
102301         }
102302         function emitTemplateType(node) {
102303             emit(node.head);
102304             emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
102305         }
102306         function emitImportTypeNode(node) {
102307             if (node.isTypeOf) {
102308                 writeKeyword("typeof");
102309                 writeSpace();
102310             }
102311             writeKeyword("import");
102312             writePunctuation("(");
102313             emit(node.argument);
102314             writePunctuation(")");
102315             if (node.qualifier) {
102316                 writePunctuation(".");
102317                 emit(node.qualifier);
102318             }
102319             emitTypeArguments(node, node.typeArguments);
102320         }
102321         //
102322         // Binding patterns
102323         //
102324         function emitObjectBindingPattern(node) {
102325             writePunctuation("{");
102326             emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */);
102327             writePunctuation("}");
102328         }
102329         function emitArrayBindingPattern(node) {
102330             writePunctuation("[");
102331             emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */);
102332             writePunctuation("]");
102333         }
102334         function emitBindingElement(node) {
102335             emit(node.dotDotDotToken);
102336             if (node.propertyName) {
102337                 emit(node.propertyName);
102338                 writePunctuation(":");
102339                 writeSpace();
102340             }
102341             emit(node.name);
102342             emitInitializer(node.initializer, node.name.end, node);
102343         }
102344         //
102345         // Expressions
102346         //
102347         function emitArrayLiteralExpression(node) {
102348             var elements = node.elements;
102349             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
102350             emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine);
102351         }
102352         function emitObjectLiteralExpression(node) {
102353             ts.forEach(node.properties, generateMemberNames);
102354             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
102355             if (indentedFlag) {
102356                 increaseIndent();
102357             }
102358             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
102359             var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */;
102360             emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
102361             if (indentedFlag) {
102362                 decreaseIndent();
102363             }
102364         }
102365         function emitPropertyAccessExpression(node) {
102366             var expression = ts.cast(emitExpression(node.expression), ts.isExpression);
102367             var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos);
102368             var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token);
102369             var linesAfterDot = getLinesBetweenNodes(node, token, node.name);
102370             writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false);
102371             var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ &&
102372                 mayNeedDotDotForPropertyAccess(expression) &&
102373                 !writer.hasTrailingComment() &&
102374                 !writer.hasTrailingWhitespace();
102375             if (shouldEmitDotDot) {
102376                 writePunctuation(".");
102377             }
102378             if (node.questionDotToken) {
102379                 emit(token);
102380             }
102381             else {
102382                 emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node);
102383             }
102384             writeLinesAndIndent(linesAfterDot, /*writeSpaceIfNotIndenting*/ false);
102385             emit(node.name);
102386             decreaseIndentIf(linesBeforeDot, linesAfterDot);
102387         }
102388         // 1..toString is a valid property access, emit a dot after the literal
102389         // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
102390         function mayNeedDotDotForPropertyAccess(expression) {
102391             expression = ts.skipPartiallyEmittedExpressions(expression);
102392             if (ts.isNumericLiteral(expression)) {
102393                 // check if numeric literal is a decimal literal that was originally written with a dot
102394                 var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false);
102395                 // If he number will be printed verbatim and it doesn't already contain a dot, add one
102396                 // if the expression doesn't have any comments that will be emitted.
102397                 return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */));
102398             }
102399             else if (ts.isAccessExpression(expression)) {
102400                 // check if constant enum value is integer
102401                 var constantValue = ts.getConstantValue(expression);
102402                 // isFinite handles cases when constantValue is undefined
102403                 return typeof constantValue === "number" && isFinite(constantValue)
102404                     && Math.floor(constantValue) === constantValue;
102405             }
102406         }
102407         function emitElementAccessExpression(node) {
102408             emitExpression(node.expression);
102409             emit(node.questionDotToken);
102410             emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
102411             emitExpression(node.argumentExpression);
102412             emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node);
102413         }
102414         function emitCallExpression(node) {
102415             emitExpression(node.expression);
102416             emit(node.questionDotToken);
102417             emitTypeArguments(node, node.typeArguments);
102418             emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */);
102419         }
102420         function emitNewExpression(node) {
102421             emitTokenWithComment(102 /* NewKeyword */, node.pos, writeKeyword, node);
102422             writeSpace();
102423             emitExpression(node.expression);
102424             emitTypeArguments(node, node.typeArguments);
102425             emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */);
102426         }
102427         function emitTaggedTemplateExpression(node) {
102428             emitExpression(node.tag);
102429             emitTypeArguments(node, node.typeArguments);
102430             writeSpace();
102431             emitExpression(node.template);
102432         }
102433         function emitTypeAssertionExpression(node) {
102434             writePunctuation("<");
102435             emit(node.type);
102436             writePunctuation(">");
102437             emitExpression(node.expression);
102438         }
102439         function emitParenthesizedExpression(node) {
102440             var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node);
102441             var indented = writeLineSeparatorsAndIndentBefore(node.expression, node);
102442             emitExpression(node.expression);
102443             writeLineSeparatorsAfter(node.expression, node);
102444             decreaseIndentIf(indented);
102445             emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
102446         }
102447         function emitFunctionExpression(node) {
102448             generateNameIfNeeded(node.name);
102449             emitFunctionDeclarationOrExpression(node);
102450         }
102451         function emitArrowFunction(node) {
102452             emitDecorators(node, node.decorators);
102453             emitModifiers(node, node.modifiers);
102454             emitSignatureAndBody(node, emitArrowFunctionHead);
102455         }
102456         function emitArrowFunctionHead(node) {
102457             emitTypeParameters(node, node.typeParameters);
102458             emitParametersForArrow(node, node.parameters);
102459             emitTypeAnnotation(node.type);
102460             writeSpace();
102461             emit(node.equalsGreaterThanToken);
102462         }
102463         function emitDeleteExpression(node) {
102464             emitTokenWithComment(88 /* DeleteKeyword */, node.pos, writeKeyword, node);
102465             writeSpace();
102466             emitExpression(node.expression);
102467         }
102468         function emitTypeOfExpression(node) {
102469             emitTokenWithComment(111 /* TypeOfKeyword */, node.pos, writeKeyword, node);
102470             writeSpace();
102471             emitExpression(node.expression);
102472         }
102473         function emitVoidExpression(node) {
102474             emitTokenWithComment(113 /* VoidKeyword */, node.pos, writeKeyword, node);
102475             writeSpace();
102476             emitExpression(node.expression);
102477         }
102478         function emitAwaitExpression(node) {
102479             emitTokenWithComment(130 /* AwaitKeyword */, node.pos, writeKeyword, node);
102480             writeSpace();
102481             emitExpression(node.expression);
102482         }
102483         function emitPrefixUnaryExpression(node) {
102484             writeTokenText(node.operator, writeOperator);
102485             if (shouldEmitWhitespaceBeforeOperand(node)) {
102486                 writeSpace();
102487             }
102488             emitExpression(node.operand);
102489         }
102490         function shouldEmitWhitespaceBeforeOperand(node) {
102491             // In some cases, we need to emit a space between the operator and the operand. One obvious case
102492             // is when the operator is an identifier, like delete or typeof. We also need to do this for plus
102493             // and minus expressions in certain cases. Specifically, consider the following two cases (parens
102494             // are just for clarity of exposition, and not part of the source code):
102495             //
102496             //  (+(+1))
102497             //  (+(++1))
102498             //
102499             // We need to emit a space in both cases. In the first case, the absence of a space will make
102500             // the resulting expression a prefix increment operation. And in the second, it will make the resulting
102501             // expression a prefix increment whose operand is a plus expression - (++(+x))
102502             // The same is true of minus of course.
102503             var operand = node.operand;
102504             return operand.kind === 214 /* PrefixUnaryExpression */
102505                 && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */))
102506                     || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */)));
102507         }
102508         function emitPostfixUnaryExpression(node) {
102509             emitExpression(node.operand);
102510             writeTokenText(node.operator, writeOperator);
102511         }
102512         var EmitBinaryExpressionState;
102513         (function (EmitBinaryExpressionState) {
102514             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft";
102515             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight";
102516             EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit";
102517         })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {}));
102518         /**
102519          * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions
102520          * as possible without creating any additional stack frames. This can only be done when the emit pipeline does
102521          * not require notification/substitution/comment/sourcemap decorations.
102522          */
102523         function emitBinaryExpression(node) {
102524             var nodeStack = [node];
102525             var stateStack = [0 /* EmitLeft */];
102526             var stackIndex = 0;
102527             while (stackIndex >= 0) {
102528                 node = nodeStack[stackIndex];
102529                 switch (stateStack[stackIndex]) {
102530                     case 0 /* EmitLeft */: {
102531                         maybePipelineEmitExpression(node.left);
102532                         break;
102533                     }
102534                     case 1 /* EmitRight */: {
102535                         var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */;
102536                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
102537                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
102538                         writeLinesAndIndent(linesBeforeOperator, isCommaOperator);
102539                         emitLeadingCommentsOfPosition(node.operatorToken.pos);
102540                         writeTokenNode(node.operatorToken, node.operatorToken.kind === 100 /* InKeyword */ ? writeKeyword : writeOperator);
102541                         emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
102542                         writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true);
102543                         maybePipelineEmitExpression(node.right);
102544                         break;
102545                     }
102546                     case 2 /* FinishEmit */: {
102547                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
102548                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
102549                         decreaseIndentIf(linesBeforeOperator, linesAfterOperator);
102550                         stackIndex--;
102551                         break;
102552                     }
102553                     default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker");
102554                 }
102555             }
102556             function maybePipelineEmitExpression(next) {
102557                 // Advance the state of this unit of work,
102558                 stateStack[stackIndex]++;
102559                 // Then actually do the work of emitting the node `next` returned by the prior state
102560                 // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads
102561                 // binary expression handling, where possible, to the contained work queue
102562                 // #region trampolinePipelineEmit
102563                 var savedLastNode = lastNode;
102564                 var savedLastSubstitution = lastSubstitution;
102565                 lastNode = next;
102566                 lastSubstitution = undefined;
102567                 var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next);
102568                 if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) {
102569                     // If the target pipeline phase is emit directly, and the next node's also a binary expression,
102570                     // skip all the intermediate indirection and push the expression directly onto the work stack
102571                     stackIndex++;
102572                     stateStack[stackIndex] = 0 /* EmitLeft */;
102573                     nodeStack[stackIndex] = next;
102574                 }
102575                 else {
102576                     pipelinePhase(1 /* Expression */, next);
102577                 }
102578                 ts.Debug.assert(lastNode === next);
102579                 lastNode = savedLastNode;
102580                 lastSubstitution = savedLastSubstitution;
102581                 // #endregion trampolinePipelineEmit
102582             }
102583         }
102584         function emitConditionalExpression(node) {
102585             var linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken);
102586             var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue);
102587             var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken);
102588             var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse);
102589             emitExpression(node.condition);
102590             writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true);
102591             emit(node.questionToken);
102592             writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true);
102593             emitExpression(node.whenTrue);
102594             decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion);
102595             writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true);
102596             emit(node.colonToken);
102597             writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true);
102598             emitExpression(node.whenFalse);
102599             decreaseIndentIf(linesBeforeColon, linesAfterColon);
102600         }
102601         function emitTemplateExpression(node) {
102602             emit(node.head);
102603             emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
102604         }
102605         function emitYieldExpression(node) {
102606             emitTokenWithComment(124 /* YieldKeyword */, node.pos, writeKeyword, node);
102607             emit(node.asteriskToken);
102608             emitExpressionWithLeadingSpace(node.expression);
102609         }
102610         function emitSpreadExpression(node) {
102611             emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
102612             emitExpression(node.expression);
102613         }
102614         function emitClassExpression(node) {
102615             generateNameIfNeeded(node.name);
102616             emitClassDeclarationOrExpression(node);
102617         }
102618         function emitExpressionWithTypeArguments(node) {
102619             emitExpression(node.expression);
102620             emitTypeArguments(node, node.typeArguments);
102621         }
102622         function emitAsExpression(node) {
102623             emitExpression(node.expression);
102624             if (node.type) {
102625                 writeSpace();
102626                 writeKeyword("as");
102627                 writeSpace();
102628                 emit(node.type);
102629             }
102630         }
102631         function emitNonNullExpression(node) {
102632             emitExpression(node.expression);
102633             writeOperator("!");
102634         }
102635         function emitMetaProperty(node) {
102636             writeToken(node.keywordToken, node.pos, writePunctuation);
102637             writePunctuation(".");
102638             emit(node.name);
102639         }
102640         //
102641         // Misc
102642         //
102643         function emitTemplateSpan(node) {
102644             emitExpression(node.expression);
102645             emit(node.literal);
102646         }
102647         //
102648         // Statements
102649         //
102650         function emitBlock(node) {
102651             emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
102652         }
102653         function emitBlockStatements(node, forceSingleLine) {
102654             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
102655             var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */;
102656             emitList(node, node.statements, format);
102657             emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
102658         }
102659         function emitVariableStatement(node) {
102660             emitModifiers(node, node.modifiers);
102661             emit(node.declarationList);
102662             writeTrailingSemicolon();
102663         }
102664         function emitEmptyStatement(isEmbeddedStatement) {
102665             // While most trailing semicolons are possibly insignificant, an embedded "empty"
102666             // statement is significant and cannot be elided by a trailing-semicolon-omitting writer.
102667             if (isEmbeddedStatement) {
102668                 writePunctuation(";");
102669             }
102670             else {
102671                 writeTrailingSemicolon();
102672             }
102673         }
102674         function emitExpressionStatement(node) {
102675             emitExpression(node.expression);
102676             // Emit semicolon in non json files
102677             // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation)
102678             if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) {
102679                 writeTrailingSemicolon();
102680             }
102681         }
102682         function emitIfStatement(node) {
102683             var openParenPos = emitTokenWithComment(98 /* IfKeyword */, node.pos, writeKeyword, node);
102684             writeSpace();
102685             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
102686             emitExpression(node.expression);
102687             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
102688             emitEmbeddedStatement(node, node.thenStatement);
102689             if (node.elseStatement) {
102690                 writeLineOrSpace(node, node.thenStatement, node.elseStatement);
102691                 emitTokenWithComment(90 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
102692                 if (node.elseStatement.kind === 234 /* IfStatement */) {
102693                     writeSpace();
102694                     emit(node.elseStatement);
102695                 }
102696                 else {
102697                     emitEmbeddedStatement(node, node.elseStatement);
102698                 }
102699             }
102700         }
102701         function emitWhileClause(node, startPos) {
102702             var openParenPos = emitTokenWithComment(114 /* WhileKeyword */, startPos, writeKeyword, node);
102703             writeSpace();
102704             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
102705             emitExpression(node.expression);
102706             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
102707         }
102708         function emitDoStatement(node) {
102709             emitTokenWithComment(89 /* DoKeyword */, node.pos, writeKeyword, node);
102710             emitEmbeddedStatement(node, node.statement);
102711             if (ts.isBlock(node.statement) && !preserveSourceNewlines) {
102712                 writeSpace();
102713             }
102714             else {
102715                 writeLineOrSpace(node, node.statement, node.expression);
102716             }
102717             emitWhileClause(node, node.statement.end);
102718             writeTrailingSemicolon();
102719         }
102720         function emitWhileStatement(node) {
102721             emitWhileClause(node, node.pos);
102722             emitEmbeddedStatement(node, node.statement);
102723         }
102724         function emitForStatement(node) {
102725             var openParenPos = emitTokenWithComment(96 /* ForKeyword */, node.pos, writeKeyword, node);
102726             writeSpace();
102727             var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
102728             emitForBinding(node.initializer);
102729             pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node);
102730             emitExpressionWithLeadingSpace(node.condition);
102731             pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node);
102732             emitExpressionWithLeadingSpace(node.incrementor);
102733             emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
102734             emitEmbeddedStatement(node, node.statement);
102735         }
102736         function emitForInStatement(node) {
102737             var openParenPos = emitTokenWithComment(96 /* ForKeyword */, node.pos, writeKeyword, node);
102738             writeSpace();
102739             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
102740             emitForBinding(node.initializer);
102741             writeSpace();
102742             emitTokenWithComment(100 /* InKeyword */, node.initializer.end, writeKeyword, node);
102743             writeSpace();
102744             emitExpression(node.expression);
102745             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
102746             emitEmbeddedStatement(node, node.statement);
102747         }
102748         function emitForOfStatement(node) {
102749             var openParenPos = emitTokenWithComment(96 /* ForKeyword */, node.pos, writeKeyword, node);
102750             writeSpace();
102751             emitWithTrailingSpace(node.awaitModifier);
102752             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
102753             emitForBinding(node.initializer);
102754             writeSpace();
102755             emitTokenWithComment(156 /* OfKeyword */, node.initializer.end, writeKeyword, node);
102756             writeSpace();
102757             emitExpression(node.expression);
102758             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
102759             emitEmbeddedStatement(node, node.statement);
102760         }
102761         function emitForBinding(node) {
102762             if (node !== undefined) {
102763                 if (node.kind === 250 /* VariableDeclarationList */) {
102764                     emit(node);
102765                 }
102766                 else {
102767                     emitExpression(node);
102768                 }
102769             }
102770         }
102771         function emitContinueStatement(node) {
102772             emitTokenWithComment(85 /* ContinueKeyword */, node.pos, writeKeyword, node);
102773             emitWithLeadingSpace(node.label);
102774             writeTrailingSemicolon();
102775         }
102776         function emitBreakStatement(node) {
102777             emitTokenWithComment(80 /* BreakKeyword */, node.pos, writeKeyword, node);
102778             emitWithLeadingSpace(node.label);
102779             writeTrailingSemicolon();
102780         }
102781         function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
102782             var node = ts.getParseTreeNode(contextNode);
102783             var isSimilarNode = node && node.kind === contextNode.kind;
102784             var startPos = pos;
102785             if (isSimilarNode && currentSourceFile) {
102786                 pos = ts.skipTrivia(currentSourceFile.text, pos);
102787             }
102788             if (isSimilarNode && contextNode.pos !== startPos) {
102789                 var needsIndent = indentLeading && currentSourceFile && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
102790                 if (needsIndent) {
102791                     increaseIndent();
102792                 }
102793                 emitLeadingCommentsOfPosition(startPos);
102794                 if (needsIndent) {
102795                     decreaseIndent();
102796                 }
102797             }
102798             pos = writeTokenText(token, writer, pos);
102799             if (isSimilarNode && contextNode.end !== pos) {
102800                 var isJsxExprContext = contextNode.kind === 283 /* JsxExpression */;
102801                 emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ !isJsxExprContext, /*forceNoNewline*/ isJsxExprContext);
102802             }
102803             return pos;
102804         }
102805         function emitReturnStatement(node) {
102806             emitTokenWithComment(104 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node);
102807             emitExpressionWithLeadingSpace(node.expression);
102808             writeTrailingSemicolon();
102809         }
102810         function emitWithStatement(node) {
102811             var openParenPos = emitTokenWithComment(115 /* WithKeyword */, node.pos, writeKeyword, node);
102812             writeSpace();
102813             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
102814             emitExpression(node.expression);
102815             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
102816             emitEmbeddedStatement(node, node.statement);
102817         }
102818         function emitSwitchStatement(node) {
102819             var openParenPos = emitTokenWithComment(106 /* SwitchKeyword */, node.pos, writeKeyword, node);
102820             writeSpace();
102821             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
102822             emitExpression(node.expression);
102823             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
102824             writeSpace();
102825             emit(node.caseBlock);
102826         }
102827         function emitLabeledStatement(node) {
102828             emit(node.label);
102829             emitTokenWithComment(58 /* ColonToken */, node.label.end, writePunctuation, node);
102830             writeSpace();
102831             emit(node.statement);
102832         }
102833         function emitThrowStatement(node) {
102834             emitTokenWithComment(108 /* ThrowKeyword */, node.pos, writeKeyword, node);
102835             emitExpressionWithLeadingSpace(node.expression);
102836             writeTrailingSemicolon();
102837         }
102838         function emitTryStatement(node) {
102839             emitTokenWithComment(110 /* TryKeyword */, node.pos, writeKeyword, node);
102840             writeSpace();
102841             emit(node.tryBlock);
102842             if (node.catchClause) {
102843                 writeLineOrSpace(node, node.tryBlock, node.catchClause);
102844                 emit(node.catchClause);
102845             }
102846             if (node.finallyBlock) {
102847                 writeLineOrSpace(node, node.catchClause || node.tryBlock, node.finallyBlock);
102848                 emitTokenWithComment(95 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
102849                 writeSpace();
102850                 emit(node.finallyBlock);
102851             }
102852         }
102853         function emitDebuggerStatement(node) {
102854             writeToken(86 /* DebuggerKeyword */, node.pos, writeKeyword);
102855             writeTrailingSemicolon();
102856         }
102857         //
102858         // Declarations
102859         //
102860         function emitVariableDeclaration(node) {
102861             emit(node.name);
102862             emit(node.exclamationToken);
102863             emitTypeAnnotation(node.type);
102864             emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
102865         }
102866         function emitVariableDeclarationList(node) {
102867             writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var");
102868             writeSpace();
102869             emitList(node, node.declarations, 528 /* VariableDeclarationList */);
102870         }
102871         function emitFunctionDeclaration(node) {
102872             emitFunctionDeclarationOrExpression(node);
102873         }
102874         function emitFunctionDeclarationOrExpression(node) {
102875             emitDecorators(node, node.decorators);
102876             emitModifiers(node, node.modifiers);
102877             writeKeyword("function");
102878             emit(node.asteriskToken);
102879             writeSpace();
102880             emitIdentifierName(node.name);
102881             emitSignatureAndBody(node, emitSignatureHead);
102882         }
102883         function emitBlockCallback(_hint, body) {
102884             emitBlockFunctionBody(body);
102885         }
102886         function emitSignatureAndBody(node, emitSignatureHead) {
102887             var body = node.body;
102888             if (body) {
102889                 if (ts.isBlock(body)) {
102890                     var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
102891                     if (indentedFlag) {
102892                         increaseIndent();
102893                     }
102894                     pushNameGenerationScope(node);
102895                     ts.forEach(node.parameters, generateNames);
102896                     generateNames(node.body);
102897                     emitSignatureHead(node);
102898                     if (onEmitNode) {
102899                         onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
102900                     }
102901                     else {
102902                         emitBlockFunctionBody(body);
102903                     }
102904                     popNameGenerationScope(node);
102905                     if (indentedFlag) {
102906                         decreaseIndent();
102907                     }
102908                 }
102909                 else {
102910                     emitSignatureHead(node);
102911                     writeSpace();
102912                     emitExpression(body);
102913                 }
102914             }
102915             else {
102916                 emitSignatureHead(node);
102917                 writeTrailingSemicolon();
102918             }
102919         }
102920         function emitSignatureHead(node) {
102921             emitTypeParameters(node, node.typeParameters);
102922             emitParameters(node, node.parameters);
102923             emitTypeAnnotation(node.type);
102924         }
102925         function shouldEmitBlockFunctionBodyOnSingleLine(body) {
102926             // We must emit a function body as a single-line body in the following case:
102927             // * The body has NodeEmitFlags.SingleLine specified.
102928             // We must emit a function body as a multi-line body in the following cases:
102929             // * The body is explicitly marked as multi-line.
102930             // * A non-synthesized body's start and end position are on different lines.
102931             // * Any statement in the body starts on a new line.
102932             if (ts.getEmitFlags(body) & 1 /* SingleLine */) {
102933                 return true;
102934             }
102935             if (body.multiLine) {
102936                 return false;
102937             }
102938             if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) {
102939                 return false;
102940             }
102941             if (getLeadingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)
102942                 || getClosingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)) {
102943                 return false;
102944             }
102945             var previousStatement;
102946             for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {
102947                 var statement = _b[_a];
102948                 if (getSeparatingLineTerminatorCount(previousStatement, statement, 2 /* PreserveLines */) > 0) {
102949                     return false;
102950                 }
102951                 previousStatement = statement;
102952             }
102953             return true;
102954         }
102955         function emitBlockFunctionBody(body) {
102956             writeSpace();
102957             writePunctuation("{");
102958             increaseIndent();
102959             var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body)
102960                 ? emitBlockFunctionBodyOnSingleLine
102961                 : emitBlockFunctionBodyWorker;
102962             if (emitBodyWithDetachedComments) {
102963                 emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
102964             }
102965             else {
102966                 emitBlockFunctionBody(body);
102967             }
102968             decreaseIndent();
102969             writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body);
102970         }
102971         function emitBlockFunctionBodyOnSingleLine(body) {
102972             emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true);
102973         }
102974         function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
102975             // Emit all the prologue directives (like "use strict").
102976             var statementOffset = emitPrologueDirectives(body.statements);
102977             var pos = writer.getTextPos();
102978             emitHelpers(body);
102979             if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
102980                 decreaseIndent();
102981                 emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */);
102982                 increaseIndent();
102983             }
102984             else {
102985                 emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset);
102986             }
102987         }
102988         function emitClassDeclaration(node) {
102989             emitClassDeclarationOrExpression(node);
102990         }
102991         function emitClassDeclarationOrExpression(node) {
102992             ts.forEach(node.members, generateMemberNames);
102993             emitDecorators(node, node.decorators);
102994             emitModifiers(node, node.modifiers);
102995             writeKeyword("class");
102996             if (node.name) {
102997                 writeSpace();
102998                 emitIdentifierName(node.name);
102999             }
103000             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
103001             if (indentedFlag) {
103002                 increaseIndent();
103003             }
103004             emitTypeParameters(node, node.typeParameters);
103005             emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */);
103006             writeSpace();
103007             writePunctuation("{");
103008             emitList(node, node.members, 129 /* ClassMembers */);
103009             writePunctuation("}");
103010             if (indentedFlag) {
103011                 decreaseIndent();
103012             }
103013         }
103014         function emitInterfaceDeclaration(node) {
103015             emitDecorators(node, node.decorators);
103016             emitModifiers(node, node.modifiers);
103017             writeKeyword("interface");
103018             writeSpace();
103019             emit(node.name);
103020             emitTypeParameters(node, node.typeParameters);
103021             emitList(node, node.heritageClauses, 512 /* HeritageClauses */);
103022             writeSpace();
103023             writePunctuation("{");
103024             emitList(node, node.members, 129 /* InterfaceMembers */);
103025             writePunctuation("}");
103026         }
103027         function emitTypeAliasDeclaration(node) {
103028             emitDecorators(node, node.decorators);
103029             emitModifiers(node, node.modifiers);
103030             writeKeyword("type");
103031             writeSpace();
103032             emit(node.name);
103033             emitTypeParameters(node, node.typeParameters);
103034             writeSpace();
103035             writePunctuation("=");
103036             writeSpace();
103037             emit(node.type);
103038             writeTrailingSemicolon();
103039         }
103040         function emitEnumDeclaration(node) {
103041             emitModifiers(node, node.modifiers);
103042             writeKeyword("enum");
103043             writeSpace();
103044             emit(node.name);
103045             writeSpace();
103046             writePunctuation("{");
103047             emitList(node, node.members, 145 /* EnumMembers */);
103048             writePunctuation("}");
103049         }
103050         function emitModuleDeclaration(node) {
103051             emitModifiers(node, node.modifiers);
103052             if (~node.flags & 1024 /* GlobalAugmentation */) {
103053                 writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module");
103054                 writeSpace();
103055             }
103056             emit(node.name);
103057             var body = node.body;
103058             if (!body)
103059                 return writeTrailingSemicolon();
103060             while (body.kind === 256 /* ModuleDeclaration */) {
103061                 writePunctuation(".");
103062                 emit(body.name);
103063                 body = body.body;
103064             }
103065             writeSpace();
103066             emit(body);
103067         }
103068         function emitModuleBlock(node) {
103069             pushNameGenerationScope(node);
103070             ts.forEach(node.statements, generateNames);
103071             emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
103072             popNameGenerationScope(node);
103073         }
103074         function emitCaseBlock(node) {
103075             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
103076             emitList(node, node.clauses, 129 /* CaseBlockClauses */);
103077             emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
103078         }
103079         function emitImportEqualsDeclaration(node) {
103080             emitModifiers(node, node.modifiers);
103081             emitTokenWithComment(99 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
103082             writeSpace();
103083             if (node.isTypeOnly) {
103084                 emitTokenWithComment(149 /* TypeKeyword */, node.pos, writeKeyword, node);
103085                 writeSpace();
103086             }
103087             emit(node.name);
103088             writeSpace();
103089             emitTokenWithComment(62 /* EqualsToken */, node.name.end, writePunctuation, node);
103090             writeSpace();
103091             emitModuleReference(node.moduleReference);
103092             writeTrailingSemicolon();
103093         }
103094         function emitModuleReference(node) {
103095             if (node.kind === 78 /* Identifier */) {
103096                 emitExpression(node);
103097             }
103098             else {
103099                 emit(node);
103100             }
103101         }
103102         function emitImportDeclaration(node) {
103103             emitModifiers(node, node.modifiers);
103104             emitTokenWithComment(99 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
103105             writeSpace();
103106             if (node.importClause) {
103107                 emit(node.importClause);
103108                 writeSpace();
103109                 emitTokenWithComment(153 /* FromKeyword */, node.importClause.end, writeKeyword, node);
103110                 writeSpace();
103111             }
103112             emitExpression(node.moduleSpecifier);
103113             writeTrailingSemicolon();
103114         }
103115         function emitImportClause(node) {
103116             if (node.isTypeOnly) {
103117                 emitTokenWithComment(149 /* TypeKeyword */, node.pos, writeKeyword, node);
103118                 writeSpace();
103119             }
103120             emit(node.name);
103121             if (node.name && node.namedBindings) {
103122                 emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node);
103123                 writeSpace();
103124             }
103125             emit(node.namedBindings);
103126         }
103127         function emitNamespaceImport(node) {
103128             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
103129             writeSpace();
103130             emitTokenWithComment(126 /* AsKeyword */, asPos, writeKeyword, node);
103131             writeSpace();
103132             emit(node.name);
103133         }
103134         function emitNamedImports(node) {
103135             emitNamedImportsOrExports(node);
103136         }
103137         function emitImportSpecifier(node) {
103138             emitImportOrExportSpecifier(node);
103139         }
103140         function emitExportAssignment(node) {
103141             var nextPos = emitTokenWithComment(92 /* ExportKeyword */, node.pos, writeKeyword, node);
103142             writeSpace();
103143             if (node.isExportEquals) {
103144                 emitTokenWithComment(62 /* EqualsToken */, nextPos, writeOperator, node);
103145             }
103146             else {
103147                 emitTokenWithComment(87 /* DefaultKeyword */, nextPos, writeKeyword, node);
103148             }
103149             writeSpace();
103150             emitExpression(node.expression);
103151             writeTrailingSemicolon();
103152         }
103153         function emitExportDeclaration(node) {
103154             var nextPos = emitTokenWithComment(92 /* ExportKeyword */, node.pos, writeKeyword, node);
103155             writeSpace();
103156             if (node.isTypeOnly) {
103157                 nextPos = emitTokenWithComment(149 /* TypeKeyword */, nextPos, writeKeyword, node);
103158                 writeSpace();
103159             }
103160             if (node.exportClause) {
103161                 emit(node.exportClause);
103162             }
103163             else {
103164                 nextPos = emitTokenWithComment(41 /* AsteriskToken */, nextPos, writePunctuation, node);
103165             }
103166             if (node.moduleSpecifier) {
103167                 writeSpace();
103168                 var fromPos = node.exportClause ? node.exportClause.end : nextPos;
103169                 emitTokenWithComment(153 /* FromKeyword */, fromPos, writeKeyword, node);
103170                 writeSpace();
103171                 emitExpression(node.moduleSpecifier);
103172             }
103173             writeTrailingSemicolon();
103174         }
103175         function emitNamespaceExportDeclaration(node) {
103176             var nextPos = emitTokenWithComment(92 /* ExportKeyword */, node.pos, writeKeyword, node);
103177             writeSpace();
103178             nextPos = emitTokenWithComment(126 /* AsKeyword */, nextPos, writeKeyword, node);
103179             writeSpace();
103180             nextPos = emitTokenWithComment(140 /* NamespaceKeyword */, nextPos, writeKeyword, node);
103181             writeSpace();
103182             emit(node.name);
103183             writeTrailingSemicolon();
103184         }
103185         function emitNamespaceExport(node) {
103186             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
103187             writeSpace();
103188             emitTokenWithComment(126 /* AsKeyword */, asPos, writeKeyword, node);
103189             writeSpace();
103190             emit(node.name);
103191         }
103192         function emitNamedExports(node) {
103193             emitNamedImportsOrExports(node);
103194         }
103195         function emitExportSpecifier(node) {
103196             emitImportOrExportSpecifier(node);
103197         }
103198         function emitNamedImportsOrExports(node) {
103199             writePunctuation("{");
103200             emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */);
103201             writePunctuation("}");
103202         }
103203         function emitImportOrExportSpecifier(node) {
103204             if (node.propertyName) {
103205                 emit(node.propertyName);
103206                 writeSpace();
103207                 emitTokenWithComment(126 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
103208                 writeSpace();
103209             }
103210             emit(node.name);
103211         }
103212         //
103213         // Module references
103214         //
103215         function emitExternalModuleReference(node) {
103216             writeKeyword("require");
103217             writePunctuation("(");
103218             emitExpression(node.expression);
103219             writePunctuation(")");
103220         }
103221         //
103222         // JSX
103223         //
103224         function emitJsxElement(node) {
103225             emit(node.openingElement);
103226             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
103227             emit(node.closingElement);
103228         }
103229         function emitJsxSelfClosingElement(node) {
103230             writePunctuation("<");
103231             emitJsxTagName(node.tagName);
103232             emitTypeArguments(node, node.typeArguments);
103233             writeSpace();
103234             emit(node.attributes);
103235             writePunctuation("/>");
103236         }
103237         function emitJsxFragment(node) {
103238             emit(node.openingFragment);
103239             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
103240             emit(node.closingFragment);
103241         }
103242         function emitJsxOpeningElementOrFragment(node) {
103243             writePunctuation("<");
103244             if (ts.isJsxOpeningElement(node)) {
103245                 var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node);
103246                 emitJsxTagName(node.tagName);
103247                 emitTypeArguments(node, node.typeArguments);
103248                 if (node.attributes.properties && node.attributes.properties.length > 0) {
103249                     writeSpace();
103250                 }
103251                 emit(node.attributes);
103252                 writeLineSeparatorsAfter(node.attributes, node);
103253                 decreaseIndentIf(indented);
103254             }
103255             writePunctuation(">");
103256         }
103257         function emitJsxText(node) {
103258             writer.writeLiteral(node.text);
103259         }
103260         function emitJsxClosingElementOrFragment(node) {
103261             writePunctuation("</");
103262             if (ts.isJsxClosingElement(node)) {
103263                 emitJsxTagName(node.tagName);
103264             }
103265             writePunctuation(">");
103266         }
103267         function emitJsxAttributes(node) {
103268             emitList(node, node.properties, 262656 /* JsxElementAttributes */);
103269         }
103270         function emitJsxAttribute(node) {
103271             emit(node.name);
103272             emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue);
103273         }
103274         function emitJsxSpreadAttribute(node) {
103275             writePunctuation("{...");
103276             emitExpression(node.expression);
103277             writePunctuation("}");
103278         }
103279         function hasTrailingCommentsAtPosition(pos) {
103280             var result = false;
103281             ts.forEachTrailingCommentRange((currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.text) || "", pos + 1, function () { return result = true; });
103282             return result;
103283         }
103284         function hasLeadingCommentsAtPosition(pos) {
103285             var result = false;
103286             ts.forEachLeadingCommentRange((currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.text) || "", pos + 1, function () { return result = true; });
103287             return result;
103288         }
103289         function hasCommentsAtPosition(pos) {
103290             return hasTrailingCommentsAtPosition(pos) || hasLeadingCommentsAtPosition(pos);
103291         }
103292         function emitJsxExpression(node) {
103293             var _a;
103294             if (node.expression || (!commentsDisabled && !ts.nodeIsSynthesized(node) && hasCommentsAtPosition(node.pos))) { // preserve empty expressions if they contain comments!
103295                 var isMultiline = currentSourceFile && !ts.nodeIsSynthesized(node) && ts.getLineAndCharacterOfPosition(currentSourceFile, node.pos).line !== ts.getLineAndCharacterOfPosition(currentSourceFile, node.end).line;
103296                 if (isMultiline) {
103297                     writer.increaseIndent();
103298                 }
103299                 var end = emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
103300                 emit(node.dotDotDotToken);
103301                 emitExpression(node.expression);
103302                 emitTokenWithComment(19 /* CloseBraceToken */, ((_a = node.expression) === null || _a === void 0 ? void 0 : _a.end) || end, writePunctuation, node);
103303                 if (isMultiline) {
103304                     writer.decreaseIndent();
103305                 }
103306             }
103307         }
103308         function emitJsxTagName(node) {
103309             if (node.kind === 78 /* Identifier */) {
103310                 emitExpression(node);
103311             }
103312             else {
103313                 emit(node);
103314             }
103315         }
103316         //
103317         // Clauses
103318         //
103319         function emitCaseClause(node) {
103320             emitTokenWithComment(81 /* CaseKeyword */, node.pos, writeKeyword, node);
103321             writeSpace();
103322             emitExpression(node.expression);
103323             emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
103324         }
103325         function emitDefaultClause(node) {
103326             var pos = emitTokenWithComment(87 /* DefaultKeyword */, node.pos, writeKeyword, node);
103327             emitCaseOrDefaultClauseRest(node, node.statements, pos);
103328         }
103329         function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
103330             var emitAsSingleStatement = statements.length === 1 &&
103331                 (
103332                 // treat synthesized nodes as located on the same line for emit purposes
103333                 ts.nodeIsSynthesized(parentNode) ||
103334                     ts.nodeIsSynthesized(statements[0]) ||
103335                     ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
103336             var format = 163969 /* CaseOrDefaultClauseStatements */;
103337             if (emitAsSingleStatement) {
103338                 writeToken(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
103339                 writeSpace();
103340                 format &= ~(1 /* MultiLine */ | 128 /* Indented */);
103341             }
103342             else {
103343                 emitTokenWithComment(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
103344             }
103345             emitList(parentNode, statements, format);
103346         }
103347         function emitHeritageClause(node) {
103348             writeSpace();
103349             writeTokenText(node.token, writeKeyword);
103350             writeSpace();
103351             emitList(node, node.types, 528 /* HeritageClauseTypes */);
103352         }
103353         function emitCatchClause(node) {
103354             var openParenPos = emitTokenWithComment(82 /* CatchKeyword */, node.pos, writeKeyword, node);
103355             writeSpace();
103356             if (node.variableDeclaration) {
103357                 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
103358                 emit(node.variableDeclaration);
103359                 emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
103360                 writeSpace();
103361             }
103362             emit(node.block);
103363         }
103364         //
103365         // Property assignments
103366         //
103367         function emitPropertyAssignment(node) {
103368             emit(node.name);
103369             writePunctuation(":");
103370             writeSpace();
103371             // This is to ensure that we emit comment in the following case:
103372             //      For example:
103373             //          obj = {
103374             //              id: /*comment1*/ ()=>void
103375             //          }
103376             // "comment1" is not considered to be leading comment for node.initializer
103377             // but rather a trailing comment on the previous node.
103378             var initializer = node.initializer;
103379             if ((ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
103380                 var commentRange = ts.getCommentRange(initializer);
103381                 emitTrailingCommentsOfPosition(commentRange.pos);
103382             }
103383             emitExpression(initializer);
103384         }
103385         function emitShorthandPropertyAssignment(node) {
103386             emit(node.name);
103387             if (node.objectAssignmentInitializer) {
103388                 writeSpace();
103389                 writePunctuation("=");
103390                 writeSpace();
103391                 emitExpression(node.objectAssignmentInitializer);
103392             }
103393         }
103394         function emitSpreadAssignment(node) {
103395             if (node.expression) {
103396                 emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
103397                 emitExpression(node.expression);
103398             }
103399         }
103400         //
103401         // Enum
103402         //
103403         function emitEnumMember(node) {
103404             emit(node.name);
103405             emitInitializer(node.initializer, node.name.end, node);
103406         }
103407         //
103408         // JSDoc
103409         //
103410         function emitJSDoc(node) {
103411             write("/**");
103412             if (node.comment) {
103413                 var lines = node.comment.split(/\r\n?|\n/g);
103414                 for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) {
103415                     var line = lines_2[_a];
103416                     writeLine();
103417                     writeSpace();
103418                     writePunctuation("*");
103419                     writeSpace();
103420                     write(line);
103421                 }
103422             }
103423             if (node.tags) {
103424                 if (node.tags.length === 1 && node.tags[0].kind === 329 /* JSDocTypeTag */ && !node.comment) {
103425                     writeSpace();
103426                     emit(node.tags[0]);
103427                 }
103428                 else {
103429                     emitList(node, node.tags, 33 /* JSDocComment */);
103430                 }
103431             }
103432             writeSpace();
103433             write("*/");
103434         }
103435         function emitJSDocSimpleTypedTag(tag) {
103436             emitJSDocTagName(tag.tagName);
103437             emitJSDocTypeExpression(tag.typeExpression);
103438             emitJSDocComment(tag.comment);
103439         }
103440         function emitJSDocSeeTag(tag) {
103441             emitJSDocTagName(tag.tagName);
103442             emit(tag.name);
103443             emitJSDocComment(tag.comment);
103444         }
103445         function emitJSDocNameReference(node) {
103446             writeSpace();
103447             writePunctuation("{");
103448             emit(node.name);
103449             writePunctuation("}");
103450         }
103451         function emitJSDocHeritageTag(tag) {
103452             emitJSDocTagName(tag.tagName);
103453             writeSpace();
103454             writePunctuation("{");
103455             emit(tag.class);
103456             writePunctuation("}");
103457             emitJSDocComment(tag.comment);
103458         }
103459         function emitJSDocTemplateTag(tag) {
103460             emitJSDocTagName(tag.tagName);
103461             emitJSDocTypeExpression(tag.constraint);
103462             writeSpace();
103463             emitList(tag, tag.typeParameters, 528 /* CommaListElements */);
103464             emitJSDocComment(tag.comment);
103465         }
103466         function emitJSDocTypedefTag(tag) {
103467             emitJSDocTagName(tag.tagName);
103468             if (tag.typeExpression) {
103469                 if (tag.typeExpression.kind === 301 /* JSDocTypeExpression */) {
103470                     emitJSDocTypeExpression(tag.typeExpression);
103471                 }
103472                 else {
103473                     writeSpace();
103474                     writePunctuation("{");
103475                     write("Object");
103476                     if (tag.typeExpression.isArrayType) {
103477                         writePunctuation("[");
103478                         writePunctuation("]");
103479                     }
103480                     writePunctuation("}");
103481                 }
103482             }
103483             if (tag.fullName) {
103484                 writeSpace();
103485                 emit(tag.fullName);
103486             }
103487             emitJSDocComment(tag.comment);
103488             if (tag.typeExpression && tag.typeExpression.kind === 312 /* JSDocTypeLiteral */) {
103489                 emitJSDocTypeLiteral(tag.typeExpression);
103490             }
103491         }
103492         function emitJSDocCallbackTag(tag) {
103493             emitJSDocTagName(tag.tagName);
103494             if (tag.name) {
103495                 writeSpace();
103496                 emit(tag.name);
103497             }
103498             emitJSDocComment(tag.comment);
103499             emitJSDocSignature(tag.typeExpression);
103500         }
103501         function emitJSDocSimpleTag(tag) {
103502             emitJSDocTagName(tag.tagName);
103503             emitJSDocComment(tag.comment);
103504         }
103505         function emitJSDocTypeLiteral(lit) {
103506             emitList(lit, ts.factory.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */);
103507         }
103508         function emitJSDocSignature(sig) {
103509             if (sig.typeParameters) {
103510                 emitList(sig, ts.factory.createNodeArray(sig.typeParameters), 33 /* JSDocComment */);
103511             }
103512             if (sig.parameters) {
103513                 emitList(sig, ts.factory.createNodeArray(sig.parameters), 33 /* JSDocComment */);
103514             }
103515             if (sig.type) {
103516                 writeLine();
103517                 writeSpace();
103518                 writePunctuation("*");
103519                 writeSpace();
103520                 emit(sig.type);
103521             }
103522         }
103523         function emitJSDocPropertyLikeTag(param) {
103524             emitJSDocTagName(param.tagName);
103525             emitJSDocTypeExpression(param.typeExpression);
103526             writeSpace();
103527             if (param.isBracketed) {
103528                 writePunctuation("[");
103529             }
103530             emit(param.name);
103531             if (param.isBracketed) {
103532                 writePunctuation("]");
103533             }
103534             emitJSDocComment(param.comment);
103535         }
103536         function emitJSDocTagName(tagName) {
103537             writePunctuation("@");
103538             emit(tagName);
103539         }
103540         function emitJSDocComment(comment) {
103541             if (comment) {
103542                 writeSpace();
103543                 write(comment);
103544             }
103545         }
103546         function emitJSDocTypeExpression(typeExpression) {
103547             if (typeExpression) {
103548                 writeSpace();
103549                 writePunctuation("{");
103550                 emit(typeExpression.type);
103551                 writePunctuation("}");
103552             }
103553         }
103554         //
103555         // Top-level nodes
103556         //
103557         function emitSourceFile(node) {
103558             writeLine();
103559             var statements = node.statements;
103560             if (emitBodyWithDetachedComments) {
103561                 // Emit detached comment if there are no prologue directives or if the first node is synthesized.
103562                 // The synthesized node will have no leading comment so some comments may be missed.
103563                 var shouldEmitDetachedComment = statements.length === 0 ||
103564                     !ts.isPrologueDirective(statements[0]) ||
103565                     ts.nodeIsSynthesized(statements[0]);
103566                 if (shouldEmitDetachedComment) {
103567                     emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
103568                     return;
103569                 }
103570             }
103571             emitSourceFileWorker(node);
103572         }
103573         function emitSyntheticTripleSlashReferencesIfNeeded(node) {
103574             emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
103575             for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
103576                 var prepend = _b[_a];
103577                 if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
103578                     for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
103579                         var ref = _d[_c];
103580                         emit(ref);
103581                         writeLine();
103582                     }
103583                 }
103584             }
103585         }
103586         function emitTripleSlashDirectivesIfNeeded(node) {
103587             if (node.isDeclarationFile)
103588                 emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
103589         }
103590         function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
103591             if (hasNoDefaultLib) {
103592                 var pos = writer.getTextPos();
103593                 writeComment("/// <reference no-default-lib=\"true\"/>");
103594                 if (bundleFileInfo)
103595                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
103596                 writeLine();
103597             }
103598             if (currentSourceFile && currentSourceFile.moduleName) {
103599                 writeComment("/// <amd-module name=\"" + currentSourceFile.moduleName + "\" />");
103600                 writeLine();
103601             }
103602             if (currentSourceFile && currentSourceFile.amdDependencies) {
103603                 for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) {
103604                     var dep = _b[_a];
103605                     if (dep.name) {
103606                         writeComment("/// <amd-dependency name=\"" + dep.name + "\" path=\"" + dep.path + "\" />");
103607                     }
103608                     else {
103609                         writeComment("/// <amd-dependency path=\"" + dep.path + "\" />");
103610                     }
103611                     writeLine();
103612                 }
103613             }
103614             for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
103615                 var directive = files_1[_c];
103616                 var pos = writer.getTextPos();
103617                 writeComment("/// <reference path=\"" + directive.fileName + "\" />");
103618                 if (bundleFileInfo)
103619                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
103620                 writeLine();
103621             }
103622             for (var _d = 0, types_25 = types; _d < types_25.length; _d++) {
103623                 var directive = types_25[_d];
103624                 var pos = writer.getTextPos();
103625                 writeComment("/// <reference types=\"" + directive.fileName + "\" />");
103626                 if (bundleFileInfo)
103627                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
103628                 writeLine();
103629             }
103630             for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
103631                 var directive = libs_1[_e];
103632                 var pos = writer.getTextPos();
103633                 writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
103634                 if (bundleFileInfo)
103635                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
103636                 writeLine();
103637             }
103638         }
103639         function emitSourceFileWorker(node) {
103640             var statements = node.statements;
103641             pushNameGenerationScope(node);
103642             ts.forEach(node.statements, generateNames);
103643             emitHelpers(node);
103644             var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
103645             emitTripleSlashDirectivesIfNeeded(node);
103646             emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index);
103647             popNameGenerationScope(node);
103648         }
103649         // Transformation nodes
103650         function emitPartiallyEmittedExpression(node) {
103651             emitExpression(node.expression);
103652         }
103653         function emitCommaList(node) {
103654             emitExpressionList(node, node.elements, 528 /* CommaListElements */);
103655         }
103656         /**
103657          * Emits any prologue directives at the start of a Statement list, returning the
103658          * number of prologue directives written to the output.
103659          */
103660         function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
103661             var needsToSetSourceFile = !!sourceFile;
103662             for (var i = 0; i < statements.length; i++) {
103663                 var statement = statements[i];
103664                 if (ts.isPrologueDirective(statement)) {
103665                     var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
103666                     if (shouldEmitPrologueDirective) {
103667                         if (needsToSetSourceFile) {
103668                             needsToSetSourceFile = false;
103669                             setSourceFile(sourceFile);
103670                         }
103671                         writeLine();
103672                         var pos = writer.getTextPos();
103673                         emit(statement);
103674                         if (recordBundleFileSection && bundleFileInfo)
103675                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
103676                         if (seenPrologueDirectives) {
103677                             seenPrologueDirectives.add(statement.expression.text);
103678                         }
103679                     }
103680                 }
103681                 else {
103682                     // return index of the first non prologue directive
103683                     return i;
103684                 }
103685             }
103686             return statements.length;
103687         }
103688         function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
103689             for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
103690                 var prologue = prologues_1[_a];
103691                 if (!seenPrologueDirectives.has(prologue.data)) {
103692                     writeLine();
103693                     var pos = writer.getTextPos();
103694                     emit(prologue);
103695                     if (bundleFileInfo)
103696                         bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
103697                     if (seenPrologueDirectives) {
103698                         seenPrologueDirectives.add(prologue.data);
103699                     }
103700                 }
103701             }
103702         }
103703         function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
103704             if (ts.isSourceFile(sourceFileOrBundle)) {
103705                 emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
103706             }
103707             else {
103708                 var seenPrologueDirectives = new ts.Set();
103709                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
103710                     var prepend = _b[_a];
103711                     emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
103712                 }
103713                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
103714                     var sourceFile = _d[_c];
103715                     emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
103716                 }
103717                 setSourceFile(undefined);
103718             }
103719         }
103720         function getPrologueDirectivesFromBundledSourceFiles(bundle) {
103721             var seenPrologueDirectives = new ts.Set();
103722             var prologues;
103723             for (var index = 0; index < bundle.sourceFiles.length; index++) {
103724                 var sourceFile = bundle.sourceFiles[index];
103725                 var directives = void 0;
103726                 var end = 0;
103727                 for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
103728                     var statement = _b[_a];
103729                     if (!ts.isPrologueDirective(statement))
103730                         break;
103731                     if (seenPrologueDirectives.has(statement.expression.text))
103732                         continue;
103733                     seenPrologueDirectives.add(statement.expression.text);
103734                     (directives || (directives = [])).push({
103735                         pos: statement.pos,
103736                         end: statement.end,
103737                         expression: {
103738                             pos: statement.expression.pos,
103739                             end: statement.expression.end,
103740                             text: statement.expression.text
103741                         }
103742                     });
103743                     end = end < statement.end ? statement.end : end;
103744                 }
103745                 if (directives)
103746                     (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
103747             }
103748             return prologues;
103749         }
103750         function emitShebangIfNeeded(sourceFileOrBundle) {
103751             if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
103752                 var shebang = ts.getShebang(sourceFileOrBundle.text);
103753                 if (shebang) {
103754                     writeComment(shebang);
103755                     writeLine();
103756                     return true;
103757                 }
103758             }
103759             else {
103760                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
103761                     var prepend = _b[_a];
103762                     ts.Debug.assertNode(prepend, ts.isUnparsedSource);
103763                     if (emitShebangIfNeeded(prepend)) {
103764                         return true;
103765                     }
103766                 }
103767                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
103768                     var sourceFile = _d[_c];
103769                     // Emit only the first encountered shebang
103770                     if (emitShebangIfNeeded(sourceFile)) {
103771                         return true;
103772                     }
103773                 }
103774             }
103775         }
103776         //
103777         // Helpers
103778         //
103779         function emitNodeWithWriter(node, writer) {
103780             if (!node)
103781                 return;
103782             var savedWrite = write;
103783             write = writer;
103784             emit(node);
103785             write = savedWrite;
103786         }
103787         function emitModifiers(node, modifiers) {
103788             if (modifiers && modifiers.length) {
103789                 emitList(node, modifiers, 262656 /* Modifiers */);
103790                 writeSpace();
103791             }
103792         }
103793         function emitTypeAnnotation(node) {
103794             if (node) {
103795                 writePunctuation(":");
103796                 writeSpace();
103797                 emit(node);
103798             }
103799         }
103800         function emitInitializer(node, equalCommentStartPos, container) {
103801             if (node) {
103802                 writeSpace();
103803                 emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
103804                 writeSpace();
103805                 emitExpression(node);
103806             }
103807         }
103808         function emitNodeWithPrefix(prefix, prefixWriter, node, emit) {
103809             if (node) {
103810                 prefixWriter(prefix);
103811                 emit(node);
103812             }
103813         }
103814         function emitWithLeadingSpace(node) {
103815             if (node) {
103816                 writeSpace();
103817                 emit(node);
103818             }
103819         }
103820         function emitExpressionWithLeadingSpace(node) {
103821             if (node) {
103822                 writeSpace();
103823                 emitExpression(node);
103824             }
103825         }
103826         function emitWithTrailingSpace(node) {
103827             if (node) {
103828                 emit(node);
103829                 writeSpace();
103830             }
103831         }
103832         function emitEmbeddedStatement(parent, node) {
103833             if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) {
103834                 writeSpace();
103835                 emit(node);
103836             }
103837             else {
103838                 writeLine();
103839                 increaseIndent();
103840                 if (ts.isEmptyStatement(node)) {
103841                     pipelineEmit(5 /* EmbeddedStatement */, node);
103842                 }
103843                 else {
103844                     emit(node);
103845                 }
103846                 decreaseIndent();
103847             }
103848         }
103849         function emitDecorators(parentNode, decorators) {
103850             emitList(parentNode, decorators, 2146305 /* Decorators */);
103851         }
103852         function emitTypeArguments(parentNode, typeArguments) {
103853             emitList(parentNode, typeArguments, 53776 /* TypeArguments */);
103854         }
103855         function emitTypeParameters(parentNode, typeParameters) {
103856             if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
103857                 return emitTypeArguments(parentNode, parentNode.typeArguments);
103858             }
103859             emitList(parentNode, typeParameters, 53776 /* TypeParameters */);
103860         }
103861         function emitParameters(parentNode, parameters) {
103862             emitList(parentNode, parameters, 2576 /* Parameters */);
103863         }
103864         function canEmitSimpleArrowHead(parentNode, parameters) {
103865             var parameter = ts.singleOrUndefined(parameters);
103866             return parameter
103867                 && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter
103868                 && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head
103869                 && !parentNode.type // arrow function may not have return type annotation
103870                 && !ts.some(parentNode.decorators) // parent may not have decorators
103871                 && !ts.some(parentNode.modifiers) // parent may not have modifiers
103872                 && !ts.some(parentNode.typeParameters) // parent may not have type parameters
103873                 && !ts.some(parameter.decorators) // parameter may not have decorators
103874                 && !ts.some(parameter.modifiers) // parameter may not have modifiers
103875                 && !parameter.dotDotDotToken // parameter may not be rest
103876                 && !parameter.questionToken // parameter may not be optional
103877                 && !parameter.type // parameter may not have a type annotation
103878                 && !parameter.initializer // parameter may not have an initializer
103879                 && ts.isIdentifier(parameter.name); // parameter name must be identifier
103880         }
103881         function emitParametersForArrow(parentNode, parameters) {
103882             if (canEmitSimpleArrowHead(parentNode, parameters)) {
103883                 emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */);
103884             }
103885             else {
103886                 emitParameters(parentNode, parameters);
103887             }
103888         }
103889         function emitParametersForIndexSignature(parentNode, parameters) {
103890             emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */);
103891         }
103892         function emitList(parentNode, children, format, start, count) {
103893             emitNodeList(emit, parentNode, children, format, start, count);
103894         }
103895         function emitExpressionList(parentNode, children, format, start, count) {
103896             emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217
103897         }
103898         function writeDelimiter(format) {
103899             switch (format & 60 /* DelimitersMask */) {
103900                 case 0 /* None */:
103901                     break;
103902                 case 16 /* CommaDelimited */:
103903                     writePunctuation(",");
103904                     break;
103905                 case 4 /* BarDelimited */:
103906                     writeSpace();
103907                     writePunctuation("|");
103908                     break;
103909                 case 32 /* AsteriskDelimited */:
103910                     writeSpace();
103911                     writePunctuation("*");
103912                     writeSpace();
103913                     break;
103914                 case 8 /* AmpersandDelimited */:
103915                     writeSpace();
103916                     writePunctuation("&");
103917                     break;
103918             }
103919         }
103920         function emitNodeList(emit, parentNode, children, format, start, count) {
103921             if (start === void 0) { start = 0; }
103922             if (count === void 0) { count = children ? children.length - start : 0; }
103923             var isUndefined = children === undefined;
103924             if (isUndefined && format & 16384 /* OptionalIfUndefined */) {
103925                 return;
103926             }
103927             var isEmpty = children === undefined || start >= children.length || count === 0;
103928             if (isEmpty && format & 32768 /* OptionalIfEmpty */) {
103929                 if (onBeforeEmitNodeArray) {
103930                     onBeforeEmitNodeArray(children);
103931                 }
103932                 if (onAfterEmitNodeArray) {
103933                     onAfterEmitNodeArray(children);
103934                 }
103935                 return;
103936             }
103937             if (format & 15360 /* BracketsMask */) {
103938                 writePunctuation(getOpeningBracket(format));
103939                 if (isEmpty && !isUndefined) {
103940                     // TODO: GH#18217
103941                     emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
103942                 }
103943             }
103944             if (onBeforeEmitNodeArray) {
103945                 onBeforeEmitNodeArray(children);
103946             }
103947             if (isEmpty) {
103948                 // Write a line terminator if the parent node was multi-line
103949                 if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) {
103950                     writeLine();
103951                 }
103952                 else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) {
103953                     writeSpace();
103954                 }
103955             }
103956             else {
103957                 // Write the opening line terminator or leading whitespace.
103958                 var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0;
103959                 var shouldEmitInterveningComments = mayEmitInterveningComments;
103960                 var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217
103961                 if (leadingLineTerminatorCount) {
103962                     writeLine(leadingLineTerminatorCount);
103963                     shouldEmitInterveningComments = false;
103964                 }
103965                 else if (format & 256 /* SpaceBetweenBraces */) {
103966                     writeSpace();
103967                 }
103968                 // Increase the indent, if requested.
103969                 if (format & 128 /* Indented */) {
103970                     increaseIndent();
103971                 }
103972                 // Emit each child.
103973                 var previousSibling = void 0;
103974                 var previousSourceFileTextKind = void 0;
103975                 var shouldDecreaseIndentAfterEmit = false;
103976                 for (var i = 0; i < count; i++) {
103977                     var child = children[start + i];
103978                     // Write the delimiter if this is not the first node.
103979                     if (format & 32 /* AsteriskDelimited */) {
103980                         // always write JSDoc in the format "\n *"
103981                         writeLine();
103982                         writeDelimiter(format);
103983                     }
103984                     else if (previousSibling) {
103985                         // i.e
103986                         //      function commentedParameters(
103987                         //          /* Parameter a */
103988                         //          a
103989                         //          /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
103990                         //          ,
103991                         if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) {
103992                             emitLeadingCommentsOfPosition(previousSibling.end);
103993                         }
103994                         writeDelimiter(format);
103995                         recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
103996                         // Write either a line terminator or whitespace to separate the elements.
103997                         var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format);
103998                         if (separatingLineTerminatorCount > 0) {
103999                             // If a synthesized node in a single-line list starts on a new
104000                             // line, we should increase the indent.
104001                             if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) {
104002                                 increaseIndent();
104003                                 shouldDecreaseIndentAfterEmit = true;
104004                             }
104005                             writeLine(separatingLineTerminatorCount);
104006                             shouldEmitInterveningComments = false;
104007                         }
104008                         else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) {
104009                             writeSpace();
104010                         }
104011                     }
104012                     // Emit this child.
104013                     previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
104014                     if (shouldEmitInterveningComments) {
104015                         if (emitTrailingCommentsOfPosition) {
104016                             var commentRange = ts.getCommentRange(child);
104017                             emitTrailingCommentsOfPosition(commentRange.pos);
104018                         }
104019                     }
104020                     else {
104021                         shouldEmitInterveningComments = mayEmitInterveningComments;
104022                     }
104023                     nextListElementPos = child.pos;
104024                     emit(child);
104025                     if (shouldDecreaseIndentAfterEmit) {
104026                         decreaseIndent();
104027                         shouldDecreaseIndentAfterEmit = false;
104028                     }
104029                     previousSibling = child;
104030                 }
104031                 // Write a trailing comma, if requested.
104032                 var emitFlags = previousSibling ? ts.getEmitFlags(previousSibling) : 0;
104033                 var skipTrailingComments = commentsDisabled || !!(emitFlags & 1024 /* NoTrailingComments */);
104034                 var hasTrailingComma = (children === null || children === void 0 ? void 0 : children.hasTrailingComma) && (format & 64 /* AllowTrailingComma */) && (format & 16 /* CommaDelimited */);
104035                 if (hasTrailingComma) {
104036                     if (previousSibling && !skipTrailingComments) {
104037                         emitTokenWithComment(27 /* CommaToken */, previousSibling.end, writePunctuation, previousSibling);
104038                     }
104039                     else {
104040                         writePunctuation(",");
104041                     }
104042                 }
104043                 // Emit any trailing comment of the last element in the list
104044                 // i.e
104045                 //       var array = [...
104046                 //          2
104047                 //          /* end of element 2 */
104048                 //       ];
104049                 if (previousSibling && parentNode.end !== previousSibling.end && (format & 60 /* DelimitersMask */) && !skipTrailingComments) {
104050                     emitLeadingCommentsOfPosition(hasTrailingComma && (children === null || children === void 0 ? void 0 : children.end) ? children.end : previousSibling.end);
104051                 }
104052                 // Decrease the indent, if requested.
104053                 if (format & 128 /* Indented */) {
104054                     decreaseIndent();
104055                 }
104056                 recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
104057                 // Write the closing line terminator or closing whitespace.
104058                 var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format);
104059                 if (closingLineTerminatorCount) {
104060                     writeLine(closingLineTerminatorCount);
104061                 }
104062                 else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) {
104063                     writeSpace();
104064                 }
104065             }
104066             if (onAfterEmitNodeArray) {
104067                 onAfterEmitNodeArray(children);
104068             }
104069             if (format & 15360 /* BracketsMask */) {
104070                 if (isEmpty && !isUndefined) {
104071                     // TODO: GH#18217
104072                     emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
104073                 }
104074                 writePunctuation(getClosingBracket(format));
104075             }
104076         }
104077         // Writers
104078         function writeLiteral(s) {
104079             writer.writeLiteral(s);
104080         }
104081         function writeStringLiteral(s) {
104082             writer.writeStringLiteral(s);
104083         }
104084         function writeBase(s) {
104085             writer.write(s);
104086         }
104087         function writeSymbol(s, sym) {
104088             writer.writeSymbol(s, sym);
104089         }
104090         function writePunctuation(s) {
104091             writer.writePunctuation(s);
104092         }
104093         function writeTrailingSemicolon() {
104094             writer.writeTrailingSemicolon(";");
104095         }
104096         function writeKeyword(s) {
104097             writer.writeKeyword(s);
104098         }
104099         function writeOperator(s) {
104100             writer.writeOperator(s);
104101         }
104102         function writeParameter(s) {
104103             writer.writeParameter(s);
104104         }
104105         function writeComment(s) {
104106             writer.writeComment(s);
104107         }
104108         function writeSpace() {
104109             writer.writeSpace(" ");
104110         }
104111         function writeProperty(s) {
104112             writer.writeProperty(s);
104113         }
104114         function writeLine(count) {
104115             if (count === void 0) { count = 1; }
104116             for (var i = 0; i < count; i++) {
104117                 writer.writeLine(i > 0);
104118             }
104119         }
104120         function increaseIndent() {
104121             writer.increaseIndent();
104122         }
104123         function decreaseIndent() {
104124             writer.decreaseIndent();
104125         }
104126         function writeToken(token, pos, writer, contextNode) {
104127             return !sourceMapsDisabled
104128                 ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText)
104129                 : writeTokenText(token, writer, pos);
104130         }
104131         function writeTokenNode(node, writer) {
104132             if (onBeforeEmitToken) {
104133                 onBeforeEmitToken(node);
104134             }
104135             writer(ts.tokenToString(node.kind));
104136             if (onAfterEmitToken) {
104137                 onAfterEmitToken(node);
104138             }
104139         }
104140         function writeTokenText(token, writer, pos) {
104141             var tokenString = ts.tokenToString(token);
104142             writer(tokenString);
104143             return pos < 0 ? pos : pos + tokenString.length;
104144         }
104145         function writeLineOrSpace(parentNode, prevChildNode, nextChildNode) {
104146             if (ts.getEmitFlags(parentNode) & 1 /* SingleLine */) {
104147                 writeSpace();
104148             }
104149             else if (preserveSourceNewlines) {
104150                 var lines = getLinesBetweenNodes(parentNode, prevChildNode, nextChildNode);
104151                 if (lines) {
104152                     writeLine(lines);
104153                 }
104154                 else {
104155                     writeSpace();
104156                 }
104157             }
104158             else {
104159                 writeLine();
104160             }
104161         }
104162         function writeLines(text) {
104163             var lines = text.split(/\r\n?|\n/g);
104164             var indentation = ts.guessIndentation(lines);
104165             for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) {
104166                 var lineText = lines_3[_a];
104167                 var line = indentation ? lineText.slice(indentation) : lineText;
104168                 if (line.length) {
104169                     writeLine();
104170                     write(line);
104171                 }
104172             }
104173         }
104174         function writeLinesAndIndent(lineCount, writeSpaceIfNotIndenting) {
104175             if (lineCount) {
104176                 increaseIndent();
104177                 writeLine(lineCount);
104178             }
104179             else if (writeSpaceIfNotIndenting) {
104180                 writeSpace();
104181             }
104182         }
104183         // Helper function to decrease the indent if we previously indented.  Allows multiple
104184         // previous indent values to be considered at a time.  This also allows caller to just
104185         // call this once, passing in all their appropriate indent values, instead of needing
104186         // to call this helper function multiple times.
104187         function decreaseIndentIf(value1, value2) {
104188             if (value1) {
104189                 decreaseIndent();
104190             }
104191             if (value2) {
104192                 decreaseIndent();
104193             }
104194         }
104195         function getLeadingLineTerminatorCount(parentNode, children, format) {
104196             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
104197                 if (format & 65536 /* PreferNewLine */) {
104198                     return 1;
104199                 }
104200                 var firstChild_1 = children[0];
104201                 if (firstChild_1 === undefined) {
104202                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
104203                 }
104204                 if (firstChild_1.pos === nextListElementPos) {
104205                     // If this child starts at the beginning of a list item in a parent list, its leading
104206                     // line terminators have already been written as the separating line terminators of the
104207                     // parent list. Example:
104208                     //
104209                     // class Foo {
104210                     //   constructor() {}
104211                     //   public foo() {}
104212                     // }
104213                     //
104214                     // The outer list is the list of class members, with one line terminator between the
104215                     // constructor and the method. The constructor is written, the separating line terminator
104216                     // is written, and then we start emitting the method. Its modifiers ([public]) constitute an inner
104217                     // list, so we look for its leading line terminators. If we didn't know that we had already
104218                     // written a newline as part of the parent list, it would appear that we need to write a
104219                     // leading newline to start the modifiers.
104220                     return 0;
104221                 }
104222                 if (firstChild_1.kind === 11 /* JsxText */) {
104223                     // JsxText will be written with its leading whitespace, so don't add more manually.
104224                     return 0;
104225                 }
104226                 if (!ts.positionIsSynthesized(parentNode.pos) &&
104227                     !ts.nodeIsSynthesized(firstChild_1) &&
104228                     (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) {
104229                     if (preserveSourceNewlines) {
104230                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); });
104231                     }
104232                     return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1;
104233                 }
104234                 if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) {
104235                     return 1;
104236                 }
104237             }
104238             return format & 1 /* MultiLine */ ? 1 : 0;
104239         }
104240         function getSeparatingLineTerminatorCount(previousNode, nextNode, format) {
104241             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
104242                 if (previousNode === undefined || nextNode === undefined) {
104243                     return 0;
104244                 }
104245                 if (nextNode.kind === 11 /* JsxText */) {
104246                     // JsxText will be written with its leading whitespace, so don't add more manually.
104247                     return 0;
104248                 }
104249                 else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) {
104250                     if (preserveSourceNewlines) {
104251                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); });
104252                     }
104253                     return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1;
104254                 }
104255                 else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) {
104256                     return 1;
104257                 }
104258             }
104259             else if (ts.getStartsOnNewLine(nextNode)) {
104260                 return 1;
104261             }
104262             return format & 1 /* MultiLine */ ? 1 : 0;
104263         }
104264         function getClosingLineTerminatorCount(parentNode, children, format) {
104265             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
104266                 if (format & 65536 /* PreferNewLine */) {
104267                     return 1;
104268                 }
104269                 var lastChild = ts.lastOrUndefined(children);
104270                 if (lastChild === undefined) {
104271                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
104272                 }
104273                 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) {
104274                     if (preserveSourceNewlines) {
104275                         var end_1 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end;
104276                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_1, parentNode.end, currentSourceFile, includeComments); });
104277                     }
104278                     return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1;
104279                 }
104280                 if (synthesizedNodeStartsOnNewLine(lastChild, format)) {
104281                     return 1;
104282                 }
104283             }
104284             if (format & 1 /* MultiLine */ && !(format & 131072 /* NoTrailingNewLine */)) {
104285                 return 1;
104286             }
104287             return 0;
104288         }
104289         function getEffectiveLines(getLineDifference) {
104290             // If 'preserveSourceNewlines' is disabled, we should never call this function
104291             // because it could be more expensive than alternative approximations.
104292             ts.Debug.assert(!!preserveSourceNewlines);
104293             // We start by measuring the line difference from a position to its adjacent comments,
104294             // so that this is counted as a one-line difference, not two:
104295             //
104296             //   node1;
104297             //   // NODE2 COMMENT
104298             //   node2;
104299             var lines = getLineDifference(/*includeComments*/ true);
104300             if (lines === 0) {
104301                 // However, if the line difference considering comments was 0, we might have this:
104302                 //
104303                 //   node1; // NODE2 COMMENT
104304                 //   node2;
104305                 //
104306                 // in which case we should be ignoring node2's comment, so this too is counted as
104307                 // a one-line difference, not zero.
104308                 return getLineDifference(/*includeComments*/ false);
104309             }
104310             return lines;
104311         }
104312         function writeLineSeparatorsAndIndentBefore(node, parent) {
104313             var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */);
104314             if (leadingNewlines) {
104315                 writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false);
104316             }
104317             return !!leadingNewlines;
104318         }
104319         function writeLineSeparatorsAfter(node, parent) {
104320             var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */);
104321             if (trailingNewlines) {
104322                 writeLine(trailingNewlines);
104323             }
104324         }
104325         function synthesizedNodeStartsOnNewLine(node, format) {
104326             if (ts.nodeIsSynthesized(node)) {
104327                 var startsOnNewLine = ts.getStartsOnNewLine(node);
104328                 if (startsOnNewLine === undefined) {
104329                     return (format & 65536 /* PreferNewLine */) !== 0;
104330                 }
104331                 return startsOnNewLine;
104332             }
104333             return (format & 65536 /* PreferNewLine */) !== 0;
104334         }
104335         function getLinesBetweenNodes(parent, node1, node2) {
104336             if (ts.getEmitFlags(parent) & 131072 /* NoIndentation */) {
104337                 return 0;
104338             }
104339             parent = skipSynthesizedParentheses(parent);
104340             node1 = skipSynthesizedParentheses(node1);
104341             node2 = skipSynthesizedParentheses(node2);
104342             // Always use a newline for synthesized code if the synthesizer desires it.
104343             if (ts.getStartsOnNewLine(node2)) {
104344                 return 1;
104345             }
104346             if (!ts.nodeIsSynthesized(parent) && !ts.nodeIsSynthesized(node1) && !ts.nodeIsSynthesized(node2)) {
104347                 if (preserveSourceNewlines) {
104348                     return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(node1, node2, currentSourceFile, includeComments); });
104349                 }
104350                 return ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1;
104351             }
104352             return 0;
104353         }
104354         function isEmptyBlock(block) {
104355             return block.statements.length === 0
104356                 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
104357         }
104358         function skipSynthesizedParentheses(node) {
104359             while (node.kind === 207 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
104360                 node = node.expression;
104361             }
104362             return node;
104363         }
104364         function getTextOfNode(node, includeTrivia) {
104365             if (ts.isGeneratedIdentifier(node)) {
104366                 return generateName(node);
104367             }
104368             else if ((ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
104369                 return ts.idText(node);
104370             }
104371             else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
104372                 return getTextOfNode(node.textSourceNode, includeTrivia);
104373             }
104374             else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
104375                 return node.text;
104376             }
104377             return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia);
104378         }
104379         function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) {
104380             if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
104381                 var textSourceNode = node.textSourceNode;
104382                 if (ts.isIdentifier(textSourceNode) || ts.isNumericLiteral(textSourceNode)) {
104383                     var text = ts.isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode(textSourceNode);
104384                     return jsxAttributeEscape ? "\"" + ts.escapeJsxAttributeString(text) + "\"" :
104385                         neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(text) + "\"" :
104386                             "\"" + ts.escapeNonAsciiString(text) + "\"";
104387                 }
104388                 else {
104389                     return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape);
104390                 }
104391             }
104392             var flags = (neverAsciiEscape ? 1 /* NeverAsciiEscape */ : 0)
104393                 | (jsxAttributeEscape ? 2 /* JsxAttributeEscape */ : 0)
104394                 | (printerOptions.terminateUnterminatedLiterals ? 4 /* TerminateUnterminatedLiterals */ : 0)
104395                 | (printerOptions.target && printerOptions.target === 99 /* ESNext */ ? 8 /* AllowNumericSeparator */ : 0);
104396             return ts.getLiteralText(node, currentSourceFile, flags);
104397         }
104398         /**
104399          * Push a new name generation scope.
104400          */
104401         function pushNameGenerationScope(node) {
104402             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
104403                 return;
104404             }
104405             tempFlagsStack.push(tempFlags);
104406             tempFlags = 0;
104407             reservedNamesStack.push(reservedNames);
104408         }
104409         /**
104410          * Pop the current name generation scope.
104411          */
104412         function popNameGenerationScope(node) {
104413             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
104414                 return;
104415             }
104416             tempFlags = tempFlagsStack.pop();
104417             reservedNames = reservedNamesStack.pop();
104418         }
104419         function reserveNameInNestedScopes(name) {
104420             if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) {
104421                 reservedNames = new ts.Set();
104422             }
104423             reservedNames.add(name);
104424         }
104425         function generateNames(node) {
104426             if (!node)
104427                 return;
104428             switch (node.kind) {
104429                 case 230 /* Block */:
104430                     ts.forEach(node.statements, generateNames);
104431                     break;
104432                 case 245 /* LabeledStatement */:
104433                 case 243 /* WithStatement */:
104434                 case 235 /* DoStatement */:
104435                 case 236 /* WhileStatement */:
104436                     generateNames(node.statement);
104437                     break;
104438                 case 234 /* IfStatement */:
104439                     generateNames(node.thenStatement);
104440                     generateNames(node.elseStatement);
104441                     break;
104442                 case 237 /* ForStatement */:
104443                 case 239 /* ForOfStatement */:
104444                 case 238 /* ForInStatement */:
104445                     generateNames(node.initializer);
104446                     generateNames(node.statement);
104447                     break;
104448                 case 244 /* SwitchStatement */:
104449                     generateNames(node.caseBlock);
104450                     break;
104451                 case 258 /* CaseBlock */:
104452                     ts.forEach(node.clauses, generateNames);
104453                     break;
104454                 case 284 /* CaseClause */:
104455                 case 285 /* DefaultClause */:
104456                     ts.forEach(node.statements, generateNames);
104457                     break;
104458                 case 247 /* TryStatement */:
104459                     generateNames(node.tryBlock);
104460                     generateNames(node.catchClause);
104461                     generateNames(node.finallyBlock);
104462                     break;
104463                 case 287 /* CatchClause */:
104464                     generateNames(node.variableDeclaration);
104465                     generateNames(node.block);
104466                     break;
104467                 case 232 /* VariableStatement */:
104468                     generateNames(node.declarationList);
104469                     break;
104470                 case 250 /* VariableDeclarationList */:
104471                     ts.forEach(node.declarations, generateNames);
104472                     break;
104473                 case 249 /* VariableDeclaration */:
104474                 case 160 /* Parameter */:
104475                 case 198 /* BindingElement */:
104476                 case 252 /* ClassDeclaration */:
104477                     generateNameIfNeeded(node.name);
104478                     break;
104479                 case 251 /* FunctionDeclaration */:
104480                     generateNameIfNeeded(node.name);
104481                     if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
104482                         ts.forEach(node.parameters, generateNames);
104483                         generateNames(node.body);
104484                     }
104485                     break;
104486                 case 196 /* ObjectBindingPattern */:
104487                 case 197 /* ArrayBindingPattern */:
104488                     ts.forEach(node.elements, generateNames);
104489                     break;
104490                 case 261 /* ImportDeclaration */:
104491                     generateNames(node.importClause);
104492                     break;
104493                 case 262 /* ImportClause */:
104494                     generateNameIfNeeded(node.name);
104495                     generateNames(node.namedBindings);
104496                     break;
104497                 case 263 /* NamespaceImport */:
104498                     generateNameIfNeeded(node.name);
104499                     break;
104500                 case 269 /* NamespaceExport */:
104501                     generateNameIfNeeded(node.name);
104502                     break;
104503                 case 264 /* NamedImports */:
104504                     ts.forEach(node.elements, generateNames);
104505                     break;
104506                 case 265 /* ImportSpecifier */:
104507                     generateNameIfNeeded(node.propertyName || node.name);
104508                     break;
104509             }
104510         }
104511         function generateMemberNames(node) {
104512             if (!node)
104513                 return;
104514             switch (node.kind) {
104515                 case 288 /* PropertyAssignment */:
104516                 case 289 /* ShorthandPropertyAssignment */:
104517                 case 163 /* PropertyDeclaration */:
104518                 case 165 /* MethodDeclaration */:
104519                 case 167 /* GetAccessor */:
104520                 case 168 /* SetAccessor */:
104521                     generateNameIfNeeded(node.name);
104522                     break;
104523             }
104524         }
104525         function generateNameIfNeeded(name) {
104526             if (name) {
104527                 if (ts.isGeneratedIdentifier(name)) {
104528                     generateName(name);
104529                 }
104530                 else if (ts.isBindingPattern(name)) {
104531                     generateNames(name);
104532                 }
104533             }
104534         }
104535         /**
104536          * Generate the text for a generated identifier.
104537          */
104538         function generateName(name) {
104539             if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
104540                 // Node names generate unique names based on their original node
104541                 // and are cached based on that node's id.
104542                 return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
104543             }
104544             else {
104545                 // Auto, Loop, and Unique names are cached based on their unique
104546                 // autoGenerateId.
104547                 var autoGenerateId = name.autoGenerateId;
104548                 return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
104549             }
104550         }
104551         function generateNameCached(node, flags) {
104552             var nodeId = ts.getNodeId(node);
104553             return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
104554         }
104555         /**
104556          * Returns a value indicating whether a name is unique globally, within the current file,
104557          * or within the NameGenerator.
104558          */
104559         function isUniqueName(name) {
104560             return isFileLevelUniqueName(name)
104561                 && !generatedNames.has(name)
104562                 && !(reservedNames && reservedNames.has(name));
104563         }
104564         /**
104565          * Returns a value indicating whether a name is unique globally or within the current file.
104566          */
104567         function isFileLevelUniqueName(name) {
104568             return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
104569         }
104570         /**
104571          * Returns a value indicating whether a name is unique within a container.
104572          */
104573         function isUniqueLocalName(name, container) {
104574             for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) {
104575                 if (node.locals) {
104576                     var local = node.locals.get(ts.escapeLeadingUnderscores(name));
104577                     // We conservatively include alias symbols to cover cases where they're emitted as locals
104578                     if (local && local.flags & (111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
104579                         return false;
104580                     }
104581                 }
104582             }
104583             return true;
104584         }
104585         /**
104586          * Return the next available name in the pattern _a ... _z, _0, _1, ...
104587          * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
104588          * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
104589          */
104590         function makeTempVariableName(flags, reservedInNestedScopes) {
104591             if (flags && !(tempFlags & flags)) {
104592                 var name = flags === 268435456 /* _i */ ? "_i" : "_n";
104593                 if (isUniqueName(name)) {
104594                     tempFlags |= flags;
104595                     if (reservedInNestedScopes) {
104596                         reserveNameInNestedScopes(name);
104597                     }
104598                     return name;
104599                 }
104600             }
104601             while (true) {
104602                 var count = tempFlags & 268435455 /* CountMask */;
104603                 tempFlags++;
104604                 // Skip over 'i' and 'n'
104605                 if (count !== 8 && count !== 13) {
104606                     var name = count < 26
104607                         ? "_" + String.fromCharCode(97 /* a */ + count)
104608                         : "_" + (count - 26);
104609                     if (isUniqueName(name)) {
104610                         if (reservedInNestedScopes) {
104611                             reserveNameInNestedScopes(name);
104612                         }
104613                         return name;
104614                     }
104615                 }
104616             }
104617         }
104618         /**
104619          * Generate a name that is unique within the current file and doesn't conflict with any names
104620          * in global scope. The name is formed by adding an '_n' suffix to the specified base name,
104621          * where n is a positive integer. Note that names generated by makeTempVariableName and
104622          * makeUniqueName are guaranteed to never conflict.
104623          * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
104624          */
104625         function makeUniqueName(baseName, checkFn, optimistic, scoped) {
104626             if (checkFn === void 0) { checkFn = isUniqueName; }
104627             if (optimistic) {
104628                 if (checkFn(baseName)) {
104629                     if (scoped) {
104630                         reserveNameInNestedScopes(baseName);
104631                     }
104632                     else {
104633                         generatedNames.add(baseName);
104634                     }
104635                     return baseName;
104636                 }
104637             }
104638             // Find the first unique 'name_n', where n is a positive number
104639             if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
104640                 baseName += "_";
104641             }
104642             var i = 1;
104643             while (true) {
104644                 var generatedName = baseName + i;
104645                 if (checkFn(generatedName)) {
104646                     if (scoped) {
104647                         reserveNameInNestedScopes(generatedName);
104648                     }
104649                     else {
104650                         generatedNames.add(generatedName);
104651                     }
104652                     return generatedName;
104653                 }
104654                 i++;
104655             }
104656         }
104657         function makeFileLevelOptimisticUniqueName(name) {
104658             return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true);
104659         }
104660         /**
104661          * Generates a unique name for a ModuleDeclaration or EnumDeclaration.
104662          */
104663         function generateNameForModuleOrEnum(node) {
104664             var name = getTextOfNode(node.name);
104665             // Use module/enum name itself if it is unique, otherwise make a unique variation
104666             return isUniqueLocalName(name, node) ? name : makeUniqueName(name);
104667         }
104668         /**
104669          * Generates a unique name for an ImportDeclaration or ExportDeclaration.
104670          */
104671         function generateNameForImportOrExportDeclaration(node) {
104672             var expr = ts.getExternalModuleName(node); // TODO: GH#18217
104673             var baseName = ts.isStringLiteral(expr) ?
104674                 ts.makeIdentifierFromModuleName(expr.text) : "module";
104675             return makeUniqueName(baseName);
104676         }
104677         /**
104678          * Generates a unique name for a default export.
104679          */
104680         function generateNameForExportDefault() {
104681             return makeUniqueName("default");
104682         }
104683         /**
104684          * Generates a unique name for a class expression.
104685          */
104686         function generateNameForClassExpression() {
104687             return makeUniqueName("class");
104688         }
104689         function generateNameForMethodOrAccessor(node) {
104690             if (ts.isIdentifier(node.name)) {
104691                 return generateNameCached(node.name);
104692             }
104693             return makeTempVariableName(0 /* Auto */);
104694         }
104695         /**
104696          * Generates a unique name from a node.
104697          */
104698         function generateNameForNode(node, flags) {
104699             switch (node.kind) {
104700                 case 78 /* Identifier */:
104701                     return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
104702                 case 256 /* ModuleDeclaration */:
104703                 case 255 /* EnumDeclaration */:
104704                     return generateNameForModuleOrEnum(node);
104705                 case 261 /* ImportDeclaration */:
104706                 case 267 /* ExportDeclaration */:
104707                     return generateNameForImportOrExportDeclaration(node);
104708                 case 251 /* FunctionDeclaration */:
104709                 case 252 /* ClassDeclaration */:
104710                 case 266 /* ExportAssignment */:
104711                     return generateNameForExportDefault();
104712                 case 221 /* ClassExpression */:
104713                     return generateNameForClassExpression();
104714                 case 165 /* MethodDeclaration */:
104715                 case 167 /* GetAccessor */:
104716                 case 168 /* SetAccessor */:
104717                     return generateNameForMethodOrAccessor(node);
104718                 case 158 /* ComputedPropertyName */:
104719                     return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true);
104720                 default:
104721                     return makeTempVariableName(0 /* Auto */);
104722             }
104723         }
104724         /**
104725          * Generates a unique identifier for a node.
104726          */
104727         function makeName(name) {
104728             switch (name.autoGenerateFlags & 7 /* KindMask */) {
104729                 case 1 /* Auto */:
104730                     return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
104731                 case 2 /* Loop */:
104732                     return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
104733                 case 3 /* Unique */:
104734                     return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
104735             }
104736             return ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
104737         }
104738         /**
104739          * Gets the node from which a name should be generated.
104740          */
104741         function getNodeForGeneratedName(name) {
104742             var autoGenerateId = name.autoGenerateId;
104743             var node = name;
104744             var original = node.original;
104745             while (original) {
104746                 node = original;
104747                 // if "node" is a different generated name (having a different
104748                 // "autoGenerateId"), use it and stop traversing.
104749                 if (ts.isIdentifier(node)
104750                     && !!(node.autoGenerateFlags & 4 /* Node */)
104751                     && node.autoGenerateId !== autoGenerateId) {
104752                     break;
104753                 }
104754                 original = node.original;
104755             }
104756             // otherwise, return the original node for the source;
104757             return node;
104758         }
104759         // Comments
104760         function pipelineEmitWithComments(hint, node) {
104761             ts.Debug.assert(lastNode === node || lastSubstitution === node);
104762             enterComment();
104763             hasWrittenComment = false;
104764             var emitFlags = ts.getEmitFlags(node);
104765             var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
104766             var isEmittedNode = node.kind !== 335 /* NotEmittedStatement */;
104767             // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
104768             // It is expensive to walk entire tree just to set one kind of node to have no comments.
104769             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
104770             var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */;
104771             // Save current container state on the stack.
104772             var savedContainerPos = containerPos;
104773             var savedContainerEnd = containerEnd;
104774             var savedDeclarationListContainerEnd = declarationListContainerEnd;
104775             if ((pos > 0 || end > 0) && pos !== end) {
104776                 // Emit leading comments if the position is not synthesized and the node
104777                 // has not opted out from emitting leading comments.
104778                 if (!skipLeadingComments) {
104779                     emitLeadingComments(pos, isEmittedNode);
104780                 }
104781                 if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) {
104782                     // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments.
104783                     containerPos = pos;
104784                 }
104785                 if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) {
104786                     // As above.
104787                     containerEnd = end;
104788                     // To avoid invalid comment emit in a down-level binding pattern, we
104789                     // keep track of the last declaration list container's end
104790                     if (node.kind === 250 /* VariableDeclarationList */) {
104791                         declarationListContainerEnd = end;
104792                     }
104793                 }
104794             }
104795             ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
104796             exitComment();
104797             var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node);
104798             if (emitFlags & 2048 /* NoNestedComments */) {
104799                 commentsDisabled = true;
104800                 pipelinePhase(hint, node);
104801                 commentsDisabled = false;
104802             }
104803             else {
104804                 pipelinePhase(hint, node);
104805             }
104806             enterComment();
104807             ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment);
104808             if ((pos > 0 || end > 0) && pos !== end) {
104809                 // Restore previous container state.
104810                 containerPos = savedContainerPos;
104811                 containerEnd = savedContainerEnd;
104812                 declarationListContainerEnd = savedDeclarationListContainerEnd;
104813                 // Emit trailing comments if the position is not synthesized and the node
104814                 // has not opted out from emitting leading comments and is an emitted node.
104815                 if (!skipTrailingComments && isEmittedNode) {
104816                     emitTrailingComments(end);
104817                 }
104818             }
104819             exitComment();
104820             ts.Debug.assert(lastNode === node || lastSubstitution === node);
104821         }
104822         function emitLeadingSynthesizedComment(comment) {
104823             if (comment.hasLeadingNewline || comment.kind === 2 /* SingleLineCommentTrivia */) {
104824                 writer.writeLine();
104825             }
104826             writeSynthesizedComment(comment);
104827             if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
104828                 writer.writeLine();
104829             }
104830             else {
104831                 writer.writeSpace(" ");
104832             }
104833         }
104834         function emitTrailingSynthesizedComment(comment) {
104835             if (!writer.isAtStartOfLine()) {
104836                 writer.writeSpace(" ");
104837             }
104838             writeSynthesizedComment(comment);
104839             if (comment.hasTrailingNewLine) {
104840                 writer.writeLine();
104841             }
104842         }
104843         function writeSynthesizedComment(comment) {
104844             var text = formatSynthesizedComment(comment);
104845             var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined;
104846             ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
104847         }
104848         function formatSynthesizedComment(comment) {
104849             return comment.kind === 3 /* MultiLineCommentTrivia */
104850                 ? "/*" + comment.text + "*/"
104851                 : "//" + comment.text;
104852         }
104853         function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
104854             enterComment();
104855             var pos = detachedRange.pos, end = detachedRange.end;
104856             var emitFlags = ts.getEmitFlags(node);
104857             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
104858             var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
104859             if (!skipLeadingComments) {
104860                 emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
104861             }
104862             exitComment();
104863             if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) {
104864                 commentsDisabled = true;
104865                 emitCallback(node);
104866                 commentsDisabled = false;
104867             }
104868             else {
104869                 emitCallback(node);
104870             }
104871             enterComment();
104872             if (!skipTrailingComments) {
104873                 emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
104874                 if (hasWrittenComment && !writer.isAtStartOfLine()) {
104875                     writer.writeLine();
104876                 }
104877             }
104878             exitComment();
104879         }
104880         function emitLeadingComments(pos, isEmittedNode) {
104881             hasWrittenComment = false;
104882             if (isEmittedNode) {
104883                 if (pos === 0 && (currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.isDeclarationFile)) {
104884                     forEachLeadingCommentToEmit(pos, emitNonTripleSlashLeadingComment);
104885                 }
104886                 else {
104887                     forEachLeadingCommentToEmit(pos, emitLeadingComment);
104888                 }
104889             }
104890             else if (pos === 0) {
104891                 // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
104892                 // unless it is a triple slash comment at the top of the file.
104893                 // For Example:
104894                 //      /// <reference-path ...>
104895                 //      declare var x;
104896                 //      /// <reference-path ...>
104897                 //      interface F {}
104898                 //  The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
104899                 forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
104900             }
104901         }
104902         function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
104903             if (isTripleSlashComment(commentPos, commentEnd)) {
104904                 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
104905             }
104906         }
104907         function emitNonTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
104908             if (!isTripleSlashComment(commentPos, commentEnd)) {
104909                 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
104910             }
104911         }
104912         function shouldWriteComment(text, pos) {
104913             if (printerOptions.onlyPrintJsDocStyle) {
104914                 return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos));
104915             }
104916             return true;
104917         }
104918         function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
104919             if (!shouldWriteComment(currentSourceFile.text, commentPos))
104920                 return;
104921             if (!hasWrittenComment) {
104922                 ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos);
104923                 hasWrittenComment = true;
104924             }
104925             // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
104926             emitPos(commentPos);
104927             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
104928             emitPos(commentEnd);
104929             if (hasTrailingNewLine) {
104930                 writer.writeLine();
104931             }
104932             else if (kind === 3 /* MultiLineCommentTrivia */) {
104933                 writer.writeSpace(" ");
104934             }
104935         }
104936         function emitLeadingCommentsOfPosition(pos) {
104937             if (commentsDisabled || pos === -1) {
104938                 return;
104939             }
104940             emitLeadingComments(pos, /*isEmittedNode*/ true);
104941         }
104942         function emitTrailingComments(pos) {
104943             forEachTrailingCommentToEmit(pos, emitTrailingComment);
104944         }
104945         function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) {
104946             if (!shouldWriteComment(currentSourceFile.text, commentPos))
104947                 return;
104948             // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
104949             if (!writer.isAtStartOfLine()) {
104950                 writer.writeSpace(" ");
104951             }
104952             emitPos(commentPos);
104953             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
104954             emitPos(commentEnd);
104955             if (hasTrailingNewLine) {
104956                 writer.writeLine();
104957             }
104958         }
104959         function emitTrailingCommentsOfPosition(pos, prefixSpace, forceNoNewline) {
104960             if (commentsDisabled) {
104961                 return;
104962             }
104963             enterComment();
104964             forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : forceNoNewline ? emitTrailingCommentOfPositionNoNewline : emitTrailingCommentOfPosition);
104965             exitComment();
104966         }
104967         function emitTrailingCommentOfPositionNoNewline(commentPos, commentEnd, kind) {
104968             // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
104969             emitPos(commentPos);
104970             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
104971             emitPos(commentEnd);
104972             if (kind === 2 /* SingleLineCommentTrivia */) {
104973                 writer.writeLine(); // still write a newline for single-line comments, so closing tokens aren't written on the same line
104974             }
104975         }
104976         function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
104977             // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
104978             emitPos(commentPos);
104979             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
104980             emitPos(commentEnd);
104981             if (hasTrailingNewLine) {
104982                 writer.writeLine();
104983             }
104984             else {
104985                 writer.writeSpace(" ");
104986             }
104987         }
104988         function forEachLeadingCommentToEmit(pos, cb) {
104989             // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
104990             if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) {
104991                 if (hasDetachedComments(pos)) {
104992                     forEachLeadingCommentWithoutDetachedComments(cb);
104993                 }
104994                 else {
104995                     ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
104996                 }
104997             }
104998         }
104999         function forEachTrailingCommentToEmit(end, cb) {
105000             // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
105001             if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) {
105002                 ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb);
105003             }
105004         }
105005         function hasDetachedComments(pos) {
105006             return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos;
105007         }
105008         function forEachLeadingCommentWithoutDetachedComments(cb) {
105009             // get the leading comments from detachedPos
105010             var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos;
105011             if (detachedCommentsInfo.length - 1) {
105012                 detachedCommentsInfo.pop();
105013             }
105014             else {
105015                 detachedCommentsInfo = undefined;
105016             }
105017             ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
105018         }
105019         function emitDetachedCommentsAndUpdateCommentsInfo(range) {
105020             var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled);
105021             if (currentDetachedCommentInfo) {
105022                 if (detachedCommentsInfo) {
105023                     detachedCommentsInfo.push(currentDetachedCommentInfo);
105024                 }
105025                 else {
105026                     detachedCommentsInfo = [currentDetachedCommentInfo];
105027                 }
105028             }
105029         }
105030         function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) {
105031             if (!shouldWriteComment(currentSourceFile.text, commentPos))
105032                 return;
105033             emitPos(commentPos);
105034             ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
105035             emitPos(commentEnd);
105036         }
105037         /**
105038          * Determine if the given comment is a triple-slash
105039          *
105040          * @return true if the comment is a triple-slash comment else false
105041          */
105042         function isTripleSlashComment(commentPos, commentEnd) {
105043             return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
105044         }
105045         // Source Maps
105046         function getParsedSourceMap(node) {
105047             if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
105048                 node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
105049             }
105050             return node.parsedSourceMap || undefined;
105051         }
105052         function pipelineEmitWithSourceMap(hint, node) {
105053             ts.Debug.assert(lastNode === node || lastSubstitution === node);
105054             var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node);
105055             if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
105056                 pipelinePhase(hint, node);
105057             }
105058             else if (ts.isUnparsedNode(node)) {
105059                 var parsed = getParsedSourceMap(node.parent);
105060                 if (parsed && sourceMapGenerator) {
105061                     sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
105062                 }
105063                 pipelinePhase(hint, node);
105064             }
105065             else {
105066                 var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
105067                 var emitFlags = ts.getEmitFlags(node);
105068                 if (node.kind !== 335 /* NotEmittedStatement */
105069                     && (emitFlags & 16 /* NoLeadingSourceMap */) === 0
105070                     && pos >= 0) {
105071                     emitSourcePos(source, skipSourceTrivia(source, pos));
105072                 }
105073                 if (emitFlags & 64 /* NoNestedSourceMaps */) {
105074                     sourceMapsDisabled = true;
105075                     pipelinePhase(hint, node);
105076                     sourceMapsDisabled = false;
105077                 }
105078                 else {
105079                     pipelinePhase(hint, node);
105080                 }
105081                 if (node.kind !== 335 /* NotEmittedStatement */
105082                     && (emitFlags & 32 /* NoTrailingSourceMap */) === 0
105083                     && end >= 0) {
105084                     emitSourcePos(source, end);
105085                 }
105086             }
105087             ts.Debug.assert(lastNode === node || lastSubstitution === node);
105088         }
105089         /**
105090          * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source
105091          */
105092         function skipSourceTrivia(source, pos) {
105093             return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(source.text, pos);
105094         }
105095         /**
105096          * Emits a mapping.
105097          *
105098          * If the position is synthetic (undefined or a negative value), no mapping will be
105099          * created.
105100          *
105101          * @param pos The position.
105102          */
105103         function emitPos(pos) {
105104             if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) {
105105                 return;
105106             }
105107             var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character;
105108             sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, 
105109             /*nameIndex*/ undefined);
105110         }
105111         function emitSourcePos(source, pos) {
105112             if (source !== sourceMapSource) {
105113                 var savedSourceMapSource = sourceMapSource;
105114                 var savedSourceMapSourceIndex = sourceMapSourceIndex;
105115                 setSourceMapSource(source);
105116                 emitPos(pos);
105117                 resetSourceMapSource(savedSourceMapSource, savedSourceMapSourceIndex);
105118             }
105119             else {
105120                 emitPos(pos);
105121             }
105122         }
105123         /**
105124          * Emits a token of a node with possible leading and trailing source maps.
105125          *
105126          * @param node The node containing the token.
105127          * @param token The token to emit.
105128          * @param tokenStartPos The start pos of the token.
105129          * @param emitCallback The callback used to emit the token.
105130          */
105131         function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) {
105132             if (sourceMapsDisabled || node && ts.isInJsonFile(node)) {
105133                 return emitCallback(token, writer, tokenPos);
105134             }
105135             var emitNode = node && node.emitNode;
105136             var emitFlags = emitNode && emitNode.flags || 0 /* None */;
105137             var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
105138             var source = range && range.source || sourceMapSource;
105139             tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos);
105140             if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) {
105141                 emitSourcePos(source, tokenPos);
105142             }
105143             tokenPos = emitCallback(token, writer, tokenPos);
105144             if (range)
105145                 tokenPos = range.end;
105146             if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) {
105147                 emitSourcePos(source, tokenPos);
105148             }
105149             return tokenPos;
105150         }
105151         function setSourceMapSource(source) {
105152             if (sourceMapsDisabled) {
105153                 return;
105154             }
105155             sourceMapSource = source;
105156             if (source === mostRecentlyAddedSourceMapSource) {
105157                 // Fast path for when the new source map is the most recently added, in which case
105158                 // we use its captured index without going through the source map generator.
105159                 sourceMapSourceIndex = mostRecentlyAddedSourceMapSourceIndex;
105160                 return;
105161             }
105162             if (isJsonSourceMapSource(source)) {
105163                 return;
105164             }
105165             sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName);
105166             if (printerOptions.inlineSources) {
105167                 sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text);
105168             }
105169             mostRecentlyAddedSourceMapSource = source;
105170             mostRecentlyAddedSourceMapSourceIndex = sourceMapSourceIndex;
105171         }
105172         function resetSourceMapSource(source, sourceIndex) {
105173             sourceMapSource = source;
105174             sourceMapSourceIndex = sourceIndex;
105175         }
105176         function isJsonSourceMapSource(sourceFile) {
105177             return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */);
105178         }
105179     }
105180     ts.createPrinter = createPrinter;
105181     function createBracketsMap() {
105182         var brackets = [];
105183         brackets[1024 /* Braces */] = ["{", "}"];
105184         brackets[2048 /* Parenthesis */] = ["(", ")"];
105185         brackets[4096 /* AngleBrackets */] = ["<", ">"];
105186         brackets[8192 /* SquareBrackets */] = ["[", "]"];
105187         return brackets;
105188     }
105189     function getOpeningBracket(format) {
105190         return brackets[format & 15360 /* BracketsMask */][0];
105191     }
105192     function getClosingBracket(format) {
105193         return brackets[format & 15360 /* BracketsMask */][1];
105194     }
105195     // Flags enum to track count of temp variables and a few dedicated names
105196     var TempFlags;
105197     (function (TempFlags) {
105198         TempFlags[TempFlags["Auto"] = 0] = "Auto";
105199         TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
105200         TempFlags[TempFlags["_i"] = 268435456] = "_i";
105201     })(TempFlags || (TempFlags = {}));
105202 })(ts || (ts = {}));
105203 /* @internal */
105204 var ts;
105205 (function (ts) {
105206     function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) {
105207         if (!host.getDirectories || !host.readDirectory) {
105208             return undefined;
105209         }
105210         var cachedReadDirectoryResult = new ts.Map();
105211         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
105212         return {
105213             useCaseSensitiveFileNames: useCaseSensitiveFileNames,
105214             fileExists: fileExists,
105215             readFile: function (path, encoding) { return host.readFile(path, encoding); },
105216             directoryExists: host.directoryExists && directoryExists,
105217             getDirectories: getDirectories,
105218             readDirectory: readDirectory,
105219             createDirectory: host.createDirectory && createDirectory,
105220             writeFile: host.writeFile && writeFile,
105221             addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
105222             addOrDeleteFile: addOrDeleteFile,
105223             clearCache: clearCache,
105224             realpath: host.realpath && realpath
105225         };
105226         function toPath(fileName) {
105227             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
105228         }
105229         function getCachedFileSystemEntries(rootDirPath) {
105230             return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
105231         }
105232         function getCachedFileSystemEntriesForBaseDir(path) {
105233             return getCachedFileSystemEntries(ts.getDirectoryPath(path));
105234         }
105235         function getBaseNameOfFileName(fileName) {
105236             return ts.getBaseFileName(ts.normalizePath(fileName));
105237         }
105238         function createCachedFileSystemEntries(rootDir, rootDirPath) {
105239             var resultFromHost = {
105240                 files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
105241                 directories: host.getDirectories(rootDir) || []
105242             };
105243             cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
105244             return resultFromHost;
105245         }
105246         /**
105247          * If the readDirectory result was already cached, it returns that
105248          * Otherwise gets result from host and caches it.
105249          * The host request is done under try catch block to avoid caching incorrect result
105250          */
105251         function tryReadDirectory(rootDir, rootDirPath) {
105252             rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
105253             var cachedResult = getCachedFileSystemEntries(rootDirPath);
105254             if (cachedResult) {
105255                 return cachedResult;
105256             }
105257             try {
105258                 return createCachedFileSystemEntries(rootDir, rootDirPath);
105259             }
105260             catch (_e) {
105261                 // If there is exception to read directories, dont cache the result and direct the calls to host
105262                 ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
105263                 return undefined;
105264             }
105265         }
105266         function fileNameEqual(name1, name2) {
105267             return getCanonicalFileName(name1) === getCanonicalFileName(name2);
105268         }
105269         function hasEntry(entries, name) {
105270             return ts.some(entries, function (file) { return fileNameEqual(file, name); });
105271         }
105272         function updateFileSystemEntry(entries, baseName, isValid) {
105273             if (hasEntry(entries, baseName)) {
105274                 if (!isValid) {
105275                     return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); });
105276                 }
105277             }
105278             else if (isValid) {
105279                 return entries.push(baseName);
105280             }
105281         }
105282         function writeFile(fileName, data, writeByteOrderMark) {
105283             var path = toPath(fileName);
105284             var result = getCachedFileSystemEntriesForBaseDir(path);
105285             if (result) {
105286                 updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true);
105287             }
105288             return host.writeFile(fileName, data, writeByteOrderMark);
105289         }
105290         function fileExists(fileName) {
105291             var path = toPath(fileName);
105292             var result = getCachedFileSystemEntriesForBaseDir(path);
105293             return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) ||
105294                 host.fileExists(fileName);
105295         }
105296         function directoryExists(dirPath) {
105297             var path = toPath(dirPath);
105298             return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
105299         }
105300         function createDirectory(dirPath) {
105301             var path = toPath(dirPath);
105302             var result = getCachedFileSystemEntriesForBaseDir(path);
105303             var baseFileName = getBaseNameOfFileName(dirPath);
105304             if (result) {
105305                 updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true);
105306             }
105307             host.createDirectory(dirPath);
105308         }
105309         function getDirectories(rootDir) {
105310             var rootDirPath = toPath(rootDir);
105311             var result = tryReadDirectory(rootDir, rootDirPath);
105312             if (result) {
105313                 return result.directories.slice();
105314             }
105315             return host.getDirectories(rootDir);
105316         }
105317         function readDirectory(rootDir, extensions, excludes, includes, depth) {
105318             var rootDirPath = toPath(rootDir);
105319             var result = tryReadDirectory(rootDir, rootDirPath);
105320             if (result) {
105321                 return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
105322             }
105323             return host.readDirectory(rootDir, extensions, excludes, includes, depth);
105324             function getFileSystemEntries(dir) {
105325                 var path = toPath(dir);
105326                 if (path === rootDirPath) {
105327                     return result;
105328                 }
105329                 return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
105330             }
105331         }
105332         function realpath(s) {
105333             return host.realpath ? host.realpath(s) : s;
105334         }
105335         function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
105336             var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
105337             if (existingResult) {
105338                 // Just clear the cache for now
105339                 // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated
105340                 clearCache();
105341                 return undefined;
105342             }
105343             var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath);
105344             if (!parentResult) {
105345                 return undefined;
105346             }
105347             // This was earlier a file (hence not in cached directory contents)
105348             // or we never cached the directory containing it
105349             if (!host.directoryExists) {
105350                 // Since host doesnt support directory exists, clear the cache as otherwise it might not be same
105351                 clearCache();
105352                 return undefined;
105353             }
105354             var baseName = getBaseNameOfFileName(fileOrDirectory);
105355             var fsQueryResult = {
105356                 fileExists: host.fileExists(fileOrDirectoryPath),
105357                 directoryExists: host.directoryExists(fileOrDirectoryPath)
105358             };
105359             if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) {
105360                 // Folder added or removed, clear the cache instead of updating the folder and its structure
105361                 clearCache();
105362             }
105363             else {
105364                 // No need to update the directory structure, just files
105365                 updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
105366             }
105367             return fsQueryResult;
105368         }
105369         function addOrDeleteFile(fileName, filePath, eventKind) {
105370             if (eventKind === ts.FileWatcherEventKind.Changed) {
105371                 return;
105372             }
105373             var parentResult = getCachedFileSystemEntriesForBaseDir(filePath);
105374             if (parentResult) {
105375                 updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created);
105376             }
105377         }
105378         function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) {
105379             updateFileSystemEntry(parentResult.files, baseName, fileExists);
105380         }
105381         function clearCache() {
105382             cachedReadDirectoryResult.clear();
105383         }
105384     }
105385     ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost;
105386     var ConfigFileProgramReloadLevel;
105387     (function (ConfigFileProgramReloadLevel) {
105388         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None";
105389         /** Update the file name list from the disk */
105390         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial";
105391         /** Reload completely by re-reading contents of config file from disk and updating program */
105392         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full";
105393     })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {}));
105394     /**
105395      * 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
105396      */
105397     function updateSharedExtendedConfigFileWatcher(projectPath, parsed, extendedConfigFilesMap, createExtendedConfigFileWatch, toPath) {
105398         var _a;
105399         var extendedConfigs = ts.arrayToMap(((_a = parsed === null || parsed === void 0 ? void 0 : parsed.options.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath);
105400         // remove project from all unrelated watchers
105401         extendedConfigFilesMap.forEach(function (watcher, extendedConfigFilePath) {
105402             if (!extendedConfigs.has(extendedConfigFilePath)) {
105403                 watcher.projects.delete(projectPath);
105404                 watcher.close();
105405             }
105406         });
105407         // Update the extended config files watcher
105408         extendedConfigs.forEach(function (extendedConfigFileName, extendedConfigFilePath) {
105409             var existing = extendedConfigFilesMap.get(extendedConfigFilePath);
105410             if (existing) {
105411                 existing.projects.add(projectPath);
105412             }
105413             else {
105414                 // start watching previously unseen extended config
105415                 extendedConfigFilesMap.set(extendedConfigFilePath, {
105416                     projects: new ts.Set([projectPath]),
105417                     fileWatcher: createExtendedConfigFileWatch(extendedConfigFileName, extendedConfigFilePath),
105418                     close: function () {
105419                         var existing = extendedConfigFilesMap.get(extendedConfigFilePath);
105420                         if (!existing || existing.projects.size !== 0)
105421                             return;
105422                         existing.fileWatcher.close();
105423                         extendedConfigFilesMap.delete(extendedConfigFilePath);
105424                     },
105425                 });
105426             }
105427         });
105428     }
105429     ts.updateSharedExtendedConfigFileWatcher = updateSharedExtendedConfigFileWatcher;
105430     /**
105431      * Updates the existing missing file watches with the new set of missing files after new program is created
105432      */
105433     function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) {
105434         var missingFilePaths = program.getMissingFilePaths();
105435         // TODO(rbuckton): Should be a `Set` but that requires changing the below code that uses `mutateMap`
105436         var newMissingFilePathMap = ts.arrayToMap(missingFilePaths, ts.identity, ts.returnTrue);
105437         // Update the missing file paths watcher
105438         ts.mutateMap(missingFileWatches, newMissingFilePathMap, {
105439             // Watch the missing files
105440             createNewValue: createMissingFileWatch,
105441             // Files that are no longer missing (e.g. because they are no longer required)
105442             // should no longer be watched.
105443             onDeleteValue: ts.closeFileWatcher
105444         });
105445     }
105446     ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch;
105447     /**
105448      * Updates the existing wild card directory watches with the new set of wild card directories from the config file
105449      * after new program is created because the config file was reloaded or program was created first time from the config file
105450      * Note that there is no need to call this function when the program is updated with additional files without reloading config files,
105451      * as wildcard directories wont change unless reloading config file
105452      */
105453     function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) {
105454         ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, {
105455             // Create new watch and recursive info
105456             createNewValue: createWildcardDirectoryWatcher,
105457             // Close existing watch thats not needed any more
105458             onDeleteValue: closeFileWatcherOf,
105459             // Close existing watch that doesnt match in the flags
105460             onExistingValue: updateWildcardDirectoryWatcher
105461         });
105462         function createWildcardDirectoryWatcher(directory, flags) {
105463             // Create new watch and recursive info
105464             return {
105465                 watcher: watchDirectory(directory, flags),
105466                 flags: flags
105467             };
105468         }
105469         function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) {
105470             // Watcher needs to be updated if the recursive flags dont match
105471             if (existingWatcher.flags === flags) {
105472                 return;
105473             }
105474             existingWatcher.watcher.close();
105475             existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags));
105476         }
105477     }
105478     ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories;
105479     /* @internal */
105480     function isIgnoredFileFromWildCardWatching(_a) {
105481         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;
105482         var newPath = ts.removeIgnoredPath(fileOrDirectoryPath);
105483         if (!newPath) {
105484             writeLog("Project: " + configFileName + " Detected ignored path: " + fileOrDirectory);
105485             return true;
105486         }
105487         fileOrDirectoryPath = newPath;
105488         if (fileOrDirectoryPath === watchedDirPath)
105489             return false;
105490         // If the the added or created file or directory is not supported file name, ignore the file
105491         // But when watched directory is added/removed, we need to reload the file list
105492         if (ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, options, extraFileExtensions)) {
105493             writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
105494             return true;
105495         }
105496         if (ts.isExcludedFile(fileOrDirectory, options.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames, currentDirectory)) {
105497             writeLog("Project: " + configFileName + " Detected excluded file: " + fileOrDirectory);
105498             return true;
105499         }
105500         if (!program)
105501             return false;
105502         // We want to ignore emit file check if file is not going to be emitted next to source file
105503         // In that case we follow config file inclusion rules
105504         if (options.outFile || options.outDir)
105505             return false;
105506         // File if emitted next to input needs to be ignored
105507         if (ts.fileExtensionIs(fileOrDirectoryPath, ".d.ts" /* Dts */)) {
105508             // If its declaration directory: its not ignored if not excluded by config
105509             if (options.declarationDir)
105510                 return false;
105511         }
105512         else if (!ts.fileExtensionIsOneOf(fileOrDirectoryPath, ts.supportedJSExtensions)) {
105513             return false;
105514         }
105515         // just check if sourceFile with the name exists
105516         var filePathWithoutExtension = ts.removeFileExtension(fileOrDirectoryPath);
105517         var realProgram = isBuilderProgram(program) ? program.getProgramOrUndefined() : program;
105518         if (hasSourceFile((filePathWithoutExtension + ".ts" /* Ts */)) ||
105519             hasSourceFile((filePathWithoutExtension + ".tsx" /* Tsx */))) {
105520             writeLog("Project: " + configFileName + " Detected output file: " + fileOrDirectory);
105521             return true;
105522         }
105523         return false;
105524         function hasSourceFile(file) {
105525             return realProgram ?
105526                 !!realProgram.getSourceFileByPath(file) :
105527                 program.getState().fileInfos.has(file);
105528         }
105529     }
105530     ts.isIgnoredFileFromWildCardWatching = isIgnoredFileFromWildCardWatching;
105531     function isBuilderProgram(program) {
105532         return !!program.getState;
105533     }
105534     function isEmittedFileOfProgram(program, file) {
105535         if (!program) {
105536             return false;
105537         }
105538         return program.isEmittedFile(file);
105539     }
105540     ts.isEmittedFileOfProgram = isEmittedFileOfProgram;
105541     var WatchLogLevel;
105542     (function (WatchLogLevel) {
105543         WatchLogLevel[WatchLogLevel["None"] = 0] = "None";
105544         WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly";
105545         WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose";
105546     })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {}));
105547     function getWatchFactory(host, watchLogLevel, log, getDetailWatchInfo) {
105548         ts.setSysLog(watchLogLevel === WatchLogLevel.Verbose ? log : ts.noop);
105549         var plainInvokeFactory = {
105550             watchFile: function (file, callback, pollingInterval, options) { return host.watchFile(file, callback, pollingInterval, options); },
105551             watchDirectory: function (directory, callback, flags, options) { return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options); },
105552         };
105553         var triggerInvokingFactory = watchLogLevel !== WatchLogLevel.None ?
105554             {
105555                 watchFile: createTriggerLoggingAddWatch("watchFile"),
105556                 watchDirectory: createTriggerLoggingAddWatch("watchDirectory")
105557             } :
105558             undefined;
105559         var factory = watchLogLevel === WatchLogLevel.Verbose ?
105560             {
105561                 watchFile: createFileWatcherWithLogging,
105562                 watchDirectory: createDirectoryWatcherWithLogging
105563             } :
105564             triggerInvokingFactory || plainInvokeFactory;
105565         var excludeWatcherFactory = watchLogLevel === WatchLogLevel.Verbose ?
105566             createExcludeWatcherWithLogging :
105567             ts.returnNoopFileWatcher;
105568         return {
105569             watchFile: createExcludeHandlingAddWatch("watchFile"),
105570             watchDirectory: createExcludeHandlingAddWatch("watchDirectory")
105571         };
105572         function createExcludeHandlingAddWatch(key) {
105573             return function (file, cb, flags, options, detailInfo1, detailInfo2) {
105574                 var _a;
105575                 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)) || "") ?
105576                     factory[key].call(/*thisArgs*/ undefined, file, cb, flags, options, detailInfo1, detailInfo2) :
105577                     excludeWatcherFactory(file, flags, options, detailInfo1, detailInfo2);
105578             };
105579         }
105580         function useCaseSensitiveFileNames() {
105581             return typeof host.useCaseSensitiveFileNames === "boolean" ?
105582                 host.useCaseSensitiveFileNames :
105583                 host.useCaseSensitiveFileNames();
105584         }
105585         function createExcludeWatcherWithLogging(file, flags, options, detailInfo1, detailInfo2) {
105586             log("ExcludeWatcher:: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
105587             return {
105588                 close: function () { return log("ExcludeWatcher:: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo)); }
105589             };
105590         }
105591         function createFileWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) {
105592             log("FileWatcher:: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
105593             var watcher = triggerInvokingFactory.watchFile(file, cb, flags, options, detailInfo1, detailInfo2);
105594             return {
105595                 close: function () {
105596                     log("FileWatcher:: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
105597                     watcher.close();
105598                 }
105599             };
105600         }
105601         function createDirectoryWatcherWithLogging(file, cb, flags, options, detailInfo1, detailInfo2) {
105602             var watchInfo = "DirectoryWatcher:: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
105603             log(watchInfo);
105604             var start = ts.timestamp();
105605             var watcher = triggerInvokingFactory.watchDirectory(file, cb, flags, options, detailInfo1, detailInfo2);
105606             var elapsed = ts.timestamp() - start;
105607             log("Elapsed:: " + elapsed + "ms " + watchInfo);
105608             return {
105609                 close: function () {
105610                     var watchInfo = "DirectoryWatcher:: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
105611                     log(watchInfo);
105612                     var start = ts.timestamp();
105613                     watcher.close();
105614                     var elapsed = ts.timestamp() - start;
105615                     log("Elapsed:: " + elapsed + "ms " + watchInfo);
105616                 }
105617             };
105618         }
105619         function createTriggerLoggingAddWatch(key) {
105620             return function (file, cb, flags, options, detailInfo1, detailInfo2) { return plainInvokeFactory[key].call(/*thisArgs*/ undefined, file, function () {
105621                 var args = [];
105622                 for (var _i = 0; _i < arguments.length; _i++) {
105623                     args[_i] = arguments[_i];
105624                 }
105625                 var triggerredInfo = (key === "watchFile" ? "FileWatcher" : "DirectoryWatcher") + ":: Triggered with " + args[0] + " " + (args[1] !== undefined ? args[1] : "") + ":: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
105626                 log(triggerredInfo);
105627                 var start = ts.timestamp();
105628                 cb.call.apply(cb, __spreadArray([/*thisArg*/ undefined], args));
105629                 var elapsed = ts.timestamp() - start;
105630                 log("Elapsed:: " + elapsed + "ms " + triggerredInfo);
105631             }, flags, options, detailInfo1, detailInfo2); };
105632         }
105633         function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo) {
105634             return "WatchInfo: " + file + " " + flags + " " + JSON.stringify(options) + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2);
105635         }
105636     }
105637     ts.getWatchFactory = getWatchFactory;
105638     function getFallbackOptions(options) {
105639         var fallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
105640         return {
105641             watchFile: fallbackPolling !== undefined ?
105642                 fallbackPolling :
105643                 ts.WatchFileKind.PriorityPollingInterval
105644         };
105645     }
105646     ts.getFallbackOptions = getFallbackOptions;
105647     function closeFileWatcherOf(objWithWatcher) {
105648         objWithWatcher.watcher.close();
105649     }
105650     ts.closeFileWatcherOf = closeFileWatcherOf;
105651 })(ts || (ts = {}));
105652 var ts;
105653 (function (ts) {
105654     function findConfigFile(searchPath, fileExists, configName) {
105655         if (configName === void 0) { configName = "tsconfig.json"; }
105656         return ts.forEachAncestorDirectory(searchPath, function (ancestor) {
105657             var fileName = ts.combinePaths(ancestor, configName);
105658             return fileExists(fileName) ? fileName : undefined;
105659         });
105660     }
105661     ts.findConfigFile = findConfigFile;
105662     function resolveTripleslashReference(moduleName, containingFile) {
105663         var basePath = ts.getDirectoryPath(containingFile);
105664         var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName);
105665         return ts.normalizePath(referencedFileName);
105666     }
105667     ts.resolveTripleslashReference = resolveTripleslashReference;
105668     /* @internal */
105669     function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
105670         var commonPathComponents;
105671         var failed = ts.forEach(fileNames, function (sourceFile) {
105672             // Each file contributes into common source file path
105673             var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory);
105674             sourcePathComponents.pop(); // The base file name is not part of the common directory path
105675             if (!commonPathComponents) {
105676                 // first file
105677                 commonPathComponents = sourcePathComponents;
105678                 return;
105679             }
105680             var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
105681             for (var i = 0; i < n; i++) {
105682                 if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
105683                     if (i === 0) {
105684                         // Failed to find any common path component
105685                         return true;
105686                     }
105687                     // New common path found that is 0 -> i-1
105688                     commonPathComponents.length = i;
105689                     break;
105690                 }
105691             }
105692             // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
105693             if (sourcePathComponents.length < commonPathComponents.length) {
105694                 commonPathComponents.length = sourcePathComponents.length;
105695             }
105696         });
105697         // A common path can not be found when paths span multiple drives on windows, for example
105698         if (failed) {
105699             return "";
105700         }
105701         if (!commonPathComponents) { // Can happen when all input files are .d.ts files
105702             return currentDirectory;
105703         }
105704         return ts.getPathFromPathComponents(commonPathComponents);
105705     }
105706     ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
105707     function createCompilerHost(options, setParentNodes) {
105708         return createCompilerHostWorker(options, setParentNodes);
105709     }
105710     ts.createCompilerHost = createCompilerHost;
105711     /*@internal*/
105712     // TODO(shkamat): update this after reworking ts build API
105713     function createCompilerHostWorker(options, setParentNodes, system) {
105714         if (system === void 0) { system = ts.sys; }
105715         var existingDirectories = new ts.Map();
105716         var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
105717         var computeHash = ts.maybeBind(system, system.createHash) || ts.generateDjb2Hash;
105718         function getSourceFile(fileName, languageVersion, onError) {
105719             var text;
105720             try {
105721                 ts.performance.mark("beforeIORead");
105722                 text = compilerHost.readFile(fileName);
105723                 ts.performance.mark("afterIORead");
105724                 ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
105725             }
105726             catch (e) {
105727                 if (onError) {
105728                     onError(e.message);
105729                 }
105730                 text = "";
105731             }
105732             return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
105733         }
105734         function directoryExists(directoryPath) {
105735             if (existingDirectories.has(directoryPath)) {
105736                 return true;
105737             }
105738             if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) {
105739                 existingDirectories.set(directoryPath, true);
105740                 return true;
105741             }
105742             return false;
105743         }
105744         function writeFile(fileName, data, writeByteOrderMark, onError) {
105745             try {
105746                 ts.performance.mark("beforeIOWrite");
105747                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
105748                 // the system.writeFile will do its own directory creation and
105749                 // the ensureDirectoriesExist call will always be redundant.
105750                 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); });
105751                 ts.performance.mark("afterIOWrite");
105752                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
105753             }
105754             catch (e) {
105755                 if (onError) {
105756                     onError(e.message);
105757                 }
105758             }
105759         }
105760         var outputFingerprints;
105761         function writeFileWorker(fileName, data, writeByteOrderMark) {
105762             if (!ts.isWatchSet(options) || !system.getModifiedTime) {
105763                 system.writeFile(fileName, data, writeByteOrderMark);
105764                 return;
105765             }
105766             if (!outputFingerprints) {
105767                 outputFingerprints = new ts.Map();
105768             }
105769             var hash = computeHash(data);
105770             var mtimeBefore = system.getModifiedTime(fileName);
105771             if (mtimeBefore) {
105772                 var fingerprint = outputFingerprints.get(fileName);
105773                 // If output has not been changed, and the file has no external modification
105774                 if (fingerprint &&
105775                     fingerprint.byteOrderMark === writeByteOrderMark &&
105776                     fingerprint.hash === hash &&
105777                     fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
105778                     return;
105779                 }
105780             }
105781             system.writeFile(fileName, data, writeByteOrderMark);
105782             var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime;
105783             outputFingerprints.set(fileName, {
105784                 hash: hash,
105785                 byteOrderMark: writeByteOrderMark,
105786                 mtime: mtimeAfter
105787             });
105788         }
105789         function getDefaultLibLocation() {
105790             return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
105791         }
105792         var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
105793         var realpath = system.realpath && (function (path) { return system.realpath(path); });
105794         var compilerHost = {
105795             getSourceFile: getSourceFile,
105796             getDefaultLibLocation: getDefaultLibLocation,
105797             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
105798             writeFile: writeFile,
105799             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
105800             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
105801             getCanonicalFileName: getCanonicalFileName,
105802             getNewLine: function () { return newLine; },
105803             fileExists: function (fileName) { return system.fileExists(fileName); },
105804             readFile: function (fileName) { return system.readFile(fileName); },
105805             trace: function (s) { return system.write(s + newLine); },
105806             directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
105807             getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
105808             getDirectories: function (path) { return system.getDirectories(path); },
105809             realpath: realpath,
105810             readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
105811             createDirectory: function (d) { return system.createDirectory(d); },
105812             createHash: ts.maybeBind(system, system.createHash)
105813         };
105814         return compilerHost;
105815     }
105816     ts.createCompilerHostWorker = createCompilerHostWorker;
105817     /*@internal*/
105818     function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) {
105819         var originalReadFile = host.readFile;
105820         var originalFileExists = host.fileExists;
105821         var originalDirectoryExists = host.directoryExists;
105822         var originalCreateDirectory = host.createDirectory;
105823         var originalWriteFile = host.writeFile;
105824         var readFileCache = new ts.Map();
105825         var fileExistsCache = new ts.Map();
105826         var directoryExistsCache = new ts.Map();
105827         var sourceFileCache = new ts.Map();
105828         var readFileWithCache = function (fileName) {
105829             var key = toPath(fileName);
105830             var value = readFileCache.get(key);
105831             if (value !== undefined)
105832                 return value !== false ? value : undefined;
105833             return setReadFileCache(key, fileName);
105834         };
105835         var setReadFileCache = function (key, fileName) {
105836             var newValue = originalReadFile.call(host, fileName);
105837             readFileCache.set(key, newValue !== undefined ? newValue : false);
105838             return newValue;
105839         };
105840         host.readFile = function (fileName) {
105841             var key = toPath(fileName);
105842             var value = readFileCache.get(key);
105843             if (value !== undefined)
105844                 return value !== false ? value : undefined; // could be .d.ts from output
105845             // Cache json or buildInfo
105846             if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
105847                 return originalReadFile.call(host, fileName);
105848             }
105849             return setReadFileCache(key, fileName);
105850         };
105851         var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
105852             var key = toPath(fileName);
105853             var value = sourceFileCache.get(key);
105854             if (value)
105855                 return value;
105856             var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
105857             if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
105858                 sourceFileCache.set(key, sourceFile);
105859             }
105860             return sourceFile;
105861         } : undefined;
105862         // fileExists for any kind of extension
105863         host.fileExists = function (fileName) {
105864             var key = toPath(fileName);
105865             var value = fileExistsCache.get(key);
105866             if (value !== undefined)
105867                 return value;
105868             var newValue = originalFileExists.call(host, fileName);
105869             fileExistsCache.set(key, !!newValue);
105870             return newValue;
105871         };
105872         if (originalWriteFile) {
105873             host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
105874                 var key = toPath(fileName);
105875                 fileExistsCache.delete(key);
105876                 var value = readFileCache.get(key);
105877                 if (value !== undefined && value !== data) {
105878                     readFileCache.delete(key);
105879                     sourceFileCache.delete(key);
105880                 }
105881                 else if (getSourceFileWithCache) {
105882                     var sourceFile = sourceFileCache.get(key);
105883                     if (sourceFile && sourceFile.text !== data) {
105884                         sourceFileCache.delete(key);
105885                     }
105886                 }
105887                 originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
105888             };
105889         }
105890         // directoryExists
105891         if (originalDirectoryExists && originalCreateDirectory) {
105892             host.directoryExists = function (directory) {
105893                 var key = toPath(directory);
105894                 var value = directoryExistsCache.get(key);
105895                 if (value !== undefined)
105896                     return value;
105897                 var newValue = originalDirectoryExists.call(host, directory);
105898                 directoryExistsCache.set(key, !!newValue);
105899                 return newValue;
105900             };
105901             host.createDirectory = function (directory) {
105902                 var key = toPath(directory);
105903                 directoryExistsCache.delete(key);
105904                 originalCreateDirectory.call(host, directory);
105905             };
105906         }
105907         return {
105908             originalReadFile: originalReadFile,
105909             originalFileExists: originalFileExists,
105910             originalDirectoryExists: originalDirectoryExists,
105911             originalCreateDirectory: originalCreateDirectory,
105912             originalWriteFile: originalWriteFile,
105913             getSourceFileWithCache: getSourceFileWithCache,
105914             readFileWithCache: readFileWithCache
105915         };
105916     }
105917     ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache;
105918     function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
105919         var diagnostics;
105920         diagnostics = ts.addRange(diagnostics, program.getConfigFileParsingDiagnostics());
105921         diagnostics = ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken));
105922         diagnostics = ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile, cancellationToken));
105923         diagnostics = ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
105924         diagnostics = ts.addRange(diagnostics, program.getSemanticDiagnostics(sourceFile, cancellationToken));
105925         if (ts.getEmitDeclarations(program.getCompilerOptions())) {
105926             diagnostics = ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
105927         }
105928         return ts.sortAndDeduplicateDiagnostics(diagnostics || ts.emptyArray);
105929     }
105930     ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
105931     function formatDiagnostics(diagnostics, host) {
105932         var output = "";
105933         for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) {
105934             var diagnostic = diagnostics_3[_i];
105935             output += formatDiagnostic(diagnostic, host);
105936         }
105937         return output;
105938     }
105939     ts.formatDiagnostics = formatDiagnostics;
105940     function formatDiagnostic(diagnostic, host) {
105941         var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
105942         if (diagnostic.file) {
105943             var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217
105944             var fileName = diagnostic.file.fileName;
105945             var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
105946             return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage;
105947         }
105948         return errorMessage;
105949     }
105950     ts.formatDiagnostic = formatDiagnostic;
105951     /** @internal */
105952     var ForegroundColorEscapeSequences;
105953     (function (ForegroundColorEscapeSequences) {
105954         ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
105955         ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
105956         ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
105957         ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
105958         ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
105959     })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {}));
105960     var gutterStyleSequence = "\u001b[7m";
105961     var gutterSeparator = " ";
105962     var resetEscapeSequence = "\u001b[0m";
105963     var ellipsis = "...";
105964     var halfIndent = "  ";
105965     var indent = "    ";
105966     function getCategoryFormat(category) {
105967         switch (category) {
105968             case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
105969             case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
105970             case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
105971             case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
105972         }
105973     }
105974     /** @internal */
105975     function formatColorAndReset(text, formatStyle) {
105976         return formatStyle + text + resetEscapeSequence;
105977     }
105978     ts.formatColorAndReset = formatColorAndReset;
105979     function formatCodeSpan(file, start, length, indent, squiggleColor, host) {
105980         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
105981         var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character;
105982         var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
105983         var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
105984         var gutterWidth = (lastLine + 1 + "").length;
105985         if (hasMoreThanFiveLines) {
105986             gutterWidth = Math.max(ellipsis.length, gutterWidth);
105987         }
105988         var context = "";
105989         for (var i = firstLine; i <= lastLine; i++) {
105990             context += host.getNewLine();
105991             // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
105992             // so we'll skip ahead to the second-to-last line.
105993             if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
105994                 context += indent + formatColorAndReset(ts.padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
105995                 i = lastLine - 1;
105996             }
105997             var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
105998             var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
105999             var lineContent = file.text.slice(lineStart, lineEnd);
106000             lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
106001             lineContent = lineContent.replace(/\t/g, " "); // convert tabs to single spaces
106002             // Output the gutter and the actual contents of the line.
106003             context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
106004             context += lineContent + host.getNewLine();
106005             // Output the gutter and the error span for the line using tildes.
106006             context += indent + formatColorAndReset(ts.padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
106007             context += squiggleColor;
106008             if (i === firstLine) {
106009                 // If we're on the last line, then limit it to the last character of the last line.
106010                 // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
106011                 var lastCharForLine = i === lastLine ? lastLineChar : undefined;
106012                 context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
106013                 context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
106014             }
106015             else if (i === lastLine) {
106016                 context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
106017             }
106018             else {
106019                 // Squiggle the entire line.
106020                 context += lineContent.replace(/./g, "~");
106021             }
106022             context += resetEscapeSequence;
106023         }
106024         return context;
106025     }
106026     /* @internal */
106027     function formatLocation(file, start, host, color) {
106028         if (color === void 0) { color = formatColorAndReset; }
106029         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217
106030         var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
106031         var output = "";
106032         output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
106033         output += ":";
106034         output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow);
106035         output += ":";
106036         output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
106037         return output;
106038     }
106039     ts.formatLocation = formatLocation;
106040     function formatDiagnosticsWithColorAndContext(diagnostics, host) {
106041         var output = "";
106042         for (var _i = 0, diagnostics_4 = diagnostics; _i < diagnostics_4.length; _i++) {
106043             var diagnostic = diagnostics_4[_i];
106044             if (diagnostic.file) {
106045                 var file = diagnostic.file, start = diagnostic.start;
106046                 output += formatLocation(file, start, host); // TODO: GH#18217
106047                 output += " - ";
106048             }
106049             output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
106050             output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
106051             output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
106052             if (diagnostic.file) {
106053                 output += host.getNewLine();
106054                 output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
106055             }
106056             if (diagnostic.relatedInformation) {
106057                 output += host.getNewLine();
106058                 for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
106059                     var _c = _b[_a], file = _c.file, start = _c.start, length_9 = _c.length, messageText = _c.messageText;
106060                     if (file) {
106061                         output += host.getNewLine();
106062                         output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
106063                         output += formatCodeSpan(file, start, length_9, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
106064                     }
106065                     output += host.getNewLine();
106066                     output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
106067                 }
106068             }
106069             output += host.getNewLine();
106070         }
106071         return output;
106072     }
106073     ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext;
106074     function flattenDiagnosticMessageText(diag, newLine, indent) {
106075         if (indent === void 0) { indent = 0; }
106076         if (ts.isString(diag)) {
106077             return diag;
106078         }
106079         else if (diag === undefined) {
106080             return "";
106081         }
106082         var result = "";
106083         if (indent) {
106084             result += newLine;
106085             for (var i = 0; i < indent; i++) {
106086                 result += "  ";
106087             }
106088         }
106089         result += diag.messageText;
106090         indent++;
106091         if (diag.next) {
106092             for (var _i = 0, _a = diag.next; _i < _a.length; _i++) {
106093                 var kid = _a[_i];
106094                 result += flattenDiagnosticMessageText(kid, newLine, indent);
106095             }
106096         }
106097         return result;
106098     }
106099     ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
106100     /* @internal */
106101     function loadWithLocalCache(names, containingFile, redirectedReference, loader) {
106102         if (names.length === 0) {
106103             return [];
106104         }
106105         var resolutions = [];
106106         var cache = new ts.Map();
106107         for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
106108             var name = names_2[_i];
106109             var result = void 0;
106110             if (cache.has(name)) {
106111                 result = cache.get(name);
106112             }
106113             else {
106114                 cache.set(name, result = loader(name, containingFile, redirectedReference));
106115             }
106116             resolutions.push(result);
106117         }
106118         return resolutions;
106119     }
106120     ts.loadWithLocalCache = loadWithLocalCache;
106121     /* @internal */
106122     function forEachResolvedProjectReference(resolvedProjectReferences, cb) {
106123         return forEachProjectReference(/*projectReferences*/ undefined, resolvedProjectReferences, function (resolvedRef, parent) { return resolvedRef && cb(resolvedRef, parent); });
106124     }
106125     ts.forEachResolvedProjectReference = forEachResolvedProjectReference;
106126     function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) {
106127         var seenResolvedRefs;
106128         return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined);
106129         function worker(projectReferences, resolvedProjectReferences, parent) {
106130             // Visit project references first
106131             if (cbRef) {
106132                 var result = cbRef(projectReferences, parent);
106133                 if (result) {
106134                     return result;
106135                 }
106136             }
106137             return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) {
106138                 if (resolvedRef && (seenResolvedRefs === null || seenResolvedRefs === void 0 ? void 0 : seenResolvedRefs.has(resolvedRef.sourceFile.path))) {
106139                     // ignore recursives
106140                     return undefined;
106141                 }
106142                 var result = cbResolvedRef(resolvedRef, parent, index);
106143                 if (result || !resolvedRef)
106144                     return result;
106145                 (seenResolvedRefs || (seenResolvedRefs = new ts.Set())).add(resolvedRef.sourceFile.path);
106146                 return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef);
106147             });
106148         }
106149     }
106150     /* @internal */
106151     ts.inferredTypesContainingFile = "__inferred type names__.ts";
106152     /*@internal*/
106153     function isReferencedFile(reason) {
106154         switch (reason === null || reason === void 0 ? void 0 : reason.kind) {
106155             case ts.FileIncludeKind.Import:
106156             case ts.FileIncludeKind.ReferenceFile:
106157             case ts.FileIncludeKind.TypeReferenceDirective:
106158             case ts.FileIncludeKind.LibReferenceDirective:
106159                 return true;
106160             default:
106161                 return false;
106162         }
106163     }
106164     ts.isReferencedFile = isReferencedFile;
106165     /*@internal*/
106166     function isReferenceFileLocation(location) {
106167         return location.pos !== undefined;
106168     }
106169     ts.isReferenceFileLocation = isReferenceFileLocation;
106170     /*@internal*/
106171     function getReferencedFileLocation(getSourceFileByPath, ref) {
106172         var _a, _b, _c;
106173         var _d, _e, _f, _g;
106174         var file = ts.Debug.checkDefined(getSourceFileByPath(ref.file));
106175         var kind = ref.kind, index = ref.index;
106176         var pos, end, packageId;
106177         switch (kind) {
106178             case ts.FileIncludeKind.Import:
106179                 var importLiteral = getModuleNameStringLiteralAt(file, index);
106180                 packageId = (_e = (_d = file.resolvedModules) === null || _d === void 0 ? void 0 : _d.get(importLiteral.text)) === null || _e === void 0 ? void 0 : _e.packageId;
106181                 if (importLiteral.pos === -1)
106182                     return { file: file, packageId: packageId, text: importLiteral.text };
106183                 pos = ts.skipTrivia(file.text, importLiteral.pos);
106184                 end = importLiteral.end;
106185                 break;
106186             case ts.FileIncludeKind.ReferenceFile:
106187                 (_a = file.referencedFiles[index], pos = _a.pos, end = _a.end);
106188                 break;
106189             case ts.FileIncludeKind.TypeReferenceDirective:
106190                 (_b = file.typeReferenceDirectives[index], pos = _b.pos, end = _b.end);
106191                 packageId = (_g = (_f = file.resolvedTypeReferenceDirectiveNames) === null || _f === void 0 ? void 0 : _f.get(ts.toFileNameLowerCase(file.typeReferenceDirectives[index].fileName))) === null || _g === void 0 ? void 0 : _g.packageId;
106192                 break;
106193             case ts.FileIncludeKind.LibReferenceDirective:
106194                 (_c = file.libReferenceDirectives[index], pos = _c.pos, end = _c.end);
106195                 break;
106196             default:
106197                 return ts.Debug.assertNever(kind);
106198         }
106199         return { file: file, pos: pos, end: end, packageId: packageId };
106200     }
106201     ts.getReferencedFileLocation = getReferencedFileLocation;
106202     /**
106203      * Determines if program structure is upto date or needs to be recreated
106204      */
106205     /* @internal */
106206     function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) {
106207         // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
106208         if (!program || (hasChangedAutomaticTypeDirectiveNames === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) {
106209             return false;
106210         }
106211         // If root file names don't match
106212         if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) {
106213             return false;
106214         }
106215         var seenResolvedRefs;
106216         // If project references don't match
106217         if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) {
106218             return false;
106219         }
106220         // If any file is not up-to-date, then the whole program is not up-to-date
106221         if (program.getSourceFiles().some(sourceFileNotUptoDate)) {
106222             return false;
106223         }
106224         // If any of the missing file paths are now created
106225         if (program.getMissingFilePaths().some(fileExists)) {
106226             return false;
106227         }
106228         var currentOptions = program.getCompilerOptions();
106229         // If the compilation settings do no match, then the program is not up-to-date
106230         if (!ts.compareDataObjects(currentOptions, newOptions)) {
106231             return false;
106232         }
106233         // If everything matches but the text of config file is changed,
106234         // error locations can change for program options, so update the program
106235         if (currentOptions.configFile && newOptions.configFile) {
106236             return currentOptions.configFile.text === newOptions.configFile.text;
106237         }
106238         return true;
106239         function sourceFileNotUptoDate(sourceFile) {
106240             return !sourceFileVersionUptoDate(sourceFile) ||
106241                 hasInvalidatedResolution(sourceFile.path);
106242         }
106243         function sourceFileVersionUptoDate(sourceFile) {
106244             return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName);
106245         }
106246         function projectReferenceUptoDate(oldRef, newRef, index) {
106247             if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) {
106248                 return false;
106249             }
106250             return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef);
106251         }
106252         function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) {
106253             if (oldResolvedRef) {
106254                 if (ts.contains(seenResolvedRefs, oldResolvedRef)) {
106255                     // Assume true
106256                     return true;
106257                 }
106258                 // If sourceFile for the oldResolvedRef existed, check the version for uptodate
106259                 if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) {
106260                     return false;
106261                 }
106262                 // Add to seen before checking the referenced paths of this config file
106263                 (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef);
106264                 // If child project references are upto date, this project reference is uptodate
106265                 return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) {
106266                     return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]);
106267                 });
106268             }
106269             // In old program, not able to resolve project reference path,
106270             // so if config file doesnt exist, it is uptodate.
106271             return !fileExists(resolveProjectReferencePath(oldRef));
106272         }
106273     }
106274     ts.isProgramUptoDate = isProgramUptoDate;
106275     function getConfigFileParsingDiagnostics(configFileParseResult) {
106276         return configFileParseResult.options.configFile ? __spreadArray(__spreadArray([], configFileParseResult.options.configFile.parseDiagnostics), configFileParseResult.errors) :
106277             configFileParseResult.errors;
106278     }
106279     ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
106280     /**
106281      * Determine if source file needs to be re-created even if its text hasn't changed
106282      */
106283     function shouldProgramCreateNewSourceFiles(program, newOptions) {
106284         if (!program)
106285             return false;
106286         // If any compiler options change, we can't reuse old source file even if version match
106287         // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`.
106288         var oldOptions = program.getCompilerOptions();
106289         return !!ts.sourceFileAffectingCompilerOptions.some(function (option) {
106290             return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option));
106291         });
106292     }
106293     function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
106294         return {
106295             rootNames: rootNames,
106296             options: options,
106297             host: host,
106298             oldProgram: oldProgram,
106299             configFileParsingDiagnostics: configFileParsingDiagnostics
106300         };
106301     }
106302     function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
106303         var _a, _b, _c;
106304         var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
106305         var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
106306         var oldProgram = createProgramOptions.oldProgram;
106307         var processingDefaultLibFiles;
106308         var processingOtherFiles;
106309         var files;
106310         var symlinks;
106311         var commonSourceDirectory;
106312         var diagnosticsProducingTypeChecker;
106313         var noDiagnosticsTypeChecker;
106314         var classifiableNames;
106315         var ambientModuleNameToUnmodifiedFileName = new ts.Map();
106316         var fileReasons = ts.createMultiMap();
106317         var cachedBindAndCheckDiagnosticsForFile = {};
106318         var cachedDeclarationDiagnosticsForFile = {};
106319         var resolvedTypeReferenceDirectives = new ts.Map();
106320         var fileProcessingDiagnostics;
106321         // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
106322         // This works as imported modules are discovered recursively in a depth first manner, specifically:
106323         // - For each root file, findSourceFile is called.
106324         // - This calls processImportedModules for each module imported in the source file.
106325         // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
106326         // As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
106327         // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
106328         var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
106329         var currentNodeModulesDepth = 0;
106330         // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
106331         // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
106332         var modulesWithElidedImports = new ts.Map();
106333         // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
106334         var sourceFilesFoundSearchingNodeModules = new ts.Map();
106335         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true);
106336         ts.performance.mark("beforeProgram");
106337         var host = createProgramOptions.host || createCompilerHost(options);
106338         var configParsingHost = parseConfigHostFromCompilerHostLike(host);
106339         var skipDefaultLib = options.noLib;
106340         var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
106341         var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
106342         var programDiagnostics = ts.createDiagnosticCollection();
106343         var currentDirectory = host.getCurrentDirectory();
106344         var supportedExtensions = ts.getSupportedExtensions(options);
106345         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
106346         // Map storing if there is emit blocking diagnostics for given input
106347         var hasEmitBlockingDiagnostics = new ts.Map();
106348         var _compilerOptionsObjectLiteralSyntax;
106349         var moduleResolutionCache;
106350         var actualResolveModuleNamesWorker;
106351         var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
106352         if (host.resolveModuleNames) {
106353             actualResolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.checkEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(function (resolved) {
106354                 // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
106355                 if (!resolved || resolved.extension !== undefined) {
106356                     return resolved;
106357                 }
106358                 var withExtension = ts.clone(resolved);
106359                 withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName);
106360                 return withExtension;
106361             }); };
106362         }
106363         else {
106364             moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options);
106365             var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217
106366             actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); };
106367         }
106368         var actualResolveTypeReferenceDirectiveNamesWorker;
106369         if (host.resolveTypeReferenceDirectives) {
106370             actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); };
106371         }
106372         else {
106373             var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217
106374             actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); };
106375         }
106376         // Map from a stringified PackageId to the source file with that id.
106377         // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile).
106378         // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around.
106379         var packageIdToSourceFile = new ts.Map();
106380         // Maps from a SourceFile's `.path` to the name of the package it was imported with.
106381         var sourceFileToPackageName = new ts.Map();
106382         // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it.
106383         var redirectTargetsMap = ts.createMultiMap();
106384         /**
106385          * map with
106386          * - SourceFile if present
106387          * - false if sourceFile missing for source of project reference redirect
106388          * - undefined otherwise
106389          */
106390         var filesByName = new ts.Map();
106391         var missingFilePaths;
106392         // stores 'filename -> file association' ignoring case
106393         // used to track cases when two file names differ only in casing
106394         var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? new ts.Map() : undefined;
106395         // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
106396         var resolvedProjectReferences;
106397         var projectReferenceRedirects;
106398         var mapFromFileToProjectReferenceRedirects;
106399         var mapFromToProjectReferenceRedirectSource;
106400         var useSourceOfProjectReferenceRedirect = !!((_a = host.useSourceOfProjectReferenceRedirect) === null || _a === void 0 ? void 0 : _a.call(host)) &&
106401             !options.disableSourceOfProjectReferenceRedirect;
106402         var _d = updateHostForUseSourceOfProjectReferenceRedirect({
106403             compilerHost: host,
106404             getSymlinkCache: getSymlinkCache,
106405             useSourceOfProjectReferenceRedirect: useSourceOfProjectReferenceRedirect,
106406             toPath: toPath,
106407             getResolvedProjectReferences: getResolvedProjectReferences,
106408             getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect,
106409             forEachResolvedProjectReference: forEachResolvedProjectReference
106410         }), onProgramCreateComplete = _d.onProgramCreateComplete, fileExists = _d.fileExists, directoryExists = _d.directoryExists;
106411         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram });
106412         var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
106413         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
106414         // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks
106415         // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`.
106416         var structureIsReused;
106417         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {});
106418         structureIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const
106419         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
106420         if (structureIsReused !== 2 /* Completely */) {
106421             processingDefaultLibFiles = [];
106422             processingOtherFiles = [];
106423             if (projectReferences) {
106424                 if (!resolvedProjectReferences) {
106425                     resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
106426                 }
106427                 if (rootNames.length) {
106428                     resolvedProjectReferences === null || resolvedProjectReferences === void 0 ? void 0 : resolvedProjectReferences.forEach(function (parsedRef, index) {
106429                         if (!parsedRef)
106430                             return;
106431                         var out = ts.outFile(parsedRef.commandLine.options);
106432                         if (useSourceOfProjectReferenceRedirect) {
106433                             if (out || ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
106434                                 for (var _i = 0, _a = parsedRef.commandLine.fileNames; _i < _a.length; _i++) {
106435                                     var fileName = _a[_i];
106436                                     processProjectReferenceFile(fileName, { kind: ts.FileIncludeKind.SourceFromProjectReference, index: index });
106437                                 }
106438                             }
106439                         }
106440                         else {
106441                             if (out) {
106442                                 processProjectReferenceFile(ts.changeExtension(out, ".d.ts"), { kind: ts.FileIncludeKind.OutputFromProjectReference, index: index });
106443                             }
106444                             else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
106445                                 var getCommonSourceDirectory_2 = ts.memoize(function () { return ts.getCommonSourceDirectoryOfConfig(parsedRef.commandLine, !host.useCaseSensitiveFileNames()); });
106446                                 for (var _b = 0, _c = parsedRef.commandLine.fileNames; _b < _c.length; _b++) {
106447                                     var fileName = _c[_b];
106448                                     if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
106449                                         processProjectReferenceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames(), getCommonSourceDirectory_2), { kind: ts.FileIncludeKind.OutputFromProjectReference, index: index });
106450                                     }
106451                                 }
106452                             }
106453                         }
106454                     });
106455                 }
106456             }
106457             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length });
106458             ts.forEach(rootNames, function (name, index) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.RootFile, index: index }); });
106459             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
106460             // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
106461             var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray;
106462             if (typeReferences.length) {
106463                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length });
106464                 // This containingFilename needs to match with the one used in managed-side
106465                 var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
106466                 var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile);
106467                 var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
106468                 for (var i = 0; i < typeReferences.length; i++) {
106469                     processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: ts.FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: (_b = resolutions[i]) === null || _b === void 0 ? void 0 : _b.packageId });
106470                 }
106471                 ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
106472             }
106473             // Do not process the default library if:
106474             //  - The '--noLib' flag is used.
106475             //  - A 'no-default-lib' reference comment is encountered in
106476             //      processing the root files.
106477             if (rootNames.length && !skipDefaultLib) {
106478                 // If '--lib' is not specified, include default library file according to '--target'
106479                 // otherwise, using options specified in '--lib' instead of '--target' default library file
106480                 var defaultLibraryFileName = getDefaultLibraryFileName();
106481                 if (!options.lib && defaultLibraryFileName) {
106482                     processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.LibFile });
106483                 }
106484                 else {
106485                     ts.forEach(options.lib, function (libFileName, index) {
106486                         processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.LibFile, index: index });
106487                     });
106488                 }
106489             }
106490             missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) {
106491                 var path = _a[0], file = _a[1];
106492                 return file === undefined ? path : undefined;
106493             }));
106494             files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles);
106495             processingDefaultLibFiles = undefined;
106496             processingOtherFiles = undefined;
106497         }
106498         ts.Debug.assert(!!missingFilePaths);
106499         // Release any files we have acquired in the old program but are
106500         // not part of the new program.
106501         if (oldProgram && host.onReleaseOldSourceFile) {
106502             var oldSourceFiles = oldProgram.getSourceFiles();
106503             for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) {
106504                 var oldSourceFile = oldSourceFiles_1[_i];
106505                 var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
106506                 if (shouldCreateNewSourceFile || !newFile ||
106507                     // old file wasn't redirect but new file is
106508                     (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) {
106509                     host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path));
106510                 }
106511             }
106512             oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) {
106513                 if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) {
106514                     host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false);
106515                 }
106516             });
106517         }
106518         // unconditionally set oldProgram to undefined to prevent it from being captured in closure
106519         oldProgram = undefined;
106520         var program = {
106521             getRootFileNames: function () { return rootNames; },
106522             getSourceFile: getSourceFile,
106523             getSourceFileByPath: getSourceFileByPath,
106524             getSourceFiles: function () { return files; },
106525             getMissingFilePaths: function () { return missingFilePaths; },
106526             getFilesByNameMap: function () { return filesByName; },
106527             getCompilerOptions: function () { return options; },
106528             getSyntacticDiagnostics: getSyntacticDiagnostics,
106529             getOptionsDiagnostics: getOptionsDiagnostics,
106530             getGlobalDiagnostics: getGlobalDiagnostics,
106531             getSemanticDiagnostics: getSemanticDiagnostics,
106532             getCachedSemanticDiagnostics: getCachedSemanticDiagnostics,
106533             getSuggestionDiagnostics: getSuggestionDiagnostics,
106534             getDeclarationDiagnostics: getDeclarationDiagnostics,
106535             getBindAndCheckDiagnostics: getBindAndCheckDiagnostics,
106536             getProgramDiagnostics: getProgramDiagnostics,
106537             getTypeChecker: getTypeChecker,
106538             getClassifiableNames: getClassifiableNames,
106539             getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker,
106540             getCommonSourceDirectory: getCommonSourceDirectory,
106541             emit: emit,
106542             getCurrentDirectory: function () { return currentDirectory; },
106543             getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); },
106544             getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); },
106545             getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
106546             getTypeCatalog: function () { return getDiagnosticsProducingTypeChecker().getTypeCatalog(); },
106547             getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
106548             getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); },
106549             getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); },
106550             getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
106551             getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
106552             isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
106553             isSourceFileDefaultLibrary: isSourceFileDefaultLibrary,
106554             dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker,
106555             getSourceFileFromReference: getSourceFileFromReference,
106556             getLibFileFromReference: getLibFileFromReference,
106557             sourceFileToPackageName: sourceFileToPackageName,
106558             redirectTargetsMap: redirectTargetsMap,
106559             isEmittedFile: isEmittedFile,
106560             getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
106561             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
106562             getProjectReferences: getProjectReferences,
106563             getResolvedProjectReferences: getResolvedProjectReferences,
106564             getProjectReferenceRedirect: getProjectReferenceRedirect,
106565             getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
106566             getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
106567             forEachResolvedProjectReference: forEachResolvedProjectReference,
106568             isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
106569             emitBuildInfo: emitBuildInfo,
106570             fileExists: fileExists,
106571             directoryExists: directoryExists,
106572             getSymlinkCache: getSymlinkCache,
106573             realpath: (_c = host.realpath) === null || _c === void 0 ? void 0 : _c.bind(host),
106574             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
106575             getFileIncludeReasons: function () { return fileReasons; },
106576             structureIsReused: structureIsReused,
106577         };
106578         onProgramCreateComplete();
106579         // Add file processingDiagnostics
106580         fileProcessingDiagnostics === null || fileProcessingDiagnostics === void 0 ? void 0 : fileProcessingDiagnostics.forEach(function (diagnostic) {
106581             switch (diagnostic.kind) {
106582                 case 1 /* FilePreprocessingFileExplainingDiagnostic */:
106583                     return programDiagnostics.add(createDiagnosticExplainingFile(diagnostic.file && getSourceFileByPath(diagnostic.file), diagnostic.fileProcessingReason, diagnostic.diagnostic, diagnostic.args || ts.emptyArray));
106584                 case 0 /* FilePreprocessingReferencedDiagnostic */:
106585                     var _a = getReferencedFileLocation(getSourceFileByPath, diagnostic.reason), file = _a.file, pos = _a.pos, end = _a.end;
106586                     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)));
106587                 default:
106588                     ts.Debug.assertNever(diagnostic);
106589             }
106590         });
106591         verifyCompilerOptions();
106592         ts.performance.mark("afterProgram");
106593         ts.performance.measure("Program", "beforeProgram", "afterProgram");
106594         ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
106595         return program;
106596         function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) {
106597             if (!moduleNames.length)
106598                 return ts.emptyArray;
106599             var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory);
106600             var redirectedReference = getRedirectReferenceForResolution(containingFile);
106601             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName });
106602             ts.performance.mark("beforeResolveModule");
106603             var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference);
106604             ts.performance.mark("afterResolveModule");
106605             ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule");
106606             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
106607             return result;
106608         }
106609         function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) {
106610             if (!typeDirectiveNames.length)
106611                 return [];
106612             var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile;
106613             var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined;
106614             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName });
106615             ts.performance.mark("beforeResolveTypeReference");
106616             var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference);
106617             ts.performance.mark("afterResolveTypeReference");
106618             ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference");
106619             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
106620             return result;
106621         }
106622         function getRedirectReferenceForResolution(file) {
106623             var redirect = getResolvedProjectReferenceToRedirect(file.originalFileName);
106624             if (redirect || !ts.fileExtensionIs(file.originalFileName, ".d.ts" /* Dts */))
106625                 return redirect;
106626             // The originalFileName could not be actual source file name if file found was d.ts from referecned project
106627             // 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
106628             var resultFromDts = getRedirectReferenceForResolutionFromSourceOfProject(file.originalFileName, file.path);
106629             if (resultFromDts)
106630                 return resultFromDts;
106631             // If preserveSymlinks is true, module resolution wont jump the symlink
106632             // but the resolved real path may be the .d.ts from project reference
106633             // Note:: Currently we try the real path only if the
106634             // file is from node_modules to avoid having to run real path on all file paths
106635             if (!host.realpath || !options.preserveSymlinks || !ts.stringContains(file.originalFileName, ts.nodeModulesPathPart))
106636                 return undefined;
106637             var realDeclarationFileName = host.realpath(file.originalFileName);
106638             var realDeclarationPath = toPath(realDeclarationFileName);
106639             return realDeclarationPath === file.path ? undefined : getRedirectReferenceForResolutionFromSourceOfProject(realDeclarationFileName, realDeclarationPath);
106640         }
106641         function getRedirectReferenceForResolutionFromSourceOfProject(fileName, filePath) {
106642             var source = getSourceOfProjectReferenceRedirect(fileName);
106643             if (ts.isString(source))
106644                 return getResolvedProjectReferenceToRedirect(source);
106645             if (!source)
106646                 return undefined;
106647             // Output of .d.ts file so return resolved ref that matches the out file name
106648             return forEachResolvedProjectReference(function (resolvedRef) {
106649                 var out = ts.outFile(resolvedRef.commandLine.options);
106650                 if (!out)
106651                     return undefined;
106652                 return toPath(out) === filePath ? resolvedRef : undefined;
106653             });
106654         }
106655         function compareDefaultLibFiles(a, b) {
106656             return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b));
106657         }
106658         function getDefaultLibFilePriority(a) {
106659             if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) {
106660                 var basename = ts.getBaseFileName(a.fileName);
106661                 if (basename === "lib.d.ts" || basename === "lib.es6.d.ts")
106662                     return 0;
106663                 var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts");
106664                 var index = ts.libs.indexOf(name);
106665                 if (index !== -1)
106666                     return index + 1;
106667             }
106668             return ts.libs.length + 2;
106669         }
106670         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
106671             return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
106672         }
106673         function toPath(fileName) {
106674             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
106675         }
106676         function getCommonSourceDirectory() {
106677             if (commonSourceDirectory === undefined) {
106678                 var emittedFiles_1 = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, program); });
106679                 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); });
106680             }
106681             return commonSourceDirectory;
106682         }
106683         function getClassifiableNames() {
106684             var _a;
106685             if (!classifiableNames) {
106686                 // Initialize a checker so that all our files are bound.
106687                 getTypeChecker();
106688                 classifiableNames = new ts.Set();
106689                 for (var _i = 0, files_2 = files; _i < files_2.length; _i++) {
106690                     var sourceFile = files_2[_i];
106691                     (_a = sourceFile.classifiableNames) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return classifiableNames.add(value); });
106692                 }
106693             }
106694             return classifiableNames;
106695         }
106696         function resolveModuleNamesReusingOldState(moduleNames, file) {
106697             if (structureIsReused === 0 /* Not */ && !file.ambientModuleNames.length) {
106698                 // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules,
106699                 // the best we can do is fallback to the default logic.
106700                 return resolveModuleNamesWorker(moduleNames, file, /*reusedNames*/ undefined);
106701             }
106702             var oldSourceFile = oldProgram && oldProgram.getSourceFile(file.fileName);
106703             if (oldSourceFile !== file && file.resolvedModules) {
106704                 // `file` was created for the new program.
106705                 //
106706                 // We only set `file.resolvedModules` via work from the current function,
106707                 // so it is defined iff we already called the current function on `file`.
106708                 // That call happened no later than the creation of the `file` object,
106709                 // which per above occurred during the current program creation.
106710                 // Since we assume the filesystem does not change during program creation,
106711                 // it is safe to reuse resolutions from the earlier call.
106712                 var result_14 = [];
106713                 for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
106714                     var moduleName = moduleNames_1[_i];
106715                     var resolvedModule = file.resolvedModules.get(moduleName);
106716                     result_14.push(resolvedModule);
106717                 }
106718                 return result_14;
106719             }
106720             // At this point, we know at least one of the following hold:
106721             // - file has local declarations for ambient modules
106722             // - old program state is available
106723             // With this information, we can infer some module resolutions without performing resolution.
106724             /** An ordered list of module names for which we cannot recover the resolution. */
106725             var unknownModuleNames;
106726             /**
106727              * The indexing of elements in this list matches that of `moduleNames`.
106728              *
106729              * Before combining results, result[i] is in one of the following states:
106730              * * undefined: needs to be recomputed,
106731              * * predictedToResolveToAmbientModuleMarker: known to be an ambient module.
106732              * Needs to be reset to undefined before returning,
106733              * * ResolvedModuleFull instance: can be reused.
106734              */
106735             var result;
106736             var reusedNames;
106737             /** A transient placeholder used to mark predicted resolution in the result list. */
106738             var predictedToResolveToAmbientModuleMarker = {};
106739             for (var i = 0; i < moduleNames.length; i++) {
106740                 var moduleName = moduleNames[i];
106741                 // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
106742                 if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
106743                     var oldResolvedModule = ts.getResolvedModule(oldSourceFile, moduleName);
106744                     if (oldResolvedModule) {
106745                         if (ts.isTraceEnabled(options, host)) {
106746                             ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory));
106747                         }
106748                         (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule;
106749                         (reusedNames || (reusedNames = [])).push(moduleName);
106750                         continue;
106751                     }
106752                 }
106753                 // We know moduleName resolves to an ambient module provided that moduleName:
106754                 // - is in the list of ambient modules locally declared in the current source file.
106755                 // - resolved to an ambient module in the old program whose declaration is in an unmodified file
106756                 //   (so the same module declaration will land in the new program)
106757                 var resolvesToAmbientModuleInNonModifiedFile = false;
106758                 if (ts.contains(file.ambientModuleNames, moduleName)) {
106759                     resolvesToAmbientModuleInNonModifiedFile = true;
106760                     if (ts.isTraceEnabled(options, host)) {
106761                         ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory));
106762                     }
106763                 }
106764                 else {
106765                     resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName);
106766                 }
106767                 if (resolvesToAmbientModuleInNonModifiedFile) {
106768                     (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker;
106769                 }
106770                 else {
106771                     // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result.
106772                     (unknownModuleNames || (unknownModuleNames = [])).push(moduleName);
106773                 }
106774             }
106775             var resolutions = unknownModuleNames && unknownModuleNames.length
106776                 ? resolveModuleNamesWorker(unknownModuleNames, file, reusedNames)
106777                 : ts.emptyArray;
106778             // Combine results of resolutions and predicted results
106779             if (!result) {
106780                 // There were no unresolved/ambient resolutions.
106781                 ts.Debug.assert(resolutions.length === moduleNames.length);
106782                 return resolutions;
106783             }
106784             var j = 0;
106785             for (var i = 0; i < result.length; i++) {
106786                 if (result[i]) {
106787                     // `result[i]` is either a `ResolvedModuleFull` or a marker.
106788                     // If it is the former, we can leave it as is.
106789                     if (result[i] === predictedToResolveToAmbientModuleMarker) {
106790                         result[i] = undefined; // TODO: GH#18217
106791                     }
106792                 }
106793                 else {
106794                     result[i] = resolutions[j];
106795                     j++;
106796                 }
106797             }
106798             ts.Debug.assert(j === resolutions.length);
106799             return result;
106800             // If we change our policy of rechecking failed lookups on each program create,
106801             // we should adjust the value returned here.
106802             function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) {
106803                 var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName);
106804                 var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName);
106805                 if (resolutionToFile && resolvedFile) {
106806                     // In the old program, we resolved to an ambient module that was in the same
106807                     //   place as we expected to find an actual module file.
106808                     // We actually need to return 'false' here even though this seems like a 'true' case
106809                     //   because the normal module resolution algorithm will find this anyway.
106810                     return false;
106811                 }
106812                 // at least one of declarations should come from non-modified source file
106813                 var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName);
106814                 if (!unmodifiedFile) {
106815                     return false;
106816                 }
106817                 if (ts.isTraceEnabled(options, host)) {
106818                     ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile);
106819                 }
106820                 return true;
106821             }
106822         }
106823         function canReuseProjectReferences() {
106824             return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, parent, index) {
106825                 var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
106826                 var newResolvedRef = parseProjectReferenceConfigFile(newRef);
106827                 if (oldResolvedRef) {
106828                     // Resolved project reference has gone missing or changed
106829                     return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile;
106830                 }
106831                 else {
106832                     // A previously-unresolved reference may be resolved now
106833                     return newResolvedRef !== undefined;
106834                 }
106835             }, function (oldProjectReferences, parent) {
106836                 // If array of references is changed, we cant resue old program
106837                 var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences;
106838                 return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo);
106839             });
106840         }
106841         function tryReuseStructureFromOldProgram() {
106842             var _a;
106843             if (!oldProgram) {
106844                 return 0 /* Not */;
106845             }
106846             // check properties that can affect structure of the program or module resolution strategy
106847             // if any of these properties has changed - structure cannot be reused
106848             var oldOptions = oldProgram.getCompilerOptions();
106849             if (ts.changesAffectModuleResolution(oldOptions, options)) {
106850                 return 0 /* Not */;
106851             }
106852             // there is an old program, check if we can reuse its structure
106853             var oldRootNames = oldProgram.getRootFileNames();
106854             if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
106855                 return 0 /* Not */;
106856             }
106857             if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
106858                 return 0 /* Not */;
106859             }
106860             // Check if any referenced project tsconfig files are different
106861             if (!canReuseProjectReferences()) {
106862                 return 0 /* Not */;
106863             }
106864             if (projectReferences) {
106865                 resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
106866             }
106867             // check if program source files has changed in the way that can affect structure of the program
106868             var newSourceFiles = [];
106869             var modifiedSourceFiles = [];
106870             structureIsReused = 2 /* Completely */;
106871             // If the missing file paths are now present, it can change the progam structure,
106872             // and hence cant reuse the structure.
106873             // This is same as how we dont reuse the structure if one of the file from old program is now missing
106874             if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) {
106875                 return 0 /* Not */;
106876             }
106877             var oldSourceFiles = oldProgram.getSourceFiles();
106878             var SeenPackageName;
106879             (function (SeenPackageName) {
106880                 SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists";
106881                 SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified";
106882             })(SeenPackageName || (SeenPackageName = {}));
106883             var seenPackageNames = new ts.Map();
106884             for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) {
106885                 var oldSourceFile = oldSourceFiles_2[_i];
106886                 var newSourceFile = host.getSourceFileByPath
106887                     ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile)
106888                     : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
106889                 if (!newSourceFile) {
106890                     return 0 /* Not */;
106891                 }
106892                 ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`");
106893                 var fileChanged = void 0;
106894                 if (oldSourceFile.redirectInfo) {
106895                     // We got `newSourceFile` by path, so it is actually for the unredirected file.
106896                     // This lets us know if the unredirected file has changed. If it has we should break the redirect.
106897                     if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) {
106898                         // Underlying file has changed. Might not redirect anymore. Must rebuild program.
106899                         return 0 /* Not */;
106900                     }
106901                     fileChanged = false;
106902                     newSourceFile = oldSourceFile; // Use the redirect.
106903                 }
106904                 else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) {
106905                     // If a redirected-to source file changes, the redirect may be broken.
106906                     if (newSourceFile !== oldSourceFile) {
106907                         return 0 /* Not */;
106908                     }
106909                     fileChanged = false;
106910                 }
106911                 else {
106912                     fileChanged = newSourceFile !== oldSourceFile;
106913                 }
106914                 // Since the project references havent changed, its right to set originalFileName and resolvedPath here
106915                 newSourceFile.path = oldSourceFile.path;
106916                 newSourceFile.originalFileName = oldSourceFile.originalFileName;
106917                 newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
106918                 newSourceFile.fileName = oldSourceFile.fileName;
106919                 var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
106920                 if (packageName !== undefined) {
106921                     // If there are 2 different source files for the same package name and at least one of them changes,
106922                     // they might become redirects. So we must rebuild the program.
106923                     var prevKind = seenPackageNames.get(packageName);
106924                     var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */;
106925                     if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) {
106926                         return 0 /* Not */;
106927                     }
106928                     seenPackageNames.set(packageName, newKind);
106929                 }
106930                 if (fileChanged) {
106931                     // The `newSourceFile` object was created for the new program.
106932                     if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) {
106933                         // 'lib' references has changed. Matches behavior in changesAffectModuleResolution
106934                         return 0 /* Not */;
106935                     }
106936                     if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
106937                         // value of no-default-lib has changed
106938                         // this will affect if default library is injected into the list of files
106939                         structureIsReused = 1 /* SafeModules */;
106940                     }
106941                     // check tripleslash references
106942                     if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
106943                         // tripleslash references has changed
106944                         structureIsReused = 1 /* SafeModules */;
106945                     }
106946                     // check imports and module augmentations
106947                     collectExternalModuleReferences(newSourceFile);
106948                     if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
106949                         // imports has changed
106950                         structureIsReused = 1 /* SafeModules */;
106951                     }
106952                     if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
106953                         // moduleAugmentations has changed
106954                         structureIsReused = 1 /* SafeModules */;
106955                     }
106956                     if ((oldSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */)) {
106957                         // dynamicImport has changed
106958                         structureIsReused = 1 /* SafeModules */;
106959                     }
106960                     if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
106961                         // 'types' references has changed
106962                         structureIsReused = 1 /* SafeModules */;
106963                     }
106964                     // tentatively approve the file
106965                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
106966                 }
106967                 else if (hasInvalidatedResolution(oldSourceFile.path)) {
106968                     // 'module/types' references could have changed
106969                     structureIsReused = 1 /* SafeModules */;
106970                     // add file to the modified list so that we will resolve it later
106971                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
106972                 }
106973                 // if file has passed all checks it should be safe to reuse it
106974                 newSourceFiles.push(newSourceFile);
106975             }
106976             if (structureIsReused !== 2 /* Completely */) {
106977                 return structureIsReused;
106978             }
106979             var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; });
106980             for (var _b = 0, oldSourceFiles_3 = oldSourceFiles; _b < oldSourceFiles_3.length; _b++) {
106981                 var oldFile = oldSourceFiles_3[_b];
106982                 if (!ts.contains(modifiedFiles, oldFile)) {
106983                     for (var _c = 0, _d = oldFile.ambientModuleNames; _c < _d.length; _c++) {
106984                         var moduleName = _d[_c];
106985                         ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName);
106986                     }
106987                 }
106988             }
106989             // try to verify results of module resolution
106990             for (var _e = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _e < modifiedSourceFiles_1.length; _e++) {
106991                 var _f = modifiedSourceFiles_1[_e], oldSourceFile = _f.oldFile, newSourceFile = _f.newFile;
106992                 var moduleNames = getModuleNames(newSourceFile);
106993                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile);
106994                 // ensure that module resolution results are still correct
106995                 var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo);
106996                 if (resolutionsChanged) {
106997                     structureIsReused = 1 /* SafeModules */;
106998                     newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions);
106999                 }
107000                 else {
107001                     newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
107002                 }
107003                 // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
107004                 var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
107005                 var typeReferenceResolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFile);
107006                 // ensure that types resolutions are still correct
107007                 var typeReferenceEesolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo);
107008                 if (typeReferenceEesolutionsChanged) {
107009                     structureIsReused = 1 /* SafeModules */;
107010                     newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, typeReferenceResolutions);
107011                 }
107012                 else {
107013                     newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
107014                 }
107015             }
107016             if (structureIsReused !== 2 /* Completely */) {
107017                 return structureIsReused;
107018             }
107019             if ((_a = host.hasChangedAutomaticTypeDirectiveNames) === null || _a === void 0 ? void 0 : _a.call(host)) {
107020                 return 1 /* SafeModules */;
107021             }
107022             missingFilePaths = oldProgram.getMissingFilePaths();
107023             // update fileName -> file mapping
107024             ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length);
107025             for (var _g = 0, newSourceFiles_1 = newSourceFiles; _g < newSourceFiles_1.length; _g++) {
107026                 var newSourceFile = newSourceFiles_1[_g];
107027                 filesByName.set(newSourceFile.path, newSourceFile);
107028             }
107029             var oldFilesByNameMap = oldProgram.getFilesByNameMap();
107030             oldFilesByNameMap.forEach(function (oldFile, path) {
107031                 if (!oldFile) {
107032                     filesByName.set(path, oldFile);
107033                     return;
107034                 }
107035                 if (oldFile.path === path) {
107036                     // Set the file as found during node modules search if it was found that way in old progra,
107037                     if (oldProgram.isSourceFileFromExternalLibrary(oldFile)) {
107038                         sourceFilesFoundSearchingNodeModules.set(oldFile.path, true);
107039                     }
107040                     return;
107041                 }
107042                 filesByName.set(path, filesByName.get(oldFile.path));
107043             });
107044             files = newSourceFiles;
107045             fileReasons = oldProgram.getFileIncludeReasons();
107046             fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
107047             resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
107048             sourceFileToPackageName = oldProgram.sourceFileToPackageName;
107049             redirectTargetsMap = oldProgram.redirectTargetsMap;
107050             return 2 /* Completely */;
107051         }
107052         function getEmitHost(writeFileCallback) {
107053             return {
107054                 getPrependNodes: getPrependNodes,
107055                 getCanonicalFileName: getCanonicalFileName,
107056                 getCommonSourceDirectory: program.getCommonSourceDirectory,
107057                 getCompilerOptions: program.getCompilerOptions,
107058                 getCurrentDirectory: function () { return currentDirectory; },
107059                 getNewLine: function () { return host.getNewLine(); },
107060                 getSourceFile: program.getSourceFile,
107061                 getSourceFileByPath: program.getSourceFileByPath,
107062                 getSourceFiles: program.getSourceFiles,
107063                 getLibFileFromReference: program.getLibFileFromReference,
107064                 isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
107065                 getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
107066                 getProjectReferenceRedirect: getProjectReferenceRedirect,
107067                 isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
107068                 getSymlinkCache: getSymlinkCache,
107069                 writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }),
107070                 isEmitBlocked: isEmitBlocked,
107071                 readFile: function (f) { return host.readFile(f); },
107072                 fileExists: function (f) {
107073                     // Use local caches
107074                     var path = toPath(f);
107075                     if (getSourceFileByPath(path))
107076                         return true;
107077                     if (ts.contains(missingFilePaths, path))
107078                         return false;
107079                     // Before falling back to the host
107080                     return host.fileExists(f);
107081                 },
107082                 useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
107083                 getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); },
107084                 getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); },
107085                 redirectTargetsMap: redirectTargetsMap,
107086                 getFileIncludeReasons: program.getFileIncludeReasons,
107087             };
107088         }
107089         function emitBuildInfo(writeFileCallback) {
107090             ts.Debug.assert(!ts.outFile(options));
107091             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("emit" /* Emit */, "emitBuildInfo", {}, /*separateBeginAndEnd*/ true);
107092             ts.performance.mark("beforeEmit");
107093             var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), 
107094             /*targetSourceFile*/ undefined, 
107095             /*transformers*/ ts.noTransformers, 
107096             /*emitOnlyDtsFiles*/ false, 
107097             /*onlyBuildInfo*/ true);
107098             ts.performance.mark("afterEmit");
107099             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
107100             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
107101             return emitResult;
107102         }
107103         function getResolvedProjectReferences() {
107104             return resolvedProjectReferences;
107105         }
107106         function getProjectReferences() {
107107             return projectReferences;
107108         }
107109         function getPrependNodes() {
107110             return createPrependNodes(projectReferences, function (_ref, index) { var _a; return (_a = resolvedProjectReferences[index]) === null || _a === void 0 ? void 0 : _a.commandLine; }, function (fileName) {
107111                 var path = toPath(fileName);
107112                 var sourceFile = getSourceFileByPath(path);
107113                 return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
107114             });
107115         }
107116         function isSourceFileFromExternalLibrary(file) {
107117             return !!sourceFilesFoundSearchingNodeModules.get(file.path);
107118         }
107119         function isSourceFileDefaultLibrary(file) {
107120             if (file.hasNoDefaultLib) {
107121                 return true;
107122             }
107123             if (!options.noLib) {
107124                 return false;
107125             }
107126             // If '--lib' is not specified, include default library file according to '--target'
107127             // otherwise, using options specified in '--lib' instead of '--target' default library file
107128             var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive;
107129             if (!options.lib) {
107130                 return equalityComparer(file.fileName, getDefaultLibraryFileName());
107131             }
107132             else {
107133                 return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); });
107134             }
107135         }
107136         function getDiagnosticsProducingTypeChecker() {
107137             return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
107138         }
107139         function dropDiagnosticsProducingTypeChecker() {
107140             diagnosticsProducingTypeChecker = undefined;
107141         }
107142         function getTypeChecker() {
107143             return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
107144         }
107145         function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) {
107146             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);
107147             var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); });
107148             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
107149             return result;
107150         }
107151         function isEmitBlocked(emitFileName) {
107152             return hasEmitBlockingDiagnostics.has(toPath(emitFileName));
107153         }
107154         function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit) {
107155             if (!forceDtsEmit) {
107156                 var result = handleNoEmitOptions(program, sourceFile, writeFileCallback, cancellationToken);
107157                 if (result)
107158                     return result;
107159             }
107160             // Create the emit resolver outside of the "emitTime" tracking code below.  That way
107161             // any cost associated with it (like type checking) are appropriate associated with
107162             // the type-checking counter.
107163             //
107164             // If the -out option is specified, we should not pass the source file to getEmitResolver.
107165             // This is because in the -out scenario all files need to be emitted, and therefore all
107166             // files need to be type checked. And the way to specify that all files need to be type
107167             // checked is to not pass the file to getEmitResolver.
107168             var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver(ts.outFile(options) ? undefined : sourceFile, cancellationToken);
107169             ts.performance.mark("beforeEmit");
107170             var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, ts.getTransformers(options, customTransformers, emitOnlyDtsFiles), emitOnlyDtsFiles, 
107171             /*onlyBuildInfo*/ false, forceDtsEmit);
107172             ts.performance.mark("afterEmit");
107173             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
107174             return emitResult;
107175         }
107176         function getSourceFile(fileName) {
107177             return getSourceFileByPath(toPath(fileName));
107178         }
107179         function getSourceFileByPath(path) {
107180             return filesByName.get(path) || undefined;
107181         }
107182         function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
107183             if (sourceFile) {
107184                 return getDiagnostics(sourceFile, cancellationToken);
107185             }
107186             return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) {
107187                 if (cancellationToken) {
107188                     cancellationToken.throwIfCancellationRequested();
107189                 }
107190                 return getDiagnostics(sourceFile, cancellationToken);
107191             }));
107192         }
107193         function getSyntacticDiagnostics(sourceFile, cancellationToken) {
107194             return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
107195         }
107196         function getSemanticDiagnostics(sourceFile, cancellationToken) {
107197             return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
107198         }
107199         function getCachedSemanticDiagnostics(sourceFile) {
107200             var _a;
107201             return sourceFile
107202                 ? (_a = cachedBindAndCheckDiagnosticsForFile.perFile) === null || _a === void 0 ? void 0 : _a.get(sourceFile.path)
107203                 : cachedBindAndCheckDiagnosticsForFile.allDiagnostics;
107204         }
107205         function getBindAndCheckDiagnostics(sourceFile, cancellationToken) {
107206             return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken);
107207         }
107208         function getProgramDiagnostics(sourceFile) {
107209             var _a;
107210             if (ts.skipTypeChecking(sourceFile, options, program)) {
107211                 return ts.emptyArray;
107212             }
107213             var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
107214             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
107215                 return programDiagnosticsInFile;
107216             }
107217             return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, programDiagnosticsInFile).diagnostics;
107218         }
107219         function getDeclarationDiagnostics(sourceFile, cancellationToken) {
107220             var options = program.getCompilerOptions();
107221             // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit)
107222             if (!sourceFile || ts.outFile(options)) {
107223                 return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
107224             }
107225             else {
107226                 return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
107227             }
107228         }
107229         function getSyntacticDiagnosticsForFile(sourceFile) {
107230             // For JavaScript files, we report semantic errors for using TypeScript-only
107231             // constructs from within a JavaScript file as syntactic errors.
107232             if (ts.isSourceFileJS(sourceFile)) {
107233                 if (!sourceFile.additionalSyntacticDiagnostics) {
107234                     sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
107235                 }
107236                 return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
107237             }
107238             return sourceFile.parseDiagnostics;
107239         }
107240         function runWithCancellationToken(func) {
107241             try {
107242                 return func();
107243             }
107244             catch (e) {
107245                 if (e instanceof ts.OperationCanceledException) {
107246                     // We were canceled while performing the operation.  Because our type checker
107247                     // might be a bad state, we need to throw it away.
107248                     //
107249                     // Note: we are overly aggressive here.  We do not actually *have* to throw away
107250                     // the "noDiagnosticsTypeChecker".  However, for simplicity, i'd like to keep
107251                     // the lifetimes of these two TypeCheckers the same.  Also, we generally only
107252                     // cancel when the user has made a change anyways.  And, in that case, we (the
107253                     // program instance) will get thrown away anyways.  So trying to keep one of
107254                     // these type checkers alive doesn't serve much purpose.
107255                     noDiagnosticsTypeChecker = undefined;
107256                     diagnosticsProducingTypeChecker = undefined;
107257                 }
107258                 throw e;
107259             }
107260         }
107261         function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
107262             return ts.concatenate(filterSemanticDiagnotics(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), options), getProgramDiagnostics(sourceFile));
107263         }
107264         function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) {
107265             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedBindAndCheckDiagnosticsForFile, getBindAndCheckDiagnosticsForFileNoCache);
107266         }
107267         function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
107268             return runWithCancellationToken(function () {
107269                 if (ts.skipTypeChecking(sourceFile, options, program)) {
107270                     return ts.emptyArray;
107271                 }
107272                 var typeChecker = getDiagnosticsProducingTypeChecker();
107273                 ts.Debug.assert(!!sourceFile.bindDiagnostics);
107274                 var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
107275                 var isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false;
107276                 // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
107277                 var includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
107278                     sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */);
107279                 var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
107280                 var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
107281                 return getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined);
107282             });
107283         }
107284         function getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics) {
107285             var _a;
107286             var allDiagnostics = [];
107287             for (var _i = 2; _i < arguments.length; _i++) {
107288                 allDiagnostics[_i - 2] = arguments[_i];
107289             }
107290             var flatDiagnostics = ts.flatten(allDiagnostics);
107291             if (!includeBindAndCheckDiagnostics || !((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
107292                 return flatDiagnostics;
107293             }
107294             var _b = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics), diagnostics = _b.diagnostics, directives = _b.directives;
107295             for (var _c = 0, _d = directives.getUnusedExpectations(); _c < _d.length; _c++) {
107296                 var errorExpectation = _d[_c];
107297                 diagnostics.push(ts.createDiagnosticForRange(sourceFile, errorExpectation.range, ts.Diagnostics.Unused_ts_expect_error_directive));
107298             }
107299             return diagnostics;
107300         }
107301         /**
107302          * Creates a map of comment directives along with the diagnostics immediately preceded by one of them.
107303          * Comments that match to any of those diagnostics are marked as used.
107304          */
107305         function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) {
107306             // Diagnostics are only reported if there is no comment directive preceding them
107307             // This will modify the directives map by marking "used" ones with a corresponding diagnostic
107308             var directives = ts.createCommentDirectivesMap(sourceFile, commentDirectives);
107309             var diagnostics = flatDiagnostics.filter(function (diagnostic) { return markPrecedingCommentDirectiveLine(diagnostic, directives) === -1; });
107310             return { diagnostics: diagnostics, directives: directives };
107311         }
107312         function getSuggestionDiagnostics(sourceFile, cancellationToken) {
107313             return runWithCancellationToken(function () {
107314                 return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
107315             });
107316         }
107317         /**
107318          * @returns The line index marked as preceding the diagnostic, or -1 if none was.
107319          */
107320         function markPrecedingCommentDirectiveLine(diagnostic, directives) {
107321             var file = diagnostic.file, start = diagnostic.start;
107322             if (!file) {
107323                 return -1;
107324             }
107325             // Start out with the line just before the text
107326             var lineStarts = ts.getLineStarts(file);
107327             var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line - 1; // TODO: GH#18217
107328             while (line >= 0) {
107329                 // As soon as that line is known to have a comment directive, use that
107330                 if (directives.markUsed(line)) {
107331                     return line;
107332                 }
107333                 // Stop searching if the line is not empty and not a comment
107334                 var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim();
107335                 if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) {
107336                     return -1;
107337                 }
107338                 line--;
107339             }
107340             return -1;
107341         }
107342         function getJSSyntacticDiagnosticsForFile(sourceFile) {
107343             return runWithCancellationToken(function () {
107344                 var diagnostics = [];
107345                 walk(sourceFile, sourceFile);
107346                 ts.forEachChildRecursively(sourceFile, walk, walkArray);
107347                 return diagnostics;
107348                 function walk(node, parent) {
107349                     // Return directly from the case if the given node doesnt want to visit each child
107350                     // Otherwise break to visit each child
107351                     switch (parent.kind) {
107352                         case 160 /* Parameter */:
107353                         case 163 /* PropertyDeclaration */:
107354                         case 165 /* MethodDeclaration */:
107355                             if (parent.questionToken === node) {
107356                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
107357                                 return "skip";
107358                             }
107359                         // falls through
107360                         case 164 /* MethodSignature */:
107361                         case 166 /* Constructor */:
107362                         case 167 /* GetAccessor */:
107363                         case 168 /* SetAccessor */:
107364                         case 208 /* FunctionExpression */:
107365                         case 251 /* FunctionDeclaration */:
107366                         case 209 /* ArrowFunction */:
107367                         case 249 /* VariableDeclaration */:
107368                             // type annotation
107369                             if (parent.type === node) {
107370                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files));
107371                                 return "skip";
107372                             }
107373                     }
107374                     switch (node.kind) {
107375                         case 262 /* ImportClause */:
107376                             if (node.isTypeOnly) {
107377                                 diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type"));
107378                                 return "skip";
107379                             }
107380                             break;
107381                         case 267 /* ExportDeclaration */:
107382                             if (node.isTypeOnly) {
107383                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type"));
107384                                 return "skip";
107385                             }
107386                             break;
107387                         case 260 /* ImportEqualsDeclaration */:
107388                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files));
107389                             return "skip";
107390                         case 266 /* ExportAssignment */:
107391                             if (node.isExportEquals) {
107392                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files));
107393                                 return "skip";
107394                             }
107395                             break;
107396                         case 286 /* HeritageClause */:
107397                             var heritageClause = node;
107398                             if (heritageClause.token === 116 /* ImplementsKeyword */) {
107399                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files));
107400                                 return "skip";
107401                             }
107402                             break;
107403                         case 253 /* InterfaceDeclaration */:
107404                             var interfaceKeyword = ts.tokenToString(117 /* InterfaceKeyword */);
107405                             ts.Debug.assertIsDefined(interfaceKeyword);
107406                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword));
107407                             return "skip";
107408                         case 256 /* ModuleDeclaration */:
107409                             var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(140 /* NamespaceKeyword */) : ts.tokenToString(139 /* ModuleKeyword */);
107410                             ts.Debug.assertIsDefined(moduleKeyword);
107411                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword));
107412                             return "skip";
107413                         case 254 /* TypeAliasDeclaration */:
107414                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files));
107415                             return "skip";
107416                         case 255 /* EnumDeclaration */:
107417                             var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(91 /* EnumKeyword */));
107418                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword));
107419                             return "skip";
107420                         case 225 /* NonNullExpression */:
107421                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files));
107422                             return "skip";
107423                         case 224 /* AsExpression */:
107424                             diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files));
107425                             return "skip";
107426                         case 206 /* TypeAssertionExpression */:
107427                             ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX.
107428                     }
107429                 }
107430                 function walkArray(nodes, parent) {
107431                     if (parent.decorators === nodes && !options.experimentalDecorators) {
107432                         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));
107433                     }
107434                     switch (parent.kind) {
107435                         case 252 /* ClassDeclaration */:
107436                         case 221 /* ClassExpression */:
107437                         case 165 /* MethodDeclaration */:
107438                         case 166 /* Constructor */:
107439                         case 167 /* GetAccessor */:
107440                         case 168 /* SetAccessor */:
107441                         case 208 /* FunctionExpression */:
107442                         case 251 /* FunctionDeclaration */:
107443                         case 209 /* ArrowFunction */:
107444                             // Check type parameters
107445                             if (nodes === parent.typeParameters) {
107446                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files));
107447                                 return "skip";
107448                             }
107449                         // falls through
107450                         case 232 /* VariableStatement */:
107451                             // Check modifiers
107452                             if (nodes === parent.modifiers) {
107453                                 checkModifiers(parent.modifiers, parent.kind === 232 /* VariableStatement */);
107454                                 return "skip";
107455                             }
107456                             break;
107457                         case 163 /* PropertyDeclaration */:
107458                             // Check modifiers of property declaration
107459                             if (nodes === parent.modifiers) {
107460                                 for (var _i = 0, _a = nodes; _i < _a.length; _i++) {
107461                                     var modifier = _a[_i];
107462                                     if (modifier.kind !== 123 /* StaticKeyword */) {
107463                                         diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
107464                                     }
107465                                 }
107466                                 return "skip";
107467                             }
107468                             break;
107469                         case 160 /* Parameter */:
107470                             // Check modifiers of parameter declaration
107471                             if (nodes === parent.modifiers) {
107472                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files));
107473                                 return "skip";
107474                             }
107475                             break;
107476                         case 203 /* CallExpression */:
107477                         case 204 /* NewExpression */:
107478                         case 223 /* ExpressionWithTypeArguments */:
107479                         case 274 /* JsxSelfClosingElement */:
107480                         case 275 /* JsxOpeningElement */:
107481                         case 205 /* TaggedTemplateExpression */:
107482                             // Check type arguments
107483                             if (nodes === parent.typeArguments) {
107484                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files));
107485                                 return "skip";
107486                             }
107487                             break;
107488                     }
107489                 }
107490                 function checkModifiers(modifiers, isConstValid) {
107491                     for (var _i = 0, modifiers_2 = modifiers; _i < modifiers_2.length; _i++) {
107492                         var modifier = modifiers_2[_i];
107493                         switch (modifier.kind) {
107494                             case 84 /* ConstKeyword */:
107495                                 if (isConstValid) {
107496                                     continue;
107497                                 }
107498                             // to report error,
107499                             // falls through
107500                             case 122 /* PublicKeyword */:
107501                             case 120 /* PrivateKeyword */:
107502                             case 121 /* ProtectedKeyword */:
107503                             case 142 /* ReadonlyKeyword */:
107504                             case 133 /* DeclareKeyword */:
107505                             case 125 /* AbstractKeyword */:
107506                                 diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
107507                                 break;
107508                             // These are all legal modifiers.
107509                             case 123 /* StaticKeyword */:
107510                             case 92 /* ExportKeyword */:
107511                             case 87 /* DefaultKeyword */:
107512                         }
107513                     }
107514                 }
107515                 function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) {
107516                     var start = nodes.pos;
107517                     return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
107518                 }
107519                 // Since these are syntactic diagnostics, parent might not have been set
107520                 // this means the sourceFile cannot be infered from the node
107521                 function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
107522                     return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
107523                 }
107524             });
107525         }
107526         function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
107527             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
107528         }
107529         function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
107530             return runWithCancellationToken(function () {
107531                 var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
107532                 // Don't actually write any files since we're just getting diagnostics.
107533                 return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile) || ts.emptyArray;
107534             });
107535         }
107536         function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
107537             var _a;
107538             var cachedResult = sourceFile
107539                 ? (_a = cache.perFile) === null || _a === void 0 ? void 0 : _a.get(sourceFile.path)
107540                 : cache.allDiagnostics;
107541             if (cachedResult) {
107542                 return cachedResult;
107543             }
107544             var result = getDiagnostics(sourceFile, cancellationToken);
107545             if (sourceFile) {
107546                 (cache.perFile || (cache.perFile = new ts.Map())).set(sourceFile.path, result);
107547             }
107548             else {
107549                 cache.allDiagnostics = result;
107550             }
107551             return result;
107552         }
107553         function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
107554             return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
107555         }
107556         function getOptionsDiagnostics() {
107557             return ts.sortAndDeduplicateDiagnostics(ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile()));
107558         }
107559         function getOptionsDiagnosticsOfConfigFile() {
107560             if (!options.configFile) {
107561                 return ts.emptyArray;
107562             }
107563             var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName);
107564             forEachResolvedProjectReference(function (resolvedRef) {
107565                 diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName));
107566             });
107567             return diagnostics;
107568         }
107569         function getGlobalDiagnostics() {
107570             return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray;
107571         }
107572         function getConfigFileParsingDiagnostics() {
107573             return configFileParsingDiagnostics || ts.emptyArray;
107574         }
107575         function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib, reason) {
107576             processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined, reason);
107577         }
107578         function fileReferenceIsEqualTo(a, b) {
107579             return a.fileName === b.fileName;
107580         }
107581         function moduleNameIsEqualTo(a, b) {
107582             return a.kind === 78 /* Identifier */
107583                 ? b.kind === 78 /* Identifier */ && a.escapedText === b.escapedText
107584                 : b.kind === 10 /* StringLiteral */ && a.text === b.text;
107585         }
107586         function createSyntheticImport(text, file) {
107587             var externalHelpersModuleReference = ts.factory.createStringLiteral(text);
107588             var importDecl = ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
107589             ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */);
107590             ts.setParent(externalHelpersModuleReference, importDecl);
107591             ts.setParent(importDecl, file);
107592             // explicitly unset the synthesized flag on these declarations so the checker API will answer questions about them
107593             // (which is required to build the dependency graph for incremental emit)
107594             externalHelpersModuleReference.flags &= ~8 /* Synthesized */;
107595             importDecl.flags &= ~8 /* Synthesized */;
107596             return externalHelpersModuleReference;
107597         }
107598         function collectExternalModuleReferences(file) {
107599             if (file.imports) {
107600                 return;
107601             }
107602             var isJavaScriptFile = ts.isSourceFileJS(file);
107603             var isExternalModuleFile = ts.isExternalModule(file);
107604             // file.imports may not be undefined if there exists dynamic import
107605             var imports;
107606             var moduleAugmentations;
107607             var ambientModules;
107608             // If we are importing helpers, we need to add a synthetic reference to resolve the
107609             // helpers library.
107610             if ((options.isolatedModules || isExternalModuleFile)
107611                 && !file.isDeclarationFile) {
107612                 if (options.importHelpers) {
107613                     // synthesize 'import "tslib"' declaration
107614                     imports = [createSyntheticImport(ts.externalHelpersModuleNameText, file)];
107615                 }
107616                 var jsxImport = ts.getJSXRuntimeImport(ts.getJSXImplicitImportBase(options, file), options);
107617                 if (jsxImport) {
107618                     // synthesize `import "base/jsx-runtime"` declaration
107619                     (imports || (imports = [])).push(createSyntheticImport(jsxImport, file));
107620                 }
107621             }
107622             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
107623                 var node = _a[_i];
107624                 collectModuleReferences(node, /*inAmbientModule*/ false);
107625             }
107626             if ((file.flags & 1048576 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) {
107627                 collectDynamicImportOrRequireCalls(file);
107628             }
107629             file.imports = imports || ts.emptyArray;
107630             file.moduleAugmentations = moduleAugmentations || ts.emptyArray;
107631             file.ambientModuleNames = ambientModules || ts.emptyArray;
107632             return;
107633             function collectModuleReferences(node, inAmbientModule) {
107634                 if (ts.isAnyImportOrReExport(node)) {
107635                     var moduleNameExpr = ts.getExternalModuleName(node);
107636                     // TypeScript 1.0 spec (April 2014): 12.1.6
107637                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
107638                     // only through top - level external module names. Relative external module names are not permitted.
107639                     if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) {
107640                         imports = ts.append(imports, moduleNameExpr);
107641                     }
107642                 }
107643                 else if (ts.isModuleDeclaration(node)) {
107644                     if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasSyntacticModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) {
107645                         var nameText = ts.getTextOfIdentifierOrLiteral(node.name);
107646                         // Ambient module declarations can be interpreted as augmentations for some existing external modules.
107647                         // This will happen in two cases:
107648                         // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
107649                         // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
107650                         //   immediately nested in top level ambient module declaration .
107651                         if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) {
107652                             (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
107653                         }
107654                         else if (!inAmbientModule) {
107655                             if (file.isDeclarationFile) {
107656                                 // for global .d.ts files record name of ambient module
107657                                 (ambientModules || (ambientModules = [])).push(nameText);
107658                             }
107659                             // An AmbientExternalModuleDeclaration declares an external module.
107660                             // This type of declaration is permitted only in the global module.
107661                             // The StringLiteral must specify a top - level external module name.
107662                             // Relative external module names are not permitted
107663                             // NOTE: body of ambient module is always a module block, if it exists
107664                             var body = node.body;
107665                             if (body) {
107666                                 for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
107667                                     var statement = _a[_i];
107668                                     collectModuleReferences(statement, /*inAmbientModule*/ true);
107669                                 }
107670                             }
107671                         }
107672                     }
107673                 }
107674             }
107675             function collectDynamicImportOrRequireCalls(file) {
107676                 var r = /import|require/g;
107677                 while (r.exec(file.text) !== null) { // eslint-disable-line no-null/no-null
107678                     var node = getNodeAtPosition(file, r.lastIndex);
107679                     if (isJavaScriptFile && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
107680                         imports = ts.append(imports, node.arguments[0]);
107681                     }
107682                     // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
107683                     else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) {
107684                         imports = ts.append(imports, node.arguments[0]);
107685                     }
107686                     else if (ts.isLiteralImportTypeNode(node)) {
107687                         imports = ts.append(imports, node.argument.literal);
107688                     }
107689                 }
107690             }
107691             /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */
107692             function getNodeAtPosition(sourceFile, position) {
107693                 var current = sourceFile;
107694                 var getContainingChild = function (child) {
107695                     if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) {
107696                         return child;
107697                     }
107698                 };
107699                 while (true) {
107700                     var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild);
107701                     if (!child) {
107702                         return current;
107703                     }
107704                     current = child;
107705                 }
107706             }
107707         }
107708         function getLibFileFromReference(ref) {
107709             var libName = ts.toFileNameLowerCase(ref.fileName);
107710             var libFileName = ts.libMap.get(libName);
107711             if (libFileName) {
107712                 return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName));
107713             }
107714         }
107715         /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
107716         function getSourceFileFromReference(referencingFile, ref) {
107717             return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), getSourceFile);
107718         }
107719         function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, reason) {
107720             if (ts.hasExtension(fileName)) {
107721                 var canonicalFileName_1 = host.getCanonicalFileName(fileName);
107722                 if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) {
107723                     if (fail) {
107724                         if (ts.hasJSFileExtension(canonicalFileName_1)) {
107725                             fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName);
107726                         }
107727                         else {
107728                             fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'");
107729                         }
107730                     }
107731                     return undefined;
107732                 }
107733                 var sourceFile = getSourceFile(fileName);
107734                 if (fail) {
107735                     if (!sourceFile) {
107736                         var redirect = getProjectReferenceRedirect(fileName);
107737                         if (redirect) {
107738                             fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
107739                         }
107740                         else {
107741                             fail(ts.Diagnostics.File_0_not_found, fileName);
107742                         }
107743                     }
107744                     else if (isReferencedFile(reason) && canonicalFileName_1 === host.getCanonicalFileName(getSourceFileByPath(reason.file).fileName)) {
107745                         fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
107746                     }
107747                 }
107748                 return sourceFile;
107749             }
107750             else {
107751                 var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName);
107752                 if (sourceFileNoExtension)
107753                     return sourceFileNoExtension;
107754                 if (fail && options.allowNonTsExtensions) {
107755                     fail(ts.Diagnostics.File_0_not_found, fileName);
107756                     return undefined;
107757                 }
107758                 var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); });
107759                 if (fail && !sourceFileWithAddedExtension)
107760                     fail(ts.Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + supportedExtensions.join("', '") + "'");
107761                 return sourceFileWithAddedExtension;
107762             }
107763         }
107764         /** This has side effects through `findSourceFile`. */
107765         function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, reason) {
107766             getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, reason, packageId); }, // TODO: GH#18217
107767             function (diagnostic) {
107768                 var args = [];
107769                 for (var _i = 1; _i < arguments.length; _i++) {
107770                     args[_i - 1] = arguments[_i];
107771                 }
107772                 return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, diagnostic, args);
107773             }, reason);
107774         }
107775         function processProjectReferenceFile(fileName, reason) {
107776             return processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined, reason);
107777         }
107778         function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, reason) {
107779             var hasExistingReasonToReportErrorOn = !isReferencedFile(reason) && ts.some(fileReasons.get(existingFile.path), isReferencedFile);
107780             if (hasExistingReasonToReportErrorOn) {
107781                 addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, ts.Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, [existingFile.fileName, fileName]);
107782             }
107783             else {
107784                 addFilePreprocessingFileExplainingDiagnostic(existingFile, reason, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, [fileName, existingFile.fileName]);
107785             }
107786         }
107787         function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) {
107788             var redirect = Object.create(redirectTarget);
107789             redirect.fileName = fileName;
107790             redirect.path = path;
107791             redirect.resolvedPath = resolvedPath;
107792             redirect.originalFileName = originalFileName;
107793             redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected };
107794             sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
107795             Object.defineProperties(redirect, {
107796                 id: {
107797                     get: function () { return this.redirectInfo.redirectTarget.id; },
107798                     set: function (value) { this.redirectInfo.redirectTarget.id = value; },
107799                 },
107800                 symbol: {
107801                     get: function () { return this.redirectInfo.redirectTarget.symbol; },
107802                     set: function (value) { this.redirectInfo.redirectTarget.symbol = value; },
107803                 },
107804             });
107805             return redirect;
107806         }
107807         // Get source file from normalized fileName
107808         function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) {
107809             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* Program */, "findSourceFile", {
107810                 fileName: fileName,
107811                 isDefaultLib: isDefaultLib || undefined,
107812                 fileIncludeKind: ts.FileIncludeKind[reason.kind],
107813             });
107814             var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId);
107815             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
107816             return result;
107817         }
107818         function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, reason, packageId) {
107819             if (useSourceOfProjectReferenceRedirect) {
107820                 var source = getSourceOfProjectReferenceRedirect(fileName);
107821                 // If preserveSymlinks is true, module resolution wont jump the symlink
107822                 // but the resolved real path may be the .d.ts from project reference
107823                 // Note:: Currently we try the real path only if the
107824                 // file is from node_modules to avoid having to run real path on all file paths
107825                 if (!source &&
107826                     host.realpath &&
107827                     options.preserveSymlinks &&
107828                     ts.isDeclarationFileName(fileName) &&
107829                     ts.stringContains(fileName, ts.nodeModulesPathPart)) {
107830                     var realPath = host.realpath(fileName);
107831                     if (realPath !== fileName)
107832                         source = getSourceOfProjectReferenceRedirect(realPath);
107833                 }
107834                 if (source) {
107835                     var file_1 = ts.isString(source) ?
107836                         findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, reason, packageId) :
107837                         undefined;
107838                     if (file_1)
107839                         addFileToFilesByName(file_1, path, /*redirectedPath*/ undefined);
107840                     return file_1;
107841                 }
107842             }
107843             var originalFileName = fileName;
107844             if (filesByName.has(path)) {
107845                 var file_2 = filesByName.get(path);
107846                 addFileIncludeReason(file_2 || undefined, reason);
107847                 // try to check if we've already seen this file but with a different casing in path
107848                 // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected
107849                 if (file_2 && options.forceConsistentCasingInFileNames) {
107850                     var checkedName = file_2.fileName;
107851                     var isRedirect = toPath(checkedName) !== toPath(fileName);
107852                     if (isRedirect) {
107853                         fileName = getProjectReferenceRedirect(fileName) || fileName;
107854                     }
107855                     // Check if it differs only in drive letters its ok to ignore that error:
107856                     var checkedAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory);
107857                     var inputAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory);
107858                     if (checkedAbsolutePath !== inputAbsolutePath) {
107859                         reportFileNamesDifferOnlyInCasingError(fileName, file_2, reason);
107860                     }
107861                 }
107862                 // If the file was previously found via a node_modules search, but is now being processed as a root file,
107863                 // then everything it sucks in may also be marked incorrectly, and needs to be checked again.
107864                 if (file_2 && sourceFilesFoundSearchingNodeModules.get(file_2.path) && currentNodeModulesDepth === 0) {
107865                     sourceFilesFoundSearchingNodeModules.set(file_2.path, false);
107866                     if (!options.noResolve) {
107867                         processReferencedFiles(file_2, isDefaultLib);
107868                         processTypeReferenceDirectives(file_2);
107869                     }
107870                     if (!options.noLib) {
107871                         processLibReferenceDirectives(file_2);
107872                     }
107873                     modulesWithElidedImports.set(file_2.path, false);
107874                     processImportedModules(file_2);
107875                 }
107876                 // See if we need to reprocess the imports due to prior skipped imports
107877                 else if (file_2 && modulesWithElidedImports.get(file_2.path)) {
107878                     if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
107879                         modulesWithElidedImports.set(file_2.path, false);
107880                         processImportedModules(file_2);
107881                     }
107882                 }
107883                 return file_2 || undefined;
107884             }
107885             var redirectedPath;
107886             if (isReferencedFile(reason) && !useSourceOfProjectReferenceRedirect) {
107887                 var redirectProject = getProjectReferenceRedirectProject(fileName);
107888                 if (redirectProject) {
107889                     if (ts.outFile(redirectProject.commandLine.options)) {
107890                         // Shouldnt create many to 1 mapping file in --out scenario
107891                         return undefined;
107892                     }
107893                     var redirect = getProjectReferenceOutputName(redirectProject, fileName);
107894                     fileName = redirect;
107895                     // Once we start redirecting to a file, we can potentially come back to it
107896                     // via a back-reference from another file in the .d.ts folder. If that happens we'll
107897                     // end up trying to add it to the program *again* because we were tracking it via its
107898                     // original (un-redirected) name. So we have to map both the original path and the redirected path
107899                     // to the source file we're about to find/create
107900                     redirectedPath = toPath(redirect);
107901                 }
107902             }
107903             // We haven't looked for this file, do so now and cache result
107904             var file = host.getSourceFile(fileName, options.target, function (hostErrorMessage) { return addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]); }, shouldCreateNewSourceFile);
107905             if (packageId) {
107906                 var packageIdKey = ts.packageIdToString(packageId);
107907                 var fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
107908                 if (fileFromPackageId) {
107909                     // Some other SourceFile already exists with this package name and version.
107910                     // Instead of creating a duplicate, just redirect to the existing one.
107911                     var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217
107912                     redirectTargetsMap.add(fileFromPackageId.path, fileName);
107913                     addFileToFilesByName(dupFile, path, redirectedPath);
107914                     addFileIncludeReason(dupFile, reason);
107915                     sourceFileToPackageName.set(path, packageId.name);
107916                     processingOtherFiles.push(dupFile);
107917                     return dupFile;
107918                 }
107919                 else if (file) {
107920                     // This is the first source file to have this packageId.
107921                     packageIdToSourceFile.set(packageIdKey, file);
107922                     sourceFileToPackageName.set(path, packageId.name);
107923                 }
107924             }
107925             addFileToFilesByName(file, path, redirectedPath);
107926             if (file) {
107927                 sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
107928                 file.fileName = fileName; // Ensure that source file has same name as what we were looking for
107929                 file.path = path;
107930                 file.resolvedPath = toPath(fileName);
107931                 file.originalFileName = originalFileName;
107932                 addFileIncludeReason(file, reason);
107933                 if (host.useCaseSensitiveFileNames()) {
107934                     var pathLowerCase = ts.toFileNameLowerCase(path);
107935                     // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
107936                     var existingFile = filesByNameIgnoreCase.get(pathLowerCase);
107937                     if (existingFile) {
107938                         reportFileNamesDifferOnlyInCasingError(fileName, existingFile, reason);
107939                     }
107940                     else {
107941                         filesByNameIgnoreCase.set(pathLowerCase, file);
107942                     }
107943                 }
107944                 skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib);
107945                 if (!options.noResolve) {
107946                     processReferencedFiles(file, isDefaultLib);
107947                     processTypeReferenceDirectives(file);
107948                 }
107949                 if (!options.noLib) {
107950                     processLibReferenceDirectives(file);
107951                 }
107952                 // always process imported modules to record module name resolutions
107953                 processImportedModules(file);
107954                 if (isDefaultLib) {
107955                     processingDefaultLibFiles.push(file);
107956                 }
107957                 else {
107958                     processingOtherFiles.push(file);
107959                 }
107960             }
107961             return file;
107962         }
107963         function addFileIncludeReason(file, reason) {
107964             if (file)
107965                 fileReasons.add(file.path, reason);
107966         }
107967         function addFileToFilesByName(file, path, redirectedPath) {
107968             if (redirectedPath) {
107969                 filesByName.set(redirectedPath, file);
107970                 filesByName.set(path, file || false);
107971             }
107972             else {
107973                 filesByName.set(path, file);
107974             }
107975         }
107976         function getProjectReferenceRedirect(fileName) {
107977             var referencedProject = getProjectReferenceRedirectProject(fileName);
107978             return referencedProject && getProjectReferenceOutputName(referencedProject, fileName);
107979         }
107980         function getProjectReferenceRedirectProject(fileName) {
107981             // Ignore dts or any json files
107982             if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || ts.fileExtensionIs(fileName, ".json" /* Json */)) {
107983                 return undefined;
107984             }
107985             // If this file is produced by a referenced project, we need to rewrite it to
107986             // look in the output folder of the referenced project rather than the input
107987             return getResolvedProjectReferenceToRedirect(fileName);
107988         }
107989         function getProjectReferenceOutputName(referencedProject, fileName) {
107990             var out = ts.outFile(referencedProject.commandLine.options);
107991             return out ?
107992                 ts.changeExtension(out, ".d.ts" /* Dts */) :
107993                 ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
107994         }
107995         /**
107996          * Get the referenced project if the file is input file from that reference project
107997          */
107998         function getResolvedProjectReferenceToRedirect(fileName) {
107999             if (mapFromFileToProjectReferenceRedirects === undefined) {
108000                 mapFromFileToProjectReferenceRedirects = new ts.Map();
108001                 forEachResolvedProjectReference(function (referencedProject) {
108002                     // not input file from the referenced project, ignore
108003                     if (toPath(options.configFilePath) !== referencedProject.sourceFile.path) {
108004                         referencedProject.commandLine.fileNames.forEach(function (f) {
108005                             return mapFromFileToProjectReferenceRedirects.set(toPath(f), referencedProject.sourceFile.path);
108006                         });
108007                     }
108008                 });
108009             }
108010             var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
108011             return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
108012         }
108013         function forEachResolvedProjectReference(cb) {
108014             return ts.forEachResolvedProjectReference(resolvedProjectReferences, cb);
108015         }
108016         function getSourceOfProjectReferenceRedirect(file) {
108017             if (!ts.isDeclarationFileName(file))
108018                 return undefined;
108019             if (mapFromToProjectReferenceRedirectSource === undefined) {
108020                 mapFromToProjectReferenceRedirectSource = new ts.Map();
108021                 forEachResolvedProjectReference(function (resolvedRef) {
108022                     var out = ts.outFile(resolvedRef.commandLine.options);
108023                     if (out) {
108024                         // Dont know which source file it means so return true?
108025                         var outputDts = ts.changeExtension(out, ".d.ts" /* Dts */);
108026                         mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), true);
108027                     }
108028                     else {
108029                         var getCommonSourceDirectory_3 = ts.memoize(function () { return ts.getCommonSourceDirectoryOfConfig(resolvedRef.commandLine, !host.useCaseSensitiveFileNames()); });
108030                         ts.forEach(resolvedRef.commandLine.fileNames, function (fileName) {
108031                             if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
108032                                 var outputDts = ts.getOutputDeclarationFileName(fileName, resolvedRef.commandLine, !host.useCaseSensitiveFileNames(), getCommonSourceDirectory_3);
108033                                 mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), fileName);
108034                             }
108035                         });
108036                     }
108037                 });
108038             }
108039             return mapFromToProjectReferenceRedirectSource.get(toPath(file));
108040         }
108041         function isSourceOfProjectReferenceRedirect(fileName) {
108042             return useSourceOfProjectReferenceRedirect && !!getResolvedProjectReferenceToRedirect(fileName);
108043         }
108044         function getResolvedProjectReferenceByPath(projectReferencePath) {
108045             if (!projectReferenceRedirects) {
108046                 return undefined;
108047             }
108048             return projectReferenceRedirects.get(projectReferencePath) || undefined;
108049         }
108050         function processReferencedFiles(file, isDefaultLib) {
108051             ts.forEach(file.referencedFiles, function (ref, index) {
108052                 processSourceFile(resolveTripleslashReference(ref.fileName, file.fileName), isDefaultLib, 
108053                 /*ignoreNoDefaultLib*/ false, 
108054                 /*packageId*/ undefined, { kind: ts.FileIncludeKind.ReferenceFile, file: file.path, index: index, });
108055             });
108056         }
108057         function processTypeReferenceDirectives(file) {
108058             // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
108059             var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
108060             if (!typeDirectives) {
108061                 return;
108062             }
108063             var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file);
108064             for (var index = 0; index < typeDirectives.length; index++) {
108065                 var ref = file.typeReferenceDirectives[index];
108066                 var resolvedTypeReferenceDirective = resolutions[index];
108067                 // store resolved type directive on the file
108068                 var fileName = ts.toFileNameLowerCase(ref.fileName);
108069                 ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
108070                 processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, { kind: ts.FileIncludeKind.TypeReferenceDirective, file: file.path, index: index, });
108071             }
108072         }
108073         function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, reason) {
108074             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 });
108075             processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason);
108076             ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop();
108077         }
108078         function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason) {
108079             // If we already found this library as a primary reference - nothing to do
108080             var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
108081             if (previousResolution && previousResolution.primary) {
108082                 return;
108083             }
108084             var saveResolution = true;
108085             if (resolvedTypeReferenceDirective) {
108086                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
108087                     currentNodeModulesDepth++;
108088                 if (resolvedTypeReferenceDirective.primary) {
108089                     // resolved from the primary path
108090                     processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, reason); // TODO: GH#18217
108091                 }
108092                 else {
108093                     // If we already resolved to this file, it must have been a secondary reference. Check file contents
108094                     // for sameness and possibly issue an error
108095                     if (previousResolution) {
108096                         // Don't bother reading the file again if it's the same file.
108097                         if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
108098                             var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
108099                             var existingFile = getSourceFile(previousResolution.resolvedFileName);
108100                             if (otherFileText !== existingFile.text) {
108101                                 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]);
108102                             }
108103                         }
108104                         // don't overwrite previous resolution result
108105                         saveResolution = false;
108106                     }
108107                     else {
108108                         // First resolution of this library
108109                         processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, reason);
108110                     }
108111                 }
108112                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
108113                     currentNodeModulesDepth--;
108114             }
108115             else {
108116                 addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, ts.Diagnostics.Cannot_find_type_definition_file_for_0, [typeReferenceDirective]);
108117             }
108118             if (saveResolution) {
108119                 resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
108120             }
108121         }
108122         function processLibReferenceDirectives(file) {
108123             ts.forEach(file.libReferenceDirectives, function (libReference, index) {
108124                 var libName = ts.toFileNameLowerCase(libReference.fileName);
108125                 var libFileName = ts.libMap.get(libName);
108126                 if (libFileName) {
108127                     // we ignore any 'no-default-lib' reference set on this file.
108128                     processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true, { kind: ts.FileIncludeKind.LibReferenceDirective, file: file.path, index: index, });
108129                 }
108130                 else {
108131                     var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts");
108132                     var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity);
108133                     var diagnostic = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
108134                     (fileProcessingDiagnostics || (fileProcessingDiagnostics = [])).push({
108135                         kind: 0 /* FilePreprocessingReferencedDiagnostic */,
108136                         reason: { kind: ts.FileIncludeKind.LibReferenceDirective, file: file.path, index: index, },
108137                         diagnostic: diagnostic,
108138                         args: [libName, suggestion]
108139                     });
108140                 }
108141             });
108142         }
108143         function getCanonicalFileName(fileName) {
108144             return host.getCanonicalFileName(fileName);
108145         }
108146         function processImportedModules(file) {
108147             collectExternalModuleReferences(file);
108148             if (file.imports.length || file.moduleAugmentations.length) {
108149                 // Because global augmentation doesn't have string literal name, we can check for global augmentation as such.
108150                 var moduleNames = getModuleNames(file);
108151                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, file);
108152                 ts.Debug.assert(resolutions.length === moduleNames.length);
108153                 for (var index = 0; index < moduleNames.length; index++) {
108154                     var resolution = resolutions[index];
108155                     ts.setResolvedModule(file, moduleNames[index], resolution);
108156                     if (!resolution) {
108157                         continue;
108158                     }
108159                     var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
108160                     var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension);
108161                     var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
108162                     var resolvedFileName = resolution.resolvedFileName;
108163                     if (isFromNodeModulesSearch) {
108164                         currentNodeModulesDepth++;
108165                     }
108166                     // add file to program only if:
108167                     // - resolution was successful
108168                     // - noResolve is falsy
108169                     // - module name comes from the list of imports
108170                     // - it's not a top level JavaScript module that exceeded the search max
108171                     var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
108172                     // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs')
108173                     // This may still end up being an untyped module -- the file won't be included but imports will be allowed.
108174                     var shouldAddFile = resolvedFileName
108175                         && !getResolutionDiagnostic(options, resolution)
108176                         && !options.noResolve
108177                         && index < file.imports.length
108178                         && !elideImport
108179                         && !(isJsFile && !ts.getAllowJSCompilerOption(options))
108180                         && (ts.isInJSFile(file.imports[index]) || !(file.imports[index].flags & 4194304 /* JSDoc */));
108181                     if (elideImport) {
108182                         modulesWithElidedImports.set(file.path, true);
108183                     }
108184                     else if (shouldAddFile) {
108185                         var path = toPath(resolvedFileName);
108186                         findSourceFile(resolvedFileName, path, 
108187                         /*isDefaultLib*/ false, 
108188                         /*ignoreNoDefaultLib*/ false, { kind: ts.FileIncludeKind.Import, file: file.path, index: index, }, resolution.packageId);
108189                     }
108190                     if (isFromNodeModulesSearch) {
108191                         currentNodeModulesDepth--;
108192                     }
108193                 }
108194             }
108195             else {
108196                 // no imports - drop cached module resolutions
108197                 file.resolvedModules = undefined;
108198             }
108199         }
108200         function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
108201             var allFilesBelongToPath = true;
108202             var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
108203             for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
108204                 var sourceFile = sourceFiles_2[_i];
108205                 if (!sourceFile.isDeclarationFile) {
108206                     var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
108207                     if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
108208                         addProgramDiagnosticExplainingFile(sourceFile, ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, [sourceFile.fileName, rootDirectory]);
108209                         allFilesBelongToPath = false;
108210                     }
108211                 }
108212             }
108213             return allFilesBelongToPath;
108214         }
108215         function parseProjectReferenceConfigFile(ref) {
108216             if (!projectReferenceRedirects) {
108217                 projectReferenceRedirects = new ts.Map();
108218             }
108219             // The actual filename (i.e. add "/tsconfig.json" if necessary)
108220             var refPath = resolveProjectReferencePath(ref);
108221             var sourceFilePath = toPath(refPath);
108222             var fromCache = projectReferenceRedirects.get(sourceFilePath);
108223             if (fromCache !== undefined) {
108224                 return fromCache || undefined;
108225             }
108226             var commandLine;
108227             var sourceFile;
108228             if (host.getParsedCommandLine) {
108229                 commandLine = host.getParsedCommandLine(refPath);
108230                 if (!commandLine) {
108231                     addFileToFilesByName(/*sourceFile*/ undefined, sourceFilePath, /*redirectedPath*/ undefined);
108232                     projectReferenceRedirects.set(sourceFilePath, false);
108233                     return undefined;
108234                 }
108235                 sourceFile = ts.Debug.checkDefined(commandLine.options.configFile);
108236                 ts.Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath);
108237                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
108238             }
108239             else {
108240                 // An absolute path pointing to the containing directory of the config file
108241                 var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
108242                 sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
108243                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
108244                 if (sourceFile === undefined) {
108245                     projectReferenceRedirects.set(sourceFilePath, false);
108246                     return undefined;
108247                 }
108248                 commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
108249             }
108250             sourceFile.fileName = refPath;
108251             sourceFile.path = sourceFilePath;
108252             sourceFile.resolvedPath = sourceFilePath;
108253             sourceFile.originalFileName = refPath;
108254             var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile };
108255             projectReferenceRedirects.set(sourceFilePath, resolvedRef);
108256             if (commandLine.projectReferences) {
108257                 resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile);
108258             }
108259             return resolvedRef;
108260         }
108261         function verifyCompilerOptions() {
108262             if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) {
108263                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
108264             }
108265             if (options.isolatedModules) {
108266                 if (options.out) {
108267                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules");
108268                 }
108269                 if (options.outFile) {
108270                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules");
108271                 }
108272             }
108273             if (options.inlineSourceMap) {
108274                 if (options.sourceMap) {
108275                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap");
108276                 }
108277                 if (options.mapRoot) {
108278                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap");
108279                 }
108280             }
108281             if (options.composite) {
108282                 if (options.declaration === false) {
108283                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
108284                 }
108285                 if (options.incremental === false) {
108286                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
108287                 }
108288             }
108289             var outputFile = ts.outFile(options);
108290             if (options.tsBuildInfoFile) {
108291                 if (!ts.isIncrementalCompilation(options)) {
108292                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
108293                 }
108294             }
108295             else if (options.incremental && !outputFile && !options.configFilePath) {
108296                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified));
108297             }
108298             verifyProjectReferences();
108299             // List of collected files is complete; validate exhautiveness if this is a project with a file list
108300             if (options.composite) {
108301                 var rootPaths = new ts.Set(rootNames.map(toPath));
108302                 for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
108303                     var file = files_3[_i];
108304                     // Ignore file that is not emitted
108305                     if (ts.sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) {
108306                         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 || ""]);
108307                     }
108308                 }
108309             }
108310             if (options.paths) {
108311                 for (var key in options.paths) {
108312                     if (!ts.hasProperty(options.paths, key)) {
108313                         continue;
108314                     }
108315                     if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
108316                         createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key);
108317                     }
108318                     if (ts.isArray(options.paths[key])) {
108319                         var len = options.paths[key].length;
108320                         if (len === 0) {
108321                             createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key);
108322                         }
108323                         for (var i = 0; i < len; i++) {
108324                             var subst = options.paths[key][i];
108325                             var typeOfSubst = typeof subst;
108326                             if (typeOfSubst === "string") {
108327                                 if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
108328                                     createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character, subst, key);
108329                                 }
108330                                 if (!options.baseUrl && !ts.pathIsRelative(subst) && !ts.pathIsAbsolute(subst)) {
108331                                     createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash);
108332                                 }
108333                             }
108334                             else {
108335                                 createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst);
108336                             }
108337                         }
108338                     }
108339                     else {
108340                         createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key);
108341                     }
108342                 }
108343             }
108344             if (!options.sourceMap && !options.inlineSourceMap) {
108345                 if (options.inlineSources) {
108346                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources");
108347                 }
108348                 if (options.sourceRoot) {
108349                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot");
108350                 }
108351             }
108352             if (options.out && options.outFile) {
108353                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile");
108354             }
108355             if (options.mapRoot && !(options.sourceMap || options.declarationMap)) {
108356                 // Error to specify --mapRoot without --sourcemap
108357                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap");
108358             }
108359             if (options.declarationDir) {
108360                 if (!ts.getEmitDeclarations(options)) {
108361                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite");
108362                 }
108363                 if (outputFile) {
108364                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile");
108365                 }
108366             }
108367             if (options.declarationMap && !ts.getEmitDeclarations(options)) {
108368                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite");
108369             }
108370             if (options.lib && options.noLib) {
108371                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
108372             }
108373             if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) {
108374                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
108375             }
108376             var languageVersion = options.target || 0 /* ES3 */;
108377             var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; });
108378             if (options.isolatedModules) {
108379                 if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) {
108380                     createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
108381                 }
108382                 if (options.preserveConstEnums === false) {
108383                     createDiagnosticForOptionName(ts.Diagnostics.Option_preserveConstEnums_cannot_be_disabled_when_isolatedModules_is_enabled, "preserveConstEnums", "isolatedModules");
108384                 }
108385                 var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; });
108386                 if (firstNonExternalModuleSourceFile) {
108387                     var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
108388                     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)));
108389                 }
108390             }
108391             else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) {
108392                 // We cannot use createDiagnosticFromNode because nodes do not have parents yet
108393                 var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
108394                 programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
108395             }
108396             // Cannot specify module gen that isn't amd or system with --out
108397             if (outputFile && !options.emitDeclarationOnly) {
108398                 if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) {
108399                     createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
108400                 }
108401                 else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
108402                     var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
108403                     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"));
108404                 }
108405             }
108406             if (options.resolveJsonModule) {
108407                 if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
108408                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
108409                 }
108410                 // Any emit other than common js, amd, es2015 or esnext is error
108411                 else if (!ts.hasJsonModuleEmitEnabled(options)) {
108412                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
108413                 }
108414             }
108415             // there has to be common source directory if user specified --outdir || --sourceRoot
108416             // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
108417             if (options.outDir || // there is --outDir specified
108418                 options.sourceRoot || // there is --sourceRoot specified
108419                 options.mapRoot) { // there is --mapRoot specified
108420                 // Precalculate and cache the common source directory
108421                 var dir = getCommonSourceDirectory();
108422                 // 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
108423                 if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) {
108424                     createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir");
108425                 }
108426             }
108427             if (options.useDefineForClassFields && languageVersion === 0 /* ES3 */) {
108428                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_target_is_ES3, "useDefineForClassFields");
108429             }
108430             if (options.checkJs && !ts.getAllowJSCompilerOption(options)) {
108431                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
108432             }
108433             if (options.emitDeclarationOnly) {
108434                 if (!ts.getEmitDeclarations(options)) {
108435                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite");
108436                 }
108437                 if (options.noEmit) {
108438                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit");
108439                 }
108440             }
108441             if (options.emitDecoratorMetadata &&
108442                 !options.experimentalDecorators) {
108443                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators");
108444             }
108445             if (options.jsxFactory) {
108446                 if (options.reactNamespace) {
108447                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory");
108448                 }
108449                 if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) {
108450                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxFactory", ts.inverseJsxOptionMap.get("" + options.jsx));
108451                 }
108452                 if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
108453                     createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory);
108454                 }
108455             }
108456             else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) {
108457                 createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace);
108458             }
108459             if (options.jsxFragmentFactory) {
108460                 if (!options.jsxFactory) {
108461                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "jsxFragmentFactory", "jsxFactory");
108462                 }
108463                 if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) {
108464                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxFragmentFactory", ts.inverseJsxOptionMap.get("" + options.jsx));
108465                 }
108466                 if (!ts.parseIsolatedEntityName(options.jsxFragmentFactory, languageVersion)) {
108467                     createOptionValueDiagnostic("jsxFragmentFactory", ts.Diagnostics.Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFragmentFactory);
108468                 }
108469             }
108470             if (options.reactNamespace) {
108471                 if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) {
108472                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "reactNamespace", ts.inverseJsxOptionMap.get("" + options.jsx));
108473                 }
108474             }
108475             if (options.jsxImportSource) {
108476                 if (options.jsx === 2 /* React */) {
108477                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxImportSource", ts.inverseJsxOptionMap.get("" + options.jsx));
108478                 }
108479             }
108480             // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
108481             if (!options.noEmit && !options.suppressOutputPathCheck) {
108482                 var emitHost = getEmitHost();
108483                 var emitFilesSeen_1 = new ts.Set();
108484                 ts.forEachEmittedFile(emitHost, function (emitFileNames) {
108485                     if (!options.emitDeclarationOnly) {
108486                         verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1);
108487                     }
108488                     verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1);
108489                 });
108490             }
108491             // Verify that all the emit files are unique and don't overwrite input files
108492             function verifyEmitFilePath(emitFileName, emitFilesSeen) {
108493                 if (emitFileName) {
108494                     var emitFilePath = toPath(emitFileName);
108495                     // Report error if the output overwrites input file
108496                     if (filesByName.has(emitFilePath)) {
108497                         var chain = void 0;
108498                         if (!options.configFilePath) {
108499                             // The program is from either an inferred project or an external project
108500                             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);
108501                         }
108502                         chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
108503                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain));
108504                     }
108505                     var emitFileKey = !host.useCaseSensitiveFileNames() ? ts.toFileNameLowerCase(emitFilePath) : emitFilePath;
108506                     // Report error if multiple files write into same file
108507                     if (emitFilesSeen.has(emitFileKey)) {
108508                         // Already seen the same emit file - report error
108509                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
108510                     }
108511                     else {
108512                         emitFilesSeen.add(emitFileKey);
108513                     }
108514                 }
108515             }
108516         }
108517         function createDiagnosticExplainingFile(file, fileProcessingReason, diagnostic, args) {
108518             var _a;
108519             var fileIncludeReasons;
108520             var relatedInfo;
108521             var locationReason = isReferencedFile(fileProcessingReason) ? fileProcessingReason : undefined;
108522             if (file)
108523                 (_a = fileReasons.get(file.path)) === null || _a === void 0 ? void 0 : _a.forEach(processReason);
108524             if (fileProcessingReason)
108525                 processReason(fileProcessingReason);
108526             // If we have location and there is only one reason file is in which is the location, dont add details for file include
108527             if (locationReason && (fileIncludeReasons === null || fileIncludeReasons === void 0 ? void 0 : fileIncludeReasons.length) === 1)
108528                 fileIncludeReasons = undefined;
108529             var location = locationReason && getReferencedFileLocation(getSourceFileByPath, locationReason);
108530             var fileIncludeReasonDetails = fileIncludeReasons && ts.chainDiagnosticMessages(fileIncludeReasons, ts.Diagnostics.The_file_is_in_the_program_because_Colon);
108531             var redirectInfo = file && ts.explainIfFileIsRedirect(file);
108532             var chain = ts.chainDiagnosticMessages.apply(void 0, __spreadArray([redirectInfo ? fileIncludeReasonDetails ? __spreadArray([fileIncludeReasonDetails], redirectInfo) : redirectInfo : fileIncludeReasonDetails, diagnostic], args || ts.emptyArray));
108533             return location && isReferenceFileLocation(location) ?
108534                 ts.createFileDiagnosticFromMessageChain(location.file, location.pos, location.end - location.pos, chain, relatedInfo) :
108535                 ts.createCompilerDiagnosticFromMessageChain(chain, relatedInfo);
108536             function processReason(reason) {
108537                 (fileIncludeReasons || (fileIncludeReasons = [])).push(ts.fileIncludeReasonToDiagnostics(program, reason));
108538                 if (!locationReason && isReferencedFile(reason)) {
108539                     // Report error at first reference file or file currently in processing and dont report in related information
108540                     locationReason = reason;
108541                 }
108542                 else if (locationReason !== reason) {
108543                     relatedInfo = ts.append(relatedInfo, fileIncludeReasonToRelatedInformation(reason));
108544                 }
108545                 // Remove fileProcessingReason if its already included in fileReasons of the program
108546                 if (reason === fileProcessingReason)
108547                     fileProcessingReason = undefined;
108548             }
108549         }
108550         function addFilePreprocessingFileExplainingDiagnostic(file, fileProcessingReason, diagnostic, args) {
108551             (fileProcessingDiagnostics || (fileProcessingDiagnostics = [])).push({
108552                 kind: 1 /* FilePreprocessingFileExplainingDiagnostic */,
108553                 file: file && file.path,
108554                 fileProcessingReason: fileProcessingReason,
108555                 diagnostic: diagnostic,
108556                 args: args
108557             });
108558         }
108559         function addProgramDiagnosticExplainingFile(file, diagnostic, args) {
108560             programDiagnostics.add(createDiagnosticExplainingFile(file, /*fileProcessingReason*/ undefined, diagnostic, args));
108561         }
108562         function fileIncludeReasonToRelatedInformation(reason) {
108563             if (isReferencedFile(reason)) {
108564                 var referenceLocation = getReferencedFileLocation(getSourceFileByPath, reason);
108565                 var message_2;
108566                 switch (reason.kind) {
108567                     case ts.FileIncludeKind.Import:
108568                         message_2 = ts.Diagnostics.File_is_included_via_import_here;
108569                         break;
108570                     case ts.FileIncludeKind.ReferenceFile:
108571                         message_2 = ts.Diagnostics.File_is_included_via_reference_here;
108572                         break;
108573                     case ts.FileIncludeKind.TypeReferenceDirective:
108574                         message_2 = ts.Diagnostics.File_is_included_via_type_library_reference_here;
108575                         break;
108576                     case ts.FileIncludeKind.LibReferenceDirective:
108577                         message_2 = ts.Diagnostics.File_is_included_via_library_reference_here;
108578                         break;
108579                     default:
108580                         ts.Debug.assertNever(reason);
108581                 }
108582                 return isReferenceFileLocation(referenceLocation) ? ts.createFileDiagnostic(referenceLocation.file, referenceLocation.pos, referenceLocation.end - referenceLocation.pos, message_2) : undefined;
108583             }
108584             if (!options.configFile)
108585                 return undefined;
108586             var configFileNode;
108587             var message;
108588             switch (reason.kind) {
108589                 case ts.FileIncludeKind.RootFile:
108590                     if (!options.configFile.configFileSpecs)
108591                         return undefined;
108592                     var fileName = ts.getNormalizedAbsolutePath(rootNames[reason.index], currentDirectory);
108593                     var matchedByFiles = ts.getMatchedFileSpec(program, fileName);
108594                     if (matchedByFiles) {
108595                         configFileNode = ts.getTsConfigPropArrayElementValue(options.configFile, "files", matchedByFiles);
108596                         message = ts.Diagnostics.File_is_matched_by_files_list_specified_here;
108597                         break;
108598                     }
108599                     var matchedByInclude = ts.getMatchedIncludeSpec(program, fileName);
108600                     // Could be additional files specified as roots
108601                     if (!matchedByInclude)
108602                         return undefined;
108603                     configFileNode = ts.getTsConfigPropArrayElementValue(options.configFile, "include", matchedByInclude);
108604                     message = ts.Diagnostics.File_is_matched_by_include_pattern_specified_here;
108605                     break;
108606                 case ts.FileIncludeKind.SourceFromProjectReference:
108607                 case ts.FileIncludeKind.OutputFromProjectReference:
108608                     var referencedResolvedRef_1 = ts.Debug.checkDefined(resolvedProjectReferences === null || resolvedProjectReferences === void 0 ? void 0 : resolvedProjectReferences[reason.index]);
108609                     var referenceInfo = forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, parent, index) {
108610                         return resolvedRef === referencedResolvedRef_1 ? { sourceFile: (parent === null || parent === void 0 ? void 0 : parent.sourceFile) || options.configFile, index: index } : undefined;
108611                     });
108612                     if (!referenceInfo)
108613                         return undefined;
108614                     var sourceFile = referenceInfo.sourceFile, index = referenceInfo.index;
108615                     var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
108616                     return referencesSyntax && referencesSyntax.elements.length > index ?
108617                         ts.createDiagnosticForNodeInSourceFile(sourceFile, referencesSyntax.elements[index], reason.kind === ts.FileIncludeKind.OutputFromProjectReference ?
108618                             ts.Diagnostics.File_is_output_from_referenced_project_specified_here :
108619                             ts.Diagnostics.File_is_source_from_referenced_project_specified_here) :
108620                         undefined;
108621                 case ts.FileIncludeKind.AutomaticTypeDirectiveFile:
108622                     if (!options.types)
108623                         return undefined;
108624                     configFileNode = getOptionsSyntaxByArrayElementValue("types", reason.typeReference);
108625                     message = ts.Diagnostics.File_is_entry_point_of_type_library_specified_here;
108626                     break;
108627                 case ts.FileIncludeKind.LibFile:
108628                     if (reason.index !== undefined) {
108629                         configFileNode = getOptionsSyntaxByArrayElementValue("lib", options.lib[reason.index]);
108630                         message = ts.Diagnostics.File_is_library_specified_here;
108631                         break;
108632                     }
108633                     var target = ts.forEachEntry(ts.targetOptionDeclaration.type, function (value, key) { return value === options.target ? key : undefined; });
108634                     configFileNode = target ? getOptionsSyntaxByValue("target", target) : undefined;
108635                     message = ts.Diagnostics.File_is_default_library_for_target_specified_here;
108636                     break;
108637                 default:
108638                     ts.Debug.assertNever(reason);
108639             }
108640             return configFileNode && ts.createDiagnosticForNodeInSourceFile(options.configFile, configFileNode, message);
108641         }
108642         function verifyProjectReferences() {
108643             var buildInfoPath = !options.suppressOutputPathCheck ? ts.getTsBuildInfoEmitOutputFilePath(options) : undefined;
108644             forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, parent, index) {
108645                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
108646                 var parentFile = parent && parent.sourceFile;
108647                 if (!resolvedRef) {
108648                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path);
108649                     return;
108650                 }
108651                 var options = resolvedRef.commandLine.options;
108652                 if (!options.composite || options.noEmit) {
108653                     // ok to not have composite if the current program is container only
108654                     var inputs = parent ? parent.commandLine.fileNames : rootNames;
108655                     if (inputs.length) {
108656                         if (!options.composite)
108657                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
108658                         if (options.noEmit)
108659                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_may_not_disable_emit, ref.path);
108660                     }
108661                 }
108662                 if (ref.prepend) {
108663                     var out = ts.outFile(options);
108664                     if (out) {
108665                         if (!host.fileExists(out)) {
108666                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path);
108667                         }
108668                     }
108669                     else {
108670                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
108671                     }
108672                 }
108673                 if (!parent && buildInfoPath && buildInfoPath === ts.getTsBuildInfoEmitOutputFilePath(options)) {
108674                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
108675                     hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
108676                 }
108677             });
108678         }
108679         function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
108680             var needCompilerDiagnostic = true;
108681             var pathsSyntax = getOptionPathsSyntax();
108682             for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) {
108683                 var pathProp = pathsSyntax_1[_i];
108684                 if (ts.isObjectLiteralExpression(pathProp.initializer)) {
108685                     for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) {
108686                         var keyProps = _b[_a];
108687                         var initializer = keyProps.initializer;
108688                         if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
108689                             programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2));
108690                             needCompilerDiagnostic = false;
108691                         }
108692                     }
108693                 }
108694             }
108695             if (needCompilerDiagnostic) {
108696                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
108697             }
108698         }
108699         function createDiagnosticForOptionPaths(onKey, key, message, arg0) {
108700             var needCompilerDiagnostic = true;
108701             var pathsSyntax = getOptionPathsSyntax();
108702             for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) {
108703                 var pathProp = pathsSyntax_2[_i];
108704                 if (ts.isObjectLiteralExpression(pathProp.initializer) &&
108705                     createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) {
108706                     needCompilerDiagnostic = false;
108707                 }
108708             }
108709             if (needCompilerDiagnostic) {
108710                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
108711             }
108712         }
108713         function getOptionsSyntaxByName(name) {
108714             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
108715             return compilerOptionsObjectLiteralSyntax && ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
108716         }
108717         function getOptionPathsSyntax() {
108718             return getOptionsSyntaxByName("paths") || ts.emptyArray;
108719         }
108720         function getOptionsSyntaxByValue(name, value) {
108721             var syntaxByName = getOptionsSyntaxByName(name);
108722             return syntaxByName && ts.firstDefined(syntaxByName, function (property) { return ts.isStringLiteral(property.initializer) && property.initializer.text === value ? property.initializer : undefined; });
108723         }
108724         function getOptionsSyntaxByArrayElementValue(name, value) {
108725             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
108726             return compilerOptionsObjectLiteralSyntax && ts.getPropertyArrayElementValue(compilerOptionsObjectLiteralSyntax, name, value);
108727         }
108728         function createDiagnosticForOptionName(message, option1, option2, option3) {
108729             createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
108730         }
108731         function createOptionValueDiagnostic(option1, message, arg0) {
108732             createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
108733         }
108734         function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) {
108735             var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
108736             if (referencesSyntax && referencesSyntax.elements.length > index) {
108737                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1));
108738             }
108739             else {
108740                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
108741             }
108742         }
108743         function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
108744             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
108745             var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
108746                 !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2);
108747             if (needCompilerDiagnostic) {
108748                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
108749             }
108750         }
108751         function getCompilerOptionsObjectLiteralSyntax() {
108752             if (_compilerOptionsObjectLiteralSyntax === undefined) {
108753                 _compilerOptionsObjectLiteralSyntax = false;
108754                 var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
108755                 if (jsonObjectLiteral) {
108756                     for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
108757                         var prop = _a[_i];
108758                         if (ts.isObjectLiteralExpression(prop.initializer)) {
108759                             _compilerOptionsObjectLiteralSyntax = prop.initializer;
108760                             break;
108761                         }
108762                     }
108763                 }
108764             }
108765             return _compilerOptionsObjectLiteralSyntax || undefined;
108766         }
108767         function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) {
108768             var props = ts.getPropertyAssignment(objectLiteral, key1, key2);
108769             for (var _i = 0, props_3 = props; _i < props_3.length; _i++) {
108770                 var prop = props_3[_i];
108771                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
108772             }
108773             return !!props.length;
108774         }
108775         function blockEmittingOfFile(emitFileName, diag) {
108776             hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
108777             programDiagnostics.add(diag);
108778         }
108779         function isEmittedFile(file) {
108780             if (options.noEmit) {
108781                 return false;
108782             }
108783             // If this is source file, its not emitted file
108784             var filePath = toPath(file);
108785             if (getSourceFileByPath(filePath)) {
108786                 return false;
108787             }
108788             // If options have --outFile or --out just check that
108789             var out = ts.outFile(options);
108790             if (out) {
108791                 return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */);
108792             }
108793             // If declarationDir is specified, return if its a file in that directory
108794             if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) {
108795                 return true;
108796             }
108797             // If --outDir, check if file is in that directory
108798             if (options.outDir) {
108799                 return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
108800             }
108801             if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) {
108802                 // Otherwise just check if sourceFile with the name exists
108803                 var filePathWithoutExtension = ts.removeFileExtension(filePath);
108804                 return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) ||
108805                     !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */));
108806             }
108807             return false;
108808         }
108809         function isSameFile(file1, file2) {
108810             return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
108811         }
108812         function getSymlinkCache() {
108813             if (host.getSymlinkCache) {
108814                 return host.getSymlinkCache();
108815             }
108816             return symlinks || (symlinks = ts.discoverProbableSymlinks(files, getCanonicalFileName, host.getCurrentDirectory()));
108817         }
108818     }
108819     ts.createProgram = createProgram;
108820     function updateHostForUseSourceOfProjectReferenceRedirect(host) {
108821         var setOfDeclarationDirectories;
108822         var originalFileExists = host.compilerHost.fileExists;
108823         var originalDirectoryExists = host.compilerHost.directoryExists;
108824         var originalGetDirectories = host.compilerHost.getDirectories;
108825         var originalRealpath = host.compilerHost.realpath;
108826         if (!host.useSourceOfProjectReferenceRedirect)
108827             return { onProgramCreateComplete: ts.noop, fileExists: fileExists };
108828         host.compilerHost.fileExists = fileExists;
108829         var directoryExists;
108830         if (originalDirectoryExists) {
108831             // This implementation of directoryExists checks if the directory being requested is
108832             // directory of .d.ts file for the referenced Project.
108833             // If it is it returns true irrespective of whether that directory exists on host
108834             directoryExists = host.compilerHost.directoryExists = function (path) {
108835                 if (originalDirectoryExists.call(host.compilerHost, path)) {
108836                     handleDirectoryCouldBeSymlink(path);
108837                     return true;
108838                 }
108839                 if (!host.getResolvedProjectReferences())
108840                     return false;
108841                 if (!setOfDeclarationDirectories) {
108842                     setOfDeclarationDirectories = new ts.Set();
108843                     host.forEachResolvedProjectReference(function (ref) {
108844                         var out = ts.outFile(ref.commandLine.options);
108845                         if (out) {
108846                             setOfDeclarationDirectories.add(ts.getDirectoryPath(host.toPath(out)));
108847                         }
108848                         else {
108849                             // Set declaration's in different locations only, if they are next to source the directory present doesnt change
108850                             var declarationDir = ref.commandLine.options.declarationDir || ref.commandLine.options.outDir;
108851                             if (declarationDir) {
108852                                 setOfDeclarationDirectories.add(host.toPath(declarationDir));
108853                             }
108854                         }
108855                     });
108856                 }
108857                 return fileOrDirectoryExistsUsingSource(path, /*isFile*/ false);
108858             };
108859         }
108860         if (originalGetDirectories) {
108861             // Call getDirectories only if directory actually present on the host
108862             // This is needed to ensure that we arent getting directories that we fake about presence for
108863             host.compilerHost.getDirectories = function (path) {
108864                 return !host.getResolvedProjectReferences() || (originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path)) ?
108865                     originalGetDirectories.call(host.compilerHost, path) :
108866                     [];
108867             };
108868         }
108869         // This is something we keep for life time of the host
108870         if (originalRealpath) {
108871             host.compilerHost.realpath = function (s) {
108872                 var _a;
108873                 return ((_a = host.getSymlinkCache().getSymlinkedFiles()) === null || _a === void 0 ? void 0 : _a.get(host.toPath(s))) ||
108874                     originalRealpath.call(host.compilerHost, s);
108875             };
108876         }
108877         return { onProgramCreateComplete: onProgramCreateComplete, fileExists: fileExists, directoryExists: directoryExists };
108878         function onProgramCreateComplete() {
108879             host.compilerHost.fileExists = originalFileExists;
108880             host.compilerHost.directoryExists = originalDirectoryExists;
108881             host.compilerHost.getDirectories = originalGetDirectories;
108882             // DO not revert realpath as it could be used later
108883         }
108884         // This implementation of fileExists checks if the file being requested is
108885         // .d.ts file for the referenced Project.
108886         // If it is it returns true irrespective of whether that file exists on host
108887         function fileExists(file) {
108888             if (originalFileExists.call(host.compilerHost, file))
108889                 return true;
108890             if (!host.getResolvedProjectReferences())
108891                 return false;
108892             if (!ts.isDeclarationFileName(file))
108893                 return false;
108894             // Project references go to source file instead of .d.ts file
108895             return fileOrDirectoryExistsUsingSource(file, /*isFile*/ true);
108896         }
108897         function fileExistsIfProjectReferenceDts(file) {
108898             var source = host.getSourceOfProjectReferenceRedirect(file);
108899             return source !== undefined ?
108900                 ts.isString(source) ? originalFileExists.call(host.compilerHost, source) : true :
108901                 undefined;
108902         }
108903         function directoryExistsIfProjectReferenceDeclDir(dir) {
108904             var dirPath = host.toPath(dir);
108905             var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator;
108906             return ts.forEachKey(setOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath ||
108907                 // Any parent directory of declaration dir
108908                 ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) ||
108909                 // Any directory inside declaration dir
108910                 ts.startsWith(dirPath, declDirPath + "/"); });
108911         }
108912         function handleDirectoryCouldBeSymlink(directory) {
108913             var _a;
108914             if (!host.getResolvedProjectReferences() || ts.containsIgnoredPath(directory))
108915                 return;
108916             // Because we already watch node_modules, handle symlinks in there
108917             if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart))
108918                 return;
108919             var symlinkCache = host.getSymlinkCache();
108920             var directoryPath = ts.ensureTrailingDirectorySeparator(host.toPath(directory));
108921             if ((_a = symlinkCache.getSymlinkedDirectories()) === null || _a === void 0 ? void 0 : _a.has(directoryPath))
108922                 return;
108923             var real = ts.normalizePath(originalRealpath.call(host.compilerHost, directory));
108924             var realPath;
108925             if (real === directory ||
108926                 (realPath = ts.ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) {
108927                 // not symlinked
108928                 symlinkCache.setSymlinkedDirectory(directoryPath, false);
108929                 return;
108930             }
108931             symlinkCache.setSymlinkedDirectory(directory, {
108932                 real: ts.ensureTrailingDirectorySeparator(real),
108933                 realPath: realPath
108934             });
108935         }
108936         function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) {
108937             var _a;
108938             var fileOrDirectoryExistsUsingSource = isFile ?
108939                 function (file) { return fileExistsIfProjectReferenceDts(file); } :
108940                 function (dir) { return directoryExistsIfProjectReferenceDeclDir(dir); };
108941             // Check current directory or file
108942             var result = fileOrDirectoryExistsUsingSource(fileOrDirectory);
108943             if (result !== undefined)
108944                 return result;
108945             var symlinkCache = host.getSymlinkCache();
108946             var symlinkedDirectories = symlinkCache.getSymlinkedDirectories();
108947             if (!symlinkedDirectories)
108948                 return false;
108949             var fileOrDirectoryPath = host.toPath(fileOrDirectory);
108950             if (!ts.stringContains(fileOrDirectoryPath, ts.nodeModulesPathPart))
108951                 return false;
108952             if (isFile && ((_a = symlinkCache.getSymlinkedFiles()) === null || _a === void 0 ? void 0 : _a.has(fileOrDirectoryPath)))
108953                 return true;
108954             // If it contains node_modules check if its one of the symlinked path we know of
108955             return ts.firstDefinedIterator(symlinkedDirectories.entries(), function (_a) {
108956                 var directoryPath = _a[0], symlinkedDirectory = _a[1];
108957                 if (!symlinkedDirectory || !ts.startsWith(fileOrDirectoryPath, directoryPath))
108958                     return undefined;
108959                 var result = fileOrDirectoryExistsUsingSource(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath));
108960                 if (isFile && result) {
108961                     // Store the real path for the file'
108962                     var absolutePath = ts.getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory());
108963                     symlinkCache.setSymlinkedFile(fileOrDirectoryPath, "" + symlinkedDirectory.real + absolutePath.replace(new RegExp(directoryPath, "i"), ""));
108964                 }
108965                 return result;
108966             }) || false;
108967         }
108968     }
108969     /*@internal*/
108970     ts.emitSkippedWithNoDiagnostics = { diagnostics: ts.emptyArray, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
108971     /*@internal*/
108972     function handleNoEmitOptions(program, sourceFile, writeFile, cancellationToken) {
108973         var options = program.getCompilerOptions();
108974         if (options.noEmit) {
108975             // Cache the semantic diagnostics
108976             program.getSemanticDiagnostics(sourceFile, cancellationToken);
108977             return sourceFile || ts.outFile(options) ?
108978                 ts.emitSkippedWithNoDiagnostics :
108979                 program.emitBuildInfo(writeFile, cancellationToken);
108980         }
108981         // If the noEmitOnError flag is set, then check if we have any errors so far.  If so,
108982         // immediately bail out.  Note that we pass 'undefined' for 'sourceFile' so that we
108983         // get any preEmit diagnostics, not just the ones
108984         if (!options.noEmitOnError)
108985             return undefined;
108986         var diagnostics = __spreadArray(__spreadArray(__spreadArray(__spreadArray([], program.getOptionsDiagnostics(cancellationToken)), program.getSyntacticDiagnostics(sourceFile, cancellationToken)), program.getGlobalDiagnostics(cancellationToken)), program.getSemanticDiagnostics(sourceFile, cancellationToken));
108987         if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) {
108988             diagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
108989         }
108990         if (!diagnostics.length)
108991             return undefined;
108992         var emittedFiles;
108993         if (!sourceFile && !ts.outFile(options)) {
108994             var emitResult = program.emitBuildInfo(writeFile, cancellationToken);
108995             if (emitResult.diagnostics)
108996                 diagnostics = __spreadArray(__spreadArray([], diagnostics), emitResult.diagnostics);
108997             emittedFiles = emitResult.emittedFiles;
108998         }
108999         return { diagnostics: diagnostics, sourceMaps: undefined, emittedFiles: emittedFiles, emitSkipped: true };
109000     }
109001     ts.handleNoEmitOptions = handleNoEmitOptions;
109002     /*@internal*/
109003     function filterSemanticDiagnotics(diagnostic, option) {
109004         return ts.filter(diagnostic, function (d) { return !d.skippedOn || !option[d.skippedOn]; });
109005     }
109006     ts.filterSemanticDiagnotics = filterSemanticDiagnotics;
109007     /* @internal */
109008     function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) {
109009         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
109010         return {
109011             fileExists: function (f) { return directoryStructureHost.fileExists(f); },
109012             readDirectory: function (root, extensions, excludes, includes, depth) {
109013                 ts.Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
109014                 return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
109015             },
109016             readFile: function (f) { return directoryStructureHost.readFile(f); },
109017             useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
109018             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
109019             onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
109020             trace: host.trace ? function (s) { return host.trace(s); } : undefined
109021         };
109022     }
109023     ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
109024     /* @internal */
109025     function createPrependNodes(projectReferences, getCommandLine, readFile) {
109026         if (!projectReferences)
109027             return ts.emptyArray;
109028         var nodes;
109029         for (var i = 0; i < projectReferences.length; i++) {
109030             var ref = projectReferences[i];
109031             var resolvedRefOpts = getCommandLine(ref, i);
109032             if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
109033                 var out = ts.outFile(resolvedRefOpts.options);
109034                 // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
109035                 if (!out)
109036                     continue;
109037                 var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
109038                 var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
109039                 (nodes || (nodes = [])).push(node);
109040             }
109041         }
109042         return nodes || ts.emptyArray;
109043     }
109044     ts.createPrependNodes = createPrependNodes;
109045     function resolveProjectReferencePath(hostOrRef, ref) {
109046         var passedInRef = ref ? ref : hostOrRef;
109047         return ts.resolveConfigFileProjectName(passedInRef.path);
109048     }
109049     ts.resolveProjectReferencePath = resolveProjectReferencePath;
109050     /* @internal */
109051     /**
109052      * Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
109053      * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
109054      * This returns a diagnostic even if the module will be an untyped module.
109055      */
109056     function getResolutionDiagnostic(options, _a) {
109057         var extension = _a.extension;
109058         switch (extension) {
109059             case ".ts" /* Ts */:
109060             case ".d.ts" /* Dts */:
109061                 // These are always allowed.
109062                 return undefined;
109063             case ".tsx" /* Tsx */:
109064                 return needJsx();
109065             case ".jsx" /* Jsx */:
109066                 return needJsx() || needAllowJs();
109067             case ".js" /* Js */:
109068                 return needAllowJs();
109069             case ".json" /* Json */:
109070                 return needResolveJsonModule();
109071         }
109072         function needJsx() {
109073             return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
109074         }
109075         function needAllowJs() {
109076             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;
109077         }
109078         function needResolveJsonModule() {
109079             return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used;
109080         }
109081     }
109082     ts.getResolutionDiagnostic = getResolutionDiagnostic;
109083     function getModuleNames(_a) {
109084         var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
109085         var res = imports.map(function (i) { return i.text; });
109086         for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) {
109087             var aug = moduleAugmentations_1[_i];
109088             if (aug.kind === 10 /* StringLiteral */) {
109089                 res.push(aug.text);
109090             }
109091             // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
109092         }
109093         return res;
109094     }
109095     /* @internal */
109096     function getModuleNameStringLiteralAt(_a, index) {
109097         var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
109098         if (index < imports.length)
109099             return imports[index];
109100         var augIndex = imports.length;
109101         for (var _i = 0, moduleAugmentations_2 = moduleAugmentations; _i < moduleAugmentations_2.length; _i++) {
109102             var aug = moduleAugmentations_2[_i];
109103             if (aug.kind === 10 /* StringLiteral */) {
109104                 if (index === augIndex)
109105                     return aug;
109106                 augIndex++;
109107             }
109108             // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
109109         }
109110         ts.Debug.fail("should never ask for module name at index higher than possible module name");
109111     }
109112     ts.getModuleNameStringLiteralAt = getModuleNameStringLiteralAt;
109113 })(ts || (ts = {}));
109114 /*@internal*/
109115 var ts;
109116 (function (ts) {
109117     function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) {
109118         var outputFiles = [];
109119         var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit;
109120         return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit };
109121         function writeFile(fileName, text, writeByteOrderMark) {
109122             outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text });
109123         }
109124     }
109125     ts.getFileEmitOutput = getFileEmitOutput;
109126     var BuilderState;
109127     (function (BuilderState) {
109128         /**
109129          * Get the referencedFile from the imported module symbol
109130          */
109131         function getReferencedFileFromImportedModuleSymbol(symbol) {
109132             if (symbol.declarations && symbol.declarations[0]) {
109133                 var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]);
109134                 return declarationSourceFile && declarationSourceFile.resolvedPath;
109135             }
109136         }
109137         /**
109138          * Get the referencedFile from the import name node from file
109139          */
109140         function getReferencedFileFromImportLiteral(checker, importName) {
109141             var symbol = checker.getSymbolAtLocation(importName);
109142             return symbol && getReferencedFileFromImportedModuleSymbol(symbol);
109143         }
109144         /**
109145          * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path
109146          */
109147         function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) {
109148             return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName);
109149         }
109150         /**
109151          * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true
109152          */
109153         function getReferencedFiles(program, sourceFile, getCanonicalFileName) {
109154             var referencedFiles;
109155             // We need to use a set here since the code can contain the same import twice,
109156             // but that will only be one dependency.
109157             // To avoid invernal conversion, the key of the referencedFiles map must be of type Path
109158             if (sourceFile.imports && sourceFile.imports.length > 0) {
109159                 var checker = program.getTypeChecker();
109160                 for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
109161                     var importName = _a[_i];
109162                     var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName);
109163                     if (declarationSourceFilePath) {
109164                         addReferencedFile(declarationSourceFilePath);
109165                     }
109166                 }
109167             }
109168             var sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath);
109169             // Handle triple slash references
109170             if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
109171                 for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
109172                     var referencedFile = _c[_b];
109173                     var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName);
109174                     addReferencedFile(referencedPath);
109175                 }
109176             }
109177             // Handle type reference directives
109178             if (sourceFile.resolvedTypeReferenceDirectiveNames) {
109179                 sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) {
109180                     if (!resolvedTypeReferenceDirective) {
109181                         return;
109182                     }
109183                     var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217
109184                     var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName);
109185                     addReferencedFile(typeFilePath);
109186                 });
109187             }
109188             // Add module augmentation as references
109189             if (sourceFile.moduleAugmentations.length) {
109190                 var checker = program.getTypeChecker();
109191                 for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) {
109192                     var moduleName = _e[_d];
109193                     if (!ts.isStringLiteral(moduleName)) {
109194                         continue;
109195                     }
109196                     var symbol = checker.getSymbolAtLocation(moduleName);
109197                     if (!symbol) {
109198                         continue;
109199                     }
109200                     // Add any file other than our own as reference
109201                     addReferenceFromAmbientModule(symbol);
109202                 }
109203             }
109204             // From ambient modules
109205             for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) {
109206                 var ambientModule = _g[_f];
109207                 if (ambientModule.declarations.length > 1) {
109208                     addReferenceFromAmbientModule(ambientModule);
109209                 }
109210             }
109211             return referencedFiles;
109212             function addReferenceFromAmbientModule(symbol) {
109213                 // Add any file other than our own as reference
109214                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
109215                     var declaration = _a[_i];
109216                     var declarationSourceFile = ts.getSourceFileOfNode(declaration);
109217                     if (declarationSourceFile &&
109218                         declarationSourceFile !== sourceFile) {
109219                         addReferencedFile(declarationSourceFile.resolvedPath);
109220                     }
109221                 }
109222             }
109223             function addReferencedFile(referencedPath) {
109224                 (referencedFiles || (referencedFiles = new ts.Set())).add(referencedPath);
109225             }
109226         }
109227         /**
109228          * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
109229          */
109230         function canReuseOldState(newReferencedMap, oldState) {
109231             return oldState && !oldState.referencedMap === !newReferencedMap;
109232         }
109233         BuilderState.canReuseOldState = canReuseOldState;
109234         /**
109235          * Creates the state of file references and signature for the new program from oldState if it is safe
109236          */
109237         function create(newProgram, getCanonicalFileName, oldState) {
109238             var fileInfos = new ts.Map();
109239             var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? new ts.Map() : undefined;
109240             var exportedModulesMap = referencedMap ? new ts.Map() : undefined;
109241             var hasCalledUpdateShapeSignature = new ts.Set();
109242             var useOldState = canReuseOldState(referencedMap, oldState);
109243             // Ensure source files have parent pointers set
109244             newProgram.getTypeChecker();
109245             // Create the reference map, and set the file infos
109246             for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
109247                 var sourceFile = _a[_i];
109248                 var version_2 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
109249                 var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined;
109250                 if (referencedMap) {
109251                     var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
109252                     if (newReferences) {
109253                         referencedMap.set(sourceFile.resolvedPath, newReferences);
109254                     }
109255                     // Copy old visible to outside files map
109256                     if (useOldState) {
109257                         var exportedModules = oldState.exportedModulesMap.get(sourceFile.resolvedPath);
109258                         if (exportedModules) {
109259                             exportedModulesMap.set(sourceFile.resolvedPath, exportedModules);
109260                         }
109261                     }
109262                 }
109263                 fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) });
109264             }
109265             return {
109266                 fileInfos: fileInfos,
109267                 referencedMap: referencedMap,
109268                 exportedModulesMap: exportedModulesMap,
109269                 hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature
109270             };
109271         }
109272         BuilderState.create = create;
109273         /**
109274          * Releases needed properties
109275          */
109276         function releaseCache(state) {
109277             state.allFilesExcludingDefaultLibraryFile = undefined;
109278             state.allFileNames = undefined;
109279         }
109280         BuilderState.releaseCache = releaseCache;
109281         /**
109282          * Creates a clone of the state
109283          */
109284         function clone(state) {
109285             // Dont need to backup allFiles info since its cache anyway
109286             return {
109287                 fileInfos: new ts.Map(state.fileInfos),
109288                 referencedMap: state.referencedMap && new ts.Map(state.referencedMap),
109289                 exportedModulesMap: state.exportedModulesMap && new ts.Map(state.exportedModulesMap),
109290                 hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature),
109291             };
109292         }
109293         BuilderState.clone = clone;
109294         /**
109295          * Gets the files affected by the path from the program
109296          */
109297         function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) {
109298             // Since the operation could be cancelled, the signatures are always stored in the cache
109299             // They will be committed once it is safe to use them
109300             // eg when calling this api from tsserver, if there is no cancellation of the operation
109301             // In the other cases the affected files signatures are committed only after the iteration through the result is complete
109302             var signatureCache = cacheToUpdateSignature || new ts.Map();
109303             var sourceFile = programOfThisState.getSourceFileByPath(path);
109304             if (!sourceFile) {
109305                 return ts.emptyArray;
109306             }
109307             if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) {
109308                 return [sourceFile];
109309             }
109310             var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache);
109311             if (!cacheToUpdateSignature) {
109312                 // Commit all the signatures in the signature cache
109313                 updateSignaturesFromCache(state, signatureCache);
109314             }
109315             return result;
109316         }
109317         BuilderState.getFilesAffectedBy = getFilesAffectedBy;
109318         /**
109319          * Updates the signatures from the cache into state's fileinfo signatures
109320          * This should be called whenever it is safe to commit the state of the builder
109321          */
109322         function updateSignaturesFromCache(state, signatureCache) {
109323             signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); });
109324         }
109325         BuilderState.updateSignaturesFromCache = updateSignaturesFromCache;
109326         function updateSignatureOfFile(state, signature, path) {
109327             state.fileInfos.get(path).signature = signature;
109328             state.hasCalledUpdateShapeSignature.add(path);
109329         }
109330         BuilderState.updateSignatureOfFile = updateSignatureOfFile;
109331         /**
109332          * Returns if the shape of the signature has changed since last emit
109333          */
109334         function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
109335             ts.Debug.assert(!!sourceFile);
109336             ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state");
109337             // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate
109338             if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) {
109339                 return false;
109340             }
109341             var info = state.fileInfos.get(sourceFile.resolvedPath);
109342             if (!info)
109343                 return ts.Debug.fail();
109344             var prevSignature = info.signature;
109345             var latestSignature;
109346             if (sourceFile.isDeclarationFile) {
109347                 latestSignature = sourceFile.version;
109348                 if (exportedModulesMapCache && latestSignature !== prevSignature) {
109349                     // All the references in this file are exported
109350                     var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined;
109351                     exportedModulesMapCache.set(sourceFile.resolvedPath, references || false);
109352                 }
109353             }
109354             else {
109355                 var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, 
109356                 /*emitOnlyDtsFiles*/ true, cancellationToken, 
109357                 /*customTransformers*/ undefined, 
109358                 /*forceDtsEmit*/ true);
109359                 var firstDts_1 = emitOutput_1.outputFiles &&
109360                     programOfThisState.getCompilerOptions().declarationMap ?
109361                     emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined :
109362                     emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined;
109363                 if (firstDts_1) {
109364                     ts.Debug.assert(ts.fileExtensionIs(firstDts_1.name, ".d.ts" /* Dts */), "File extension for signature expected to be dts", function () { return "Found: " + ts.getAnyExtensionFromPath(firstDts_1.name) + " for " + firstDts_1.name + ":: All output files: " + JSON.stringify(emitOutput_1.outputFiles.map(function (f) { return f.name; })); });
109365                     latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text);
109366                     if (exportedModulesMapCache && latestSignature !== prevSignature) {
109367                         updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache);
109368                     }
109369                 }
109370                 else {
109371                     latestSignature = prevSignature; // TODO: GH#18217
109372                 }
109373             }
109374             cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature);
109375             return !prevSignature || latestSignature !== prevSignature;
109376         }
109377         BuilderState.updateShapeSignature = updateShapeSignature;
109378         /**
109379          * Coverts the declaration emit result into exported modules map
109380          */
109381         function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) {
109382             if (!exportedModulesFromDeclarationEmit) {
109383                 exportedModulesMapCache.set(sourceFile.resolvedPath, false);
109384                 return;
109385             }
109386             var exportedModules;
109387             exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); });
109388             exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules || false);
109389             function addExportedModule(exportedModulePath) {
109390                 if (exportedModulePath) {
109391                     if (!exportedModules) {
109392                         exportedModules = new ts.Set();
109393                     }
109394                     exportedModules.add(exportedModulePath);
109395                 }
109396             }
109397         }
109398         /**
109399          * Updates the exported modules from cache into state's exported modules map
109400          * This should be called whenever it is safe to commit the state of the builder
109401          */
109402         function updateExportedFilesMapFromCache(state, exportedModulesMapCache) {
109403             if (exportedModulesMapCache) {
109404                 ts.Debug.assert(!!state.exportedModulesMap);
109405                 exportedModulesMapCache.forEach(function (exportedModules, path) {
109406                     if (exportedModules) {
109407                         state.exportedModulesMap.set(path, exportedModules);
109408                     }
109409                     else {
109410                         state.exportedModulesMap.delete(path);
109411                     }
109412                 });
109413             }
109414         }
109415         BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache;
109416         /**
109417          * Get all the dependencies of the sourceFile
109418          */
109419         function getAllDependencies(state, programOfThisState, sourceFile) {
109420             var compilerOptions = programOfThisState.getCompilerOptions();
109421             // With --out or --outFile all outputs go into single file, all files depend on each other
109422             if (ts.outFile(compilerOptions)) {
109423                 return getAllFileNames(state, programOfThisState);
109424             }
109425             // If this is non module emit, or its a global file, it depends on all the source files
109426             if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) {
109427                 return getAllFileNames(state, programOfThisState);
109428             }
109429             // Get the references, traversing deep from the referenceMap
109430             var seenMap = new ts.Set();
109431             var queue = [sourceFile.resolvedPath];
109432             while (queue.length) {
109433                 var path = queue.pop();
109434                 if (!seenMap.has(path)) {
109435                     seenMap.add(path);
109436                     var references = state.referencedMap.get(path);
109437                     if (references) {
109438                         var iterator = references.keys();
109439                         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
109440                             queue.push(iterResult.value);
109441                         }
109442                     }
109443                 }
109444             }
109445             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; }));
109446         }
109447         BuilderState.getAllDependencies = getAllDependencies;
109448         /**
109449          * Gets the names of all files from the program
109450          */
109451         function getAllFileNames(state, programOfThisState) {
109452             if (!state.allFileNames) {
109453                 var sourceFiles = programOfThisState.getSourceFiles();
109454                 state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; });
109455             }
109456             return state.allFileNames;
109457         }
109458         /**
109459          * Gets the files referenced by the the file path
109460          */
109461         function getReferencedByPaths(state, referencedFilePath) {
109462             return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) {
109463                 var filePath = _a[0], referencesInFile = _a[1];
109464                 return referencesInFile.has(referencedFilePath) ? filePath : undefined;
109465             }));
109466         }
109467         BuilderState.getReferencedByPaths = getReferencedByPaths;
109468         /**
109469          * For script files that contains only ambient external modules, although they are not actually external module files,
109470          * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore,
109471          * there are no point to rebuild all script files if these special files have changed. However, if any statement
109472          * in the file is not ambient external module, we treat it as a regular script file.
109473          */
109474         function containsOnlyAmbientModules(sourceFile) {
109475             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
109476                 var statement = _a[_i];
109477                 if (!ts.isModuleWithStringLiteralName(statement)) {
109478                     return false;
109479                 }
109480             }
109481             return true;
109482         }
109483         /**
109484          * Return true if file contains anything that augments to global scope we need to build them as if
109485          * they are global files as well as module
109486          */
109487         function containsGlobalScopeAugmentation(sourceFile) {
109488             return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); });
109489         }
109490         /**
109491          * Return true if the file will invalidate all files because it affectes global scope
109492          */
109493         function isFileAffectingGlobalScope(sourceFile) {
109494             return containsGlobalScopeAugmentation(sourceFile) ||
109495                 !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile);
109496         }
109497         /**
109498          * Gets all files of the program excluding the default library file
109499          */
109500         function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) {
109501             // Use cached result
109502             if (state.allFilesExcludingDefaultLibraryFile) {
109503                 return state.allFilesExcludingDefaultLibraryFile;
109504             }
109505             var result;
109506             if (firstSourceFile)
109507                 addSourceFile(firstSourceFile);
109508             for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) {
109509                 var sourceFile = _a[_i];
109510                 if (sourceFile !== firstSourceFile) {
109511                     addSourceFile(sourceFile);
109512                 }
109513             }
109514             state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray;
109515             return state.allFilesExcludingDefaultLibraryFile;
109516             function addSourceFile(sourceFile) {
109517                 if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) {
109518                     (result || (result = [])).push(sourceFile);
109519                 }
109520             }
109521         }
109522         BuilderState.getAllFilesExcludingDefaultLibraryFile = getAllFilesExcludingDefaultLibraryFile;
109523         /**
109524          * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed
109525          */
109526         function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) {
109527             var compilerOptions = programOfThisState.getCompilerOptions();
109528             // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project,
109529             // so returning the file itself is good enough.
109530             if (compilerOptions && ts.outFile(compilerOptions)) {
109531                 return [sourceFileWithUpdatedShape];
109532             }
109533             return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
109534         }
109535         /**
109536          * When program emits modular code, gets the files affected by the sourceFile whose shape has changed
109537          */
109538         function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
109539             if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) {
109540                 return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
109541             }
109542             var compilerOptions = programOfThisState.getCompilerOptions();
109543             if (compilerOptions && (compilerOptions.isolatedModules || ts.outFile(compilerOptions))) {
109544                 return [sourceFileWithUpdatedShape];
109545             }
109546             // Now we need to if each file in the referencedBy list has a shape change as well.
109547             // Because if so, its own referencedBy files need to be saved as well to make the
109548             // emitting result consistent with files on disk.
109549             var seenFileNamesMap = new ts.Map();
109550             // Start with the paths this file was referenced by
109551             seenFileNamesMap.set(sourceFileWithUpdatedShape.resolvedPath, sourceFileWithUpdatedShape);
109552             var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath);
109553             while (queue.length > 0) {
109554                 var currentPath = queue.pop();
109555                 if (!seenFileNamesMap.has(currentPath)) {
109556                     var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
109557                     seenFileNamesMap.set(currentPath, currentSourceFile);
109558                     if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) {
109559                         queue.push.apply(queue, getReferencedByPaths(state, currentSourceFile.resolvedPath));
109560                     }
109561                 }
109562             }
109563             // Return array of values that needs emit
109564             return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; }));
109565         }
109566     })(BuilderState = ts.BuilderState || (ts.BuilderState = {}));
109567 })(ts || (ts = {}));
109568 /*@internal*/
109569 var ts;
109570 (function (ts) {
109571     var BuilderFileEmit;
109572     (function (BuilderFileEmit) {
109573         BuilderFileEmit[BuilderFileEmit["DtsOnly"] = 0] = "DtsOnly";
109574         BuilderFileEmit[BuilderFileEmit["Full"] = 1] = "Full";
109575     })(BuilderFileEmit = ts.BuilderFileEmit || (ts.BuilderFileEmit = {}));
109576     function hasSameKeys(map1, map2) {
109577         // Has same size and every key is present in both maps
109578         return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); });
109579     }
109580     /**
109581      * Create the state so that we can iterate on changedFiles/affected files
109582      */
109583     function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) {
109584         var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState);
109585         state.program = newProgram;
109586         var compilerOptions = newProgram.getCompilerOptions();
109587         state.compilerOptions = compilerOptions;
109588         // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
109589         if (!ts.outFile(compilerOptions)) {
109590             state.semanticDiagnosticsPerFile = new ts.Map();
109591         }
109592         state.changedFilesSet = new ts.Set();
109593         var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState);
109594         var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined;
109595         var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
109596             !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions);
109597         if (useOldState) {
109598             // Verify the sanity of old state
109599             if (!oldState.currentChangedFilePath) {
109600                 var affectedSignatures = oldState.currentAffectedFilesSignatures;
109601                 ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
109602             }
109603             var changedFilesSet = oldState.changedFilesSet;
109604             if (canCopySemanticDiagnostics) {
109605                 ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
109606             }
109607             // Copy old state's changed files set
109608             changedFilesSet === null || changedFilesSet === void 0 ? void 0 : changedFilesSet.forEach(function (value) { return state.changedFilesSet.add(value); });
109609             if (!ts.outFile(compilerOptions) && oldState.affectedFilesPendingEmit) {
109610                 state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice();
109611                 state.affectedFilesPendingEmitKind = oldState.affectedFilesPendingEmitKind && new ts.Map(oldState.affectedFilesPendingEmitKind);
109612                 state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
109613                 state.seenAffectedFiles = new ts.Set();
109614             }
109615         }
109616         // Update changed files and copy semantic diagnostics if we can
109617         var referencedMap = state.referencedMap;
109618         var oldReferencedMap = useOldState ? oldState.referencedMap : undefined;
109619         var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck;
109620         var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck;
109621         state.fileInfos.forEach(function (info, sourceFilePath) {
109622             var oldInfo;
109623             var newReferences;
109624             // if not using old state, every file is changed
109625             if (!useOldState ||
109626                 // File wasn't present in old state
109627                 !(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
109628                 // versions dont match
109629                 oldInfo.version !== info.version ||
109630                 // Referenced files changed
109631                 !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) ||
109632                 // Referenced file was deleted in the new program
109633                 newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) {
109634                 // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
109635                 state.changedFilesSet.add(sourceFilePath);
109636             }
109637             else if (canCopySemanticDiagnostics) {
109638                 var sourceFile = newProgram.getSourceFileByPath(sourceFilePath);
109639                 if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) {
109640                     return;
109641                 }
109642                 if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) {
109643                     return;
109644                 }
109645                 // Unchanged file copy diagnostics
109646                 var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
109647                 if (diagnostics) {
109648                     state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) : diagnostics);
109649                     if (!state.semanticDiagnosticsFromOldState) {
109650                         state.semanticDiagnosticsFromOldState = new ts.Set();
109651                     }
109652                     state.semanticDiagnosticsFromOldState.add(sourceFilePath);
109653                 }
109654             }
109655         });
109656         // If the global file is removed, add all files as changed
109657         if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) {
109658             ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined)
109659                 .forEach(function (file) { return state.changedFilesSet.add(file.resolvedPath); });
109660         }
109661         else if (oldCompilerOptions && !ts.outFile(compilerOptions) && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) {
109662             // Add all files to affectedFilesPendingEmit since emit changed
109663             newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* Full */); });
109664             ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size);
109665             state.seenAffectedFiles = state.seenAffectedFiles || new ts.Set();
109666         }
109667         state.buildInfoEmitPending = !!state.changedFilesSet.size;
109668         return state;
109669     }
109670     function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) {
109671         if (!diagnostics.length)
109672             return ts.emptyArray;
109673         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory()));
109674         return diagnostics.map(function (diagnostic) {
109675             var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
109676             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
109677             result.reportsDeprecated = diagnostic.reportDeprecated;
109678             result.source = diagnostic.source;
109679             result.skippedOn = diagnostic.skippedOn;
109680             var relatedInformation = diagnostic.relatedInformation;
109681             result.relatedInformation = relatedInformation ?
109682                 relatedInformation.length ?
109683                     relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram, toPath); }) :
109684                     [] :
109685                 undefined;
109686             return result;
109687         });
109688         function toPath(path) {
109689             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
109690         }
109691     }
109692     function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath) {
109693         var file = diagnostic.file;
109694         return __assign(__assign({}, diagnostic), { file: file ? newProgram.getSourceFileByPath(toPath(file)) : undefined });
109695     }
109696     /**
109697      * Releases program and other related not needed properties
109698      */
109699     function releaseCache(state) {
109700         ts.BuilderState.releaseCache(state);
109701         state.program = undefined;
109702     }
109703     /**
109704      * Creates a clone of the state
109705      */
109706     function cloneBuilderProgramState(state) {
109707         var newState = ts.BuilderState.clone(state);
109708         newState.semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile && new ts.Map(state.semanticDiagnosticsPerFile);
109709         newState.changedFilesSet = new ts.Set(state.changedFilesSet);
109710         newState.affectedFiles = state.affectedFiles;
109711         newState.affectedFilesIndex = state.affectedFilesIndex;
109712         newState.currentChangedFilePath = state.currentChangedFilePath;
109713         newState.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures && new ts.Map(state.currentAffectedFilesSignatures);
109714         newState.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap && new ts.Map(state.currentAffectedFilesExportedModulesMap);
109715         newState.seenAffectedFiles = state.seenAffectedFiles && new ts.Set(state.seenAffectedFiles);
109716         newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles;
109717         newState.semanticDiagnosticsFromOldState = state.semanticDiagnosticsFromOldState && new ts.Set(state.semanticDiagnosticsFromOldState);
109718         newState.program = state.program;
109719         newState.compilerOptions = state.compilerOptions;
109720         newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
109721         newState.affectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind);
109722         newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
109723         newState.seenEmittedFiles = state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles);
109724         newState.programEmitComplete = state.programEmitComplete;
109725         return newState;
109726     }
109727     /**
109728      * Verifies that source file is ok to be used in calls that arent handled by next
109729      */
109730     function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) {
109731         ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath));
109732     }
109733     /**
109734      * This function returns the next affected file to be processed.
109735      * Note that until doneAffected is called it would keep reporting same result
109736      * This is to allow the callers to be able to actually remove affected file only when the operation is complete
109737      * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
109738      */
109739     function getNextAffectedFile(state, cancellationToken, computeHash) {
109740         while (true) {
109741             var affectedFiles = state.affectedFiles;
109742             if (affectedFiles) {
109743                 var seenAffectedFiles = state.seenAffectedFiles;
109744                 var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217
109745                 while (affectedFilesIndex < affectedFiles.length) {
109746                     var affectedFile = affectedFiles[affectedFilesIndex];
109747                     if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
109748                         // Set the next affected file as seen and remove the cached semantic diagnostics
109749                         state.affectedFilesIndex = affectedFilesIndex;
109750                         handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash);
109751                         return affectedFile;
109752                     }
109753                     affectedFilesIndex++;
109754                 }
109755                 // Remove the changed file from the change set
109756                 state.changedFilesSet.delete(state.currentChangedFilePath);
109757                 state.currentChangedFilePath = undefined;
109758                 // Commit the changes in file signature
109759                 ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures);
109760                 state.currentAffectedFilesSignatures.clear();
109761                 ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap);
109762                 state.affectedFiles = undefined;
109763             }
109764             // Get next changed file
109765             var nextKey = state.changedFilesSet.keys().next();
109766             if (nextKey.done) {
109767                 // Done
109768                 return undefined;
109769             }
109770             // With --out or --outFile all outputs go into single file
109771             // so operations are performed directly on program, return program
109772             var program = ts.Debug.checkDefined(state.program);
109773             var compilerOptions = program.getCompilerOptions();
109774             if (ts.outFile(compilerOptions)) {
109775                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
109776                 return program;
109777             }
109778             // Get next batch of affected files
109779             if (!state.currentAffectedFilesSignatures)
109780                 state.currentAffectedFilesSignatures = new ts.Map();
109781             if (state.exportedModulesMap) {
109782                 if (!state.currentAffectedFilesExportedModulesMap)
109783                     state.currentAffectedFilesExportedModulesMap = new ts.Map();
109784             }
109785             state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
109786             state.currentChangedFilePath = nextKey.value;
109787             state.affectedFilesIndex = 0;
109788             if (!state.seenAffectedFiles)
109789                 state.seenAffectedFiles = new ts.Set();
109790         }
109791     }
109792     /**
109793      * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
109794      */
109795     function getNextAffectedFilePendingEmit(state) {
109796         var affectedFilesPendingEmit = state.affectedFilesPendingEmit;
109797         if (affectedFilesPendingEmit) {
109798             var seenEmittedFiles = (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map()));
109799             for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) {
109800                 var affectedFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
109801                 if (affectedFile) {
109802                     var seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
109803                     var emitKind = ts.Debug.checkDefined(ts.Debug.checkDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
109804                     if (seenKind === undefined || seenKind < emitKind) {
109805                         // emit this file
109806                         state.affectedFilesPendingEmitIndex = i;
109807                         return { affectedFile: affectedFile, emitKind: emitKind };
109808                     }
109809                 }
109810             }
109811             state.affectedFilesPendingEmit = undefined;
109812             state.affectedFilesPendingEmitKind = undefined;
109813             state.affectedFilesPendingEmitIndex = undefined;
109814         }
109815         return undefined;
109816     }
109817     /**
109818      *  Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file
109819      *  This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change
109820      */
109821     function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) {
109822         removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
109823         // If affected files is everything except default library, then nothing more to do
109824         if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
109825             if (!state.cleanedDiagnosticsOfLibFiles) {
109826                 state.cleanedDiagnosticsOfLibFiles = true;
109827                 var program_1 = ts.Debug.checkDefined(state.program);
109828                 var options_2 = program_1.getCompilerOptions();
109829                 ts.forEach(program_1.getSourceFiles(), function (f) {
109830                     return program_1.isSourceFileDefaultLibrary(f) &&
109831                         !ts.skipTypeChecking(f, options_2, program_1) &&
109832                         removeSemanticDiagnosticsOf(state, f.resolvedPath);
109833                 });
109834             }
109835             return;
109836         }
109837         if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) {
109838             forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); });
109839         }
109840     }
109841     /**
109842      * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled,
109843      * Also we need to make sure signature is updated for these files
109844      */
109845     function handleDtsMayChangeOf(state, path, cancellationToken, computeHash) {
109846         removeSemanticDiagnosticsOf(state, path);
109847         if (!state.changedFilesSet.has(path)) {
109848             var program = ts.Debug.checkDefined(state.program);
109849             var sourceFile = program.getSourceFileByPath(path);
109850             if (sourceFile) {
109851                 // Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
109852                 // we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file
109853                 // This ensures that we dont later during incremental builds considering wrong signature.
109854                 // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build
109855                 ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap);
109856                 // If not dts emit, nothing more to do
109857                 if (ts.getEmitDeclarations(state.compilerOptions)) {
109858                     addToAffectedFilesPendingEmit(state, path, 0 /* DtsOnly */);
109859                 }
109860             }
109861         }
109862         return false;
109863     }
109864     /**
109865      * Removes semantic diagnostics for path and
109866      * returns true if there are no more semantic diagnostics from the old state
109867      */
109868     function removeSemanticDiagnosticsOf(state, path) {
109869         if (!state.semanticDiagnosticsFromOldState) {
109870             return true;
109871         }
109872         state.semanticDiagnosticsFromOldState.delete(path);
109873         state.semanticDiagnosticsPerFile.delete(path);
109874         return !state.semanticDiagnosticsFromOldState.size;
109875     }
109876     function isChangedSignature(state, path) {
109877         var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path);
109878         var oldSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature;
109879         return newSignature !== oldSignature;
109880     }
109881     /**
109882      * Iterate on referencing modules that export entities from affected file
109883      */
109884     function forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, fn) {
109885         // If there was change in signature (dts output) for the changed file,
109886         // then only we need to handle pending file emit
109887         if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) {
109888             return;
109889         }
109890         if (!isChangedSignature(state, affectedFile.resolvedPath))
109891             return;
109892         // Since isolated modules dont change js files, files affected by change in signature is itself
109893         // But we need to cleanup semantic diagnostics and queue dts emit for affected files
109894         if (state.compilerOptions.isolatedModules) {
109895             var seenFileNamesMap = new ts.Map();
109896             seenFileNamesMap.set(affectedFile.resolvedPath, true);
109897             var queue = ts.BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
109898             while (queue.length > 0) {
109899                 var currentPath = queue.pop();
109900                 if (!seenFileNamesMap.has(currentPath)) {
109901                     seenFileNamesMap.set(currentPath, true);
109902                     var result = fn(state, currentPath);
109903                     if (result && isChangedSignature(state, currentPath)) {
109904                         var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath);
109905                         queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
109906                     }
109907                 }
109908             }
109909         }
109910         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
109911         var seenFileAndExportsOfFile = new ts.Set();
109912         // Go through exported modules from cache first
109913         // If exported modules has path, all files referencing file exported from are affected
109914         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
109915             return exportedModules &&
109916                 exportedModules.has(affectedFile.resolvedPath) &&
109917                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
109918         })) {
109919             return;
109920         }
109921         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
109922         ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
109923             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
109924                 exportedModules.has(affectedFile.resolvedPath) &&
109925                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
109926         });
109927     }
109928     /**
109929      * Iterate on files referencing referencedPath
109930      */
109931     function forEachFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile, fn) {
109932         return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) {
109933             return referencesInFile.has(referencedPath) && forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn);
109934         });
109935     }
109936     /**
109937      * fn on file and iterate on anything that exports this file
109938      */
109939     function forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn) {
109940         if (!ts.tryAddToSet(seenFileAndExportsOfFile, filePath)) {
109941             return false;
109942         }
109943         if (fn(state, filePath)) {
109944             // If there are no more diagnostics from old cache, done
109945             return true;
109946         }
109947         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
109948         // Go through exported modules from cache first
109949         // If exported modules has path, all files referencing file exported from are affected
109950         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
109951             return exportedModules &&
109952                 exportedModules.has(filePath) &&
109953                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
109954         })) {
109955             return true;
109956         }
109957         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
109958         if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
109959             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
109960                 exportedModules.has(filePath) &&
109961                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
109962         })) {
109963             return true;
109964         }
109965         // Remove diagnostics of files that import this file (without going to exports of referencing files)
109966         return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) {
109967             return referencesInFile.has(filePath) &&
109968                 !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
109969                 fn(state, referencingFilePath);
109970         } // Dont add to seen since this is not yet done with the export removal
109971         );
109972     }
109973     /**
109974      * This is called after completing operation on the next affected file.
109975      * The operations here are postponed to ensure that cancellation during the iteration is handled correctly
109976      */
109977     function doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
109978         if (isBuildInfoEmit) {
109979             state.buildInfoEmitPending = false;
109980         }
109981         else if (affected === state.program) {
109982             state.changedFilesSet.clear();
109983             state.programEmitComplete = true;
109984         }
109985         else {
109986             state.seenAffectedFiles.add(affected.resolvedPath);
109987             if (emitKind !== undefined) {
109988                 (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map())).set(affected.resolvedPath, emitKind);
109989             }
109990             if (isPendingEmit) {
109991                 state.affectedFilesPendingEmitIndex++;
109992                 state.buildInfoEmitPending = true;
109993             }
109994             else {
109995                 state.affectedFilesIndex++;
109996             }
109997         }
109998     }
109999     /**
110000      * Returns the result with affected file
110001      */
110002     function toAffectedFileResult(state, result, affected) {
110003         doneWithAffectedFile(state, affected);
110004         return { result: result, affected: affected };
110005     }
110006     /**
110007      * Returns the result with affected file
110008      */
110009     function toAffectedFileEmitResult(state, result, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
110010         doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit);
110011         return { result: result, affected: affected };
110012     }
110013     /**
110014      * Gets semantic diagnostics for the file which are
110015      * bindAndCheckDiagnostics (from cache) and program diagnostics
110016      */
110017     function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
110018         return ts.concatenate(getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), ts.Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile));
110019     }
110020     /**
110021      * Gets the binder and checker diagnostics either from cache if present, or otherwise from program and caches it
110022      * 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
110023      */
110024     function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken) {
110025         var path = sourceFile.resolvedPath;
110026         if (state.semanticDiagnosticsPerFile) {
110027             var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
110028             // Report the bind and check diagnostics from the cache if we already have those diagnostics present
110029             if (cachedDiagnostics) {
110030                 return ts.filterSemanticDiagnotics(cachedDiagnostics, state.compilerOptions);
110031             }
110032         }
110033         // Diagnostics werent cached, get them from program, and cache the result
110034         var diagnostics = ts.Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
110035         if (state.semanticDiagnosticsPerFile) {
110036             state.semanticDiagnosticsPerFile.set(path, diagnostics);
110037         }
110038         return ts.filterSemanticDiagnotics(diagnostics, state.compilerOptions);
110039     }
110040     /**
110041      * Gets the program information to be emitted in buildInfo so that we can use it to create new program
110042      */
110043     function getProgramBuildInfo(state, getCanonicalFileName) {
110044         if (ts.outFile(state.compilerOptions))
110045             return undefined;
110046         var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory();
110047         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory));
110048         var fileInfos = {};
110049         state.fileInfos.forEach(function (value, key) {
110050             var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
110051             fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope };
110052         });
110053         var result = {
110054             fileInfos: fileInfos,
110055             options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath)
110056         };
110057         if (state.referencedMap) {
110058             var referencedMap = {};
110059             for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) {
110060                 var key = _a[_i];
110061                 referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
110062             }
110063             result.referencedMap = referencedMap;
110064         }
110065         if (state.exportedModulesMap) {
110066             var exportedModulesMap = {};
110067             for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) {
110068                 var key = _c[_b];
110069                 var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
110070                 // Not in temporary cache, use existing value
110071                 if (newValue === undefined)
110072                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
110073                 // Value in cache and has updated value map, use that
110074                 else if (newValue)
110075                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
110076             }
110077             result.exportedModulesMap = exportedModulesMap;
110078         }
110079         if (state.semanticDiagnosticsPerFile) {
110080             var semanticDiagnosticsPerFile = [];
110081             for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) {
110082                 var key = _e[_d];
110083                 var value = state.semanticDiagnosticsPerFile.get(key);
110084                 semanticDiagnosticsPerFile.push(value.length ?
110085                     [
110086                         relativeToBuildInfo(key),
110087                         state.hasReusableDiagnostic ?
110088                             value :
110089                             convertToReusableDiagnostics(value, relativeToBuildInfo)
110090                     ] :
110091                     relativeToBuildInfo(key));
110092             }
110093             result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile;
110094         }
110095         if (state.affectedFilesPendingEmit) {
110096             var affectedFilesPendingEmit = [];
110097             var seenFiles = new ts.Set();
110098             for (var _f = 0, _g = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _f < _g.length; _f++) {
110099                 var path = _g[_f];
110100                 if (ts.tryAddToSet(seenFiles, path)) {
110101                     affectedFilesPendingEmit.push([relativeToBuildInfo(path), state.affectedFilesPendingEmitKind.get(path)]);
110102                 }
110103             }
110104             result.affectedFilesPendingEmit = affectedFilesPendingEmit;
110105         }
110106         return result;
110107         function relativeToBuildInfoEnsuringAbsolutePath(path) {
110108             return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory));
110109         }
110110         function relativeToBuildInfo(path) {
110111             return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName));
110112         }
110113     }
110114     function convertToReusableCompilerOptions(options, relativeToBuildInfo) {
110115         var result = {};
110116         var optionsNameMap = ts.getOptionsNameMap().optionsNameMap;
110117         for (var name in options) {
110118             if (ts.hasProperty(options, name)) {
110119                 result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo);
110120             }
110121         }
110122         if (result.configFilePath) {
110123             result.configFilePath = relativeToBuildInfo(result.configFilePath);
110124         }
110125         return result;
110126     }
110127     function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) {
110128         if (option) {
110129             if (option.type === "list") {
110130                 var values = value;
110131                 if (option.element.isFilePath && values.length) {
110132                     return values.map(relativeToBuildInfo);
110133                 }
110134             }
110135             else if (option.isFilePath) {
110136                 return relativeToBuildInfo(value);
110137             }
110138         }
110139         return value;
110140     }
110141     function convertToReusableDiagnostics(diagnostics, relativeToBuildInfo) {
110142         ts.Debug.assert(!!diagnostics.length);
110143         return diagnostics.map(function (diagnostic) {
110144             var result = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo);
110145             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
110146             result.reportDeprecated = diagnostic.reportsDeprecated;
110147             result.source = diagnostic.source;
110148             result.skippedOn = diagnostic.skippedOn;
110149             var relatedInformation = diagnostic.relatedInformation;
110150             result.relatedInformation = relatedInformation ?
110151                 relatedInformation.length ?
110152                     relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo); }) :
110153                     [] :
110154                 undefined;
110155             return result;
110156         });
110157     }
110158     function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo) {
110159         var file = diagnostic.file;
110160         return __assign(__assign({}, diagnostic), { file: file ? relativeToBuildInfo(file.resolvedPath) : undefined });
110161     }
110162     var BuilderProgramKind;
110163     (function (BuilderProgramKind) {
110164         BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
110165         BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram";
110166     })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {}));
110167     function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
110168         var host;
110169         var newProgram;
110170         var oldProgram;
110171         if (newProgramOrRootNames === undefined) {
110172             ts.Debug.assert(hostOrOptions === undefined);
110173             host = oldProgramOrHost;
110174             oldProgram = configFileParsingDiagnosticsOrOldProgram;
110175             ts.Debug.assert(!!oldProgram);
110176             newProgram = oldProgram.getProgram();
110177         }
110178         else if (ts.isArray(newProgramOrRootNames)) {
110179             oldProgram = configFileParsingDiagnosticsOrOldProgram;
110180             newProgram = ts.createProgram({
110181                 rootNames: newProgramOrRootNames,
110182                 options: hostOrOptions,
110183                 host: oldProgramOrHost,
110184                 oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
110185                 configFileParsingDiagnostics: configFileParsingDiagnostics,
110186                 projectReferences: projectReferences
110187             });
110188             host = oldProgramOrHost;
110189         }
110190         else {
110191             newProgram = newProgramOrRootNames;
110192             host = hostOrOptions;
110193             oldProgram = oldProgramOrHost;
110194             configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram;
110195         }
110196         return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray };
110197     }
110198     ts.getBuilderCreationParameters = getBuilderCreationParameters;
110199     function createBuilderProgram(kind, _a) {
110200         var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics;
110201         // Return same program if underlying program doesnt change
110202         var oldState = oldProgram && oldProgram.getState();
110203         if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
110204             newProgram = undefined; // TODO: GH#18217
110205             oldState = undefined;
110206             return oldProgram;
110207         }
110208         /**
110209          * Create the canonical file name for identity
110210          */
110211         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
110212         /**
110213          * Computing hash to for signature verification
110214          */
110215         var computeHash = ts.maybeBind(host, host.createHash);
110216         var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
110217         var backupState;
110218         newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); };
110219         // To ensure that we arent storing any references to old program or new program without state
110220         newProgram = undefined; // TODO: GH#18217
110221         oldProgram = undefined;
110222         oldState = undefined;
110223         var builderProgram = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
110224         builderProgram.getState = function () { return state; };
110225         builderProgram.backupState = function () {
110226             ts.Debug.assert(backupState === undefined);
110227             backupState = cloneBuilderProgramState(state);
110228         };
110229         builderProgram.restoreState = function () {
110230             state = ts.Debug.checkDefined(backupState);
110231             backupState = undefined;
110232         };
110233         builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); };
110234         builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
110235         builderProgram.emit = emit;
110236         builderProgram.releaseProgram = function () {
110237             releaseCache(state);
110238             backupState = undefined;
110239         };
110240         if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
110241             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
110242         }
110243         else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
110244             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
110245             builderProgram.emitNextAffectedFile = emitNextAffectedFile;
110246             builderProgram.emitBuildInfo = emitBuildInfo;
110247         }
110248         else {
110249             ts.notImplemented();
110250         }
110251         return builderProgram;
110252         function emitBuildInfo(writeFile, cancellationToken) {
110253             if (state.buildInfoEmitPending) {
110254                 var result = ts.Debug.checkDefined(state.program).emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken);
110255                 state.buildInfoEmitPending = false;
110256                 return result;
110257             }
110258             return ts.emitSkippedWithNoDiagnostics;
110259         }
110260         /**
110261          * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
110262          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
110263          * in that order would be used to write the files
110264          */
110265         function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
110266             var affected = getNextAffectedFile(state, cancellationToken, computeHash);
110267             var emitKind = 1 /* Full */;
110268             var isPendingEmitFile = false;
110269             if (!affected) {
110270                 if (!ts.outFile(state.compilerOptions)) {
110271                     var pendingAffectedFile = getNextAffectedFilePendingEmit(state);
110272                     if (!pendingAffectedFile) {
110273                         if (!state.buildInfoEmitPending) {
110274                             return undefined;
110275                         }
110276                         var affected_1 = ts.Debug.checkDefined(state.program);
110277                         return toAffectedFileEmitResult(state, 
110278                         // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
110279                         // Otherwise just affected file
110280                         affected_1.emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken), affected_1, 1 /* Full */, 
110281                         /*isPendingEmitFile*/ false, 
110282                         /*isBuildInfoEmit*/ true);
110283                     }
110284                     (affected = pendingAffectedFile.affectedFile, emitKind = pendingAffectedFile.emitKind);
110285                     isPendingEmitFile = true;
110286                 }
110287                 else {
110288                     var program = ts.Debug.checkDefined(state.program);
110289                     if (state.programEmitComplete)
110290                         return undefined;
110291                     affected = program;
110292                 }
110293             }
110294             return toAffectedFileEmitResult(state, 
110295             // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
110296             // Otherwise just affected file
110297             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);
110298         }
110299         /**
110300          * Emits the JavaScript and declaration files.
110301          * When targetSource file is specified, emits the files corresponding to that source file,
110302          * otherwise for the whole program.
110303          * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
110304          * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
110305          * it will only emit all the affected files instead of whole program
110306          *
110307          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
110308          * in that order would be used to write the files
110309          */
110310         function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
110311             var restorePendingEmitOnHandlingNoEmitSuccess = false;
110312             var savedAffectedFilesPendingEmit;
110313             var savedAffectedFilesPendingEmitKind;
110314             var savedAffectedFilesPendingEmitIndex;
110315             // 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
110316             // This ensures pending files to emit is updated in tsbuildinfo
110317             // 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)
110318             if (kind !== BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram &&
110319                 !targetSourceFile &&
110320                 !ts.outFile(state.compilerOptions) &&
110321                 !state.compilerOptions.noEmit &&
110322                 state.compilerOptions.noEmitOnError) {
110323                 restorePendingEmitOnHandlingNoEmitSuccess = true;
110324                 savedAffectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
110325                 savedAffectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind);
110326                 savedAffectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
110327             }
110328             if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
110329                 assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
110330             }
110331             var result = ts.handleNoEmitOptions(builderProgram, targetSourceFile, writeFile, cancellationToken);
110332             if (result)
110333                 return result;
110334             if (restorePendingEmitOnHandlingNoEmitSuccess) {
110335                 state.affectedFilesPendingEmit = savedAffectedFilesPendingEmit;
110336                 state.affectedFilesPendingEmitKind = savedAffectedFilesPendingEmitKind;
110337                 state.affectedFilesPendingEmitIndex = savedAffectedFilesPendingEmitIndex;
110338             }
110339             // Emit only affected files if using builder for emit
110340             if (!targetSourceFile && kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
110341                 // Emit and report any errors we ran into.
110342                 var sourceMaps = [];
110343                 var emitSkipped = false;
110344                 var diagnostics = void 0;
110345                 var emittedFiles = [];
110346                 var affectedEmitResult = void 0;
110347                 while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
110348                     emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
110349                     diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics);
110350                     emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
110351                     sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
110352                 }
110353                 return {
110354                     emitSkipped: emitSkipped,
110355                     diagnostics: diagnostics || ts.emptyArray,
110356                     emittedFiles: emittedFiles,
110357                     sourceMaps: sourceMaps
110358                 };
110359             }
110360             return ts.Debug.checkDefined(state.program).emit(targetSourceFile, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
110361         }
110362         /**
110363          * Return the semantic diagnostics for the next affected file or undefined if iteration is complete
110364          * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true
110365          */
110366         function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) {
110367             while (true) {
110368                 var affected = getNextAffectedFile(state, cancellationToken, computeHash);
110369                 if (!affected) {
110370                     // Done
110371                     return undefined;
110372                 }
110373                 else if (affected === state.program) {
110374                     // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified)
110375                     return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected);
110376                 }
110377                 // Add file to affected file pending emit to handle for later emit time
110378                 // 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
110379                 if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram || state.compilerOptions.noEmit || state.compilerOptions.noEmitOnError) {
110380                     addToAffectedFilesPendingEmit(state, affected.resolvedPath, 1 /* Full */);
110381                 }
110382                 // Get diagnostics for the affected file if its not ignored
110383                 if (ignoreSourceFile && ignoreSourceFile(affected)) {
110384                     // Get next affected file
110385                     doneWithAffectedFile(state, affected);
110386                     continue;
110387                 }
110388                 return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected);
110389             }
110390         }
110391         /**
110392          * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
110393          * The semantic diagnostics are cached and managed here
110394          * Note that it is assumed that when asked about semantic diagnostics through this API,
110395          * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
110396          * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
110397          * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
110398          */
110399         function getSemanticDiagnostics(sourceFile, cancellationToken) {
110400             assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
110401             var compilerOptions = ts.Debug.checkDefined(state.program).getCompilerOptions();
110402             if (ts.outFile(compilerOptions)) {
110403                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
110404                 // We dont need to cache the diagnostics just return them from program
110405                 return ts.Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
110406             }
110407             if (sourceFile) {
110408                 return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
110409             }
110410             // When semantic builder asks for diagnostics of the whole program,
110411             // ensure that all the affected files are handled
110412             // eslint-disable-next-line no-empty
110413             while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {
110414             }
110415             var diagnostics;
110416             for (var _i = 0, _a = ts.Debug.checkDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
110417                 var sourceFile_1 = _a[_i];
110418                 diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
110419             }
110420             return diagnostics || ts.emptyArray;
110421         }
110422     }
110423     ts.createBuilderProgram = createBuilderProgram;
110424     function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) {
110425         if (!state.affectedFilesPendingEmit)
110426             state.affectedFilesPendingEmit = [];
110427         if (!state.affectedFilesPendingEmitKind)
110428             state.affectedFilesPendingEmitKind = new ts.Map();
110429         var existingKind = state.affectedFilesPendingEmitKind.get(affectedFilePendingEmit);
110430         state.affectedFilesPendingEmit.push(affectedFilePendingEmit);
110431         state.affectedFilesPendingEmitKind.set(affectedFilePendingEmit, existingKind || kind);
110432         // affectedFilesPendingEmitIndex === undefined
110433         // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files
110434         //   so start from 0 as array would be affectedFilesPendingEmit
110435         // else, continue to iterate from existing index, the current set is appended to existing files
110436         if (state.affectedFilesPendingEmitIndex === undefined) {
110437             state.affectedFilesPendingEmitIndex = 0;
110438         }
110439     }
110440     function getMapOfReferencedSet(mapLike, toPath) {
110441         if (!mapLike)
110442             return undefined;
110443         var map = new ts.Map();
110444         // Copies keys/values from template. Note that for..in will not throw if
110445         // template is undefined, and instead will just exit the loop.
110446         for (var key in mapLike) {
110447             if (ts.hasProperty(mapLike, key)) {
110448                 map.set(toPath(key), new ts.Set(mapLike[key].map(toPath)));
110449             }
110450         }
110451         return map;
110452     }
110453     function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) {
110454         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
110455         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
110456         var fileInfos = new ts.Map();
110457         for (var key in program.fileInfos) {
110458             if (ts.hasProperty(program.fileInfos, key)) {
110459                 fileInfos.set(toPath(key), program.fileInfos[key]);
110460             }
110461         }
110462         var state = {
110463             fileInfos: fileInfos,
110464             compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath),
110465             referencedMap: getMapOfReferencedSet(program.referencedMap, toPath),
110466             exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath),
110467             semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }),
110468             hasReusableDiagnostic: true,
110469             affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }),
110470             affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }, function (value) { return value[1]; }),
110471             affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0,
110472         };
110473         return {
110474             getState: function () { return state; },
110475             backupState: ts.noop,
110476             restoreState: ts.noop,
110477             getProgram: ts.notImplemented,
110478             getProgramOrUndefined: ts.returnUndefined,
110479             releaseProgram: ts.noop,
110480             getCompilerOptions: function () { return state.compilerOptions; },
110481             getSourceFile: ts.notImplemented,
110482             getSourceFiles: ts.notImplemented,
110483             getOptionsDiagnostics: ts.notImplemented,
110484             getGlobalDiagnostics: ts.notImplemented,
110485             getConfigFileParsingDiagnostics: ts.notImplemented,
110486             getSyntacticDiagnostics: ts.notImplemented,
110487             getDeclarationDiagnostics: ts.notImplemented,
110488             getSemanticDiagnostics: ts.notImplemented,
110489             emit: ts.notImplemented,
110490             getAllDependencies: ts.notImplemented,
110491             getCurrentDirectory: ts.notImplemented,
110492             emitNextAffectedFile: ts.notImplemented,
110493             getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
110494             emitBuildInfo: ts.notImplemented,
110495             close: ts.noop,
110496         };
110497         function toPath(path) {
110498             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
110499         }
110500         function toAbsolutePath(path) {
110501             return ts.getNormalizedAbsolutePath(path, buildInfoDirectory);
110502         }
110503     }
110504     ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
110505     function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
110506         return {
110507             getState: ts.notImplemented,
110508             backupState: ts.noop,
110509             restoreState: ts.noop,
110510             getProgram: getProgram,
110511             getProgramOrUndefined: function () { return state.program; },
110512             releaseProgram: function () { return state.program = undefined; },
110513             getCompilerOptions: function () { return state.compilerOptions; },
110514             getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); },
110515             getSourceFiles: function () { return getProgram().getSourceFiles(); },
110516             getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); },
110517             getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); },
110518             getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; },
110519             getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); },
110520             getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); },
110521             getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
110522             emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
110523             emitBuildInfo: function (writeFile, cancellationToken) { return getProgram().emitBuildInfo(writeFile, cancellationToken); },
110524             getAllDependencies: ts.notImplemented,
110525             getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
110526             close: ts.noop,
110527         };
110528         function getProgram() {
110529             return ts.Debug.checkDefined(state.program);
110530         }
110531     }
110532     ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram;
110533 })(ts || (ts = {}));
110534 var ts;
110535 (function (ts) {
110536     function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
110537         return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
110538     }
110539     ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram;
110540     function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
110541         return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
110542     }
110543     ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram;
110544     function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
110545         var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics;
110546         return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics);
110547     }
110548     ts.createAbstractBuilder = createAbstractBuilder;
110549 })(ts || (ts = {}));
110550 /*@internal*/
110551 var ts;
110552 (function (ts) {
110553     function removeIgnoredPath(path) {
110554         // Consider whole staging folder as if node_modules changed.
110555         if (ts.endsWith(path, "/node_modules/.staging")) {
110556             return ts.removeSuffix(path, "/.staging");
110557         }
110558         return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); }) ?
110559             undefined :
110560             path;
110561     }
110562     ts.removeIgnoredPath = removeIgnoredPath;
110563     /**
110564      * Filter out paths like
110565      * "/", "/user", "/user/username", "/user/username/folderAtRoot",
110566      * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot"
110567      * @param dirPath
110568      */
110569     function canWatchDirectory(dirPath) {
110570         var rootLength = ts.getRootLength(dirPath);
110571         if (dirPath.length === rootLength) {
110572             // Ignore "/", "c:/"
110573             return false;
110574         }
110575         var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength);
110576         if (nextDirectorySeparator === -1) {
110577             // ignore "/user", "c:/users" or "c:/folderAtRoot"
110578             return false;
110579         }
110580         var pathPartForUserCheck = dirPath.substring(rootLength, nextDirectorySeparator + 1);
110581         var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* slash */;
110582         if (isNonDirectorySeparatorRoot &&
110583             dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths
110584             pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart
110585             nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1);
110586             if (nextDirectorySeparator === -1) {
110587                 // ignore "//vda1cs4850/c$/folderAtRoot"
110588                 return false;
110589             }
110590             pathPartForUserCheck = dirPath.substring(rootLength + pathPartForUserCheck.length, nextDirectorySeparator + 1);
110591         }
110592         if (isNonDirectorySeparatorRoot &&
110593             pathPartForUserCheck.search(/users\//i) !== 0) {
110594             // Paths like c:/folderAtRoot/subFolder are allowed
110595             return true;
110596         }
110597         for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) {
110598             searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1;
110599             if (searchIndex === 0) {
110600                 // Folder isnt at expected minimum levels
110601                 return false;
110602             }
110603         }
110604         return true;
110605     }
110606     ts.canWatchDirectory = canWatchDirectory;
110607     function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
110608         var filesWithChangedSetOfUnresolvedImports;
110609         var filesWithInvalidatedResolutions;
110610         var filesWithInvalidatedNonRelativeUnresolvedImports;
110611         var nonRelativeExternalModuleResolutions = ts.createMultiMap();
110612         var resolutionsWithFailedLookups = [];
110613         var resolvedFileToResolution = ts.createMultiMap();
110614         var hasChangedAutomaticTypeDirectiveNames = false;
110615         var failedLookupChecks = [];
110616         var startsWithPathChecks = [];
110617         var isInDirectoryChecks = [];
110618         var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217
110619         var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
110620         // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
110621         // The key in the map is source file's path.
110622         // The values are Map of resolutions with key being name lookedup.
110623         var resolvedModuleNames = new ts.Map();
110624         var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects();
110625         var nonRelativeModuleNameCache = ts.createCacheWithRedirects();
110626         var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
110627         var resolvedTypeReferenceDirectives = new ts.Map();
110628         var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects();
110629         /**
110630          * These are the extensions that failed lookup files will have by default,
110631          * any other extension of failed lookup will be store that path in custom failed lookup path
110632          * This helps in not having to comb through all resolutions when files are added/removed
110633          * Note that .d.ts file also has .d.ts extension hence will be part of default extensions
110634          */
110635         var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
110636         var customFailedLookupPaths = new ts.Map();
110637         var directoryWatchesOfFailedLookups = new ts.Map();
110638         var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
110639         var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217
110640         var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0;
110641         // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
110642         var typeRootsWatches = new ts.Map();
110643         return {
110644             startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions,
110645             finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions,
110646             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
110647             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
110648             startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
110649             finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
110650             resolveModuleNames: resolveModuleNames,
110651             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
110652             resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
110653             removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects,
110654             removeResolutionsOfFile: removeResolutionsOfFile,
110655             hasChangedAutomaticTypeDirectiveNames: function () { return hasChangedAutomaticTypeDirectiveNames; },
110656             invalidateResolutionOfFile: invalidateResolutionOfFile,
110657             invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations,
110658             setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports,
110659             createHasInvalidatedResolution: createHasInvalidatedResolution,
110660             isFileWithInvalidatedNonRelativeUnresolvedImports: isFileWithInvalidatedNonRelativeUnresolvedImports,
110661             updateTypeRootsWatch: updateTypeRootsWatch,
110662             closeTypeRootsWatch: closeTypeRootsWatch,
110663             clear: clear
110664         };
110665         function getResolvedModule(resolution) {
110666             return resolution.resolvedModule;
110667         }
110668         function getResolvedTypeReferenceDirective(resolution) {
110669             return resolution.resolvedTypeReferenceDirective;
110670         }
110671         function isInDirectoryPath(dir, file) {
110672             if (dir === undefined || file.length <= dir.length) {
110673                 return false;
110674             }
110675             return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator;
110676         }
110677         function clear() {
110678             ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf);
110679             customFailedLookupPaths.clear();
110680             nonRelativeExternalModuleResolutions.clear();
110681             closeTypeRootsWatch();
110682             resolvedModuleNames.clear();
110683             resolvedTypeReferenceDirectives.clear();
110684             resolvedFileToResolution.clear();
110685             resolutionsWithFailedLookups.length = 0;
110686             failedLookupChecks.length = 0;
110687             startsWithPathChecks.length = 0;
110688             isInDirectoryChecks.length = 0;
110689             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
110690             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
110691             clearPerDirectoryResolutions();
110692             hasChangedAutomaticTypeDirectiveNames = false;
110693         }
110694         function startRecordingFilesWithChangedResolutions() {
110695             filesWithChangedSetOfUnresolvedImports = [];
110696         }
110697         function finishRecordingFilesWithChangedResolutions() {
110698             var collected = filesWithChangedSetOfUnresolvedImports;
110699             filesWithChangedSetOfUnresolvedImports = undefined;
110700             return collected;
110701         }
110702         function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
110703             if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
110704                 return false;
110705             }
110706             // Invalidated if file has unresolved imports
110707             var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
110708             return !!value && !!value.length;
110709         }
110710         function createHasInvalidatedResolution(forceAllFilesAsInvalidated) {
110711             // Ensure pending resolutions are applied
110712             invalidateResolutionsOfFailedLookupLocations();
110713             if (forceAllFilesAsInvalidated) {
110714                 // Any file asked would have invalidated resolution
110715                 filesWithInvalidatedResolutions = undefined;
110716                 return ts.returnTrue;
110717             }
110718             var collected = filesWithInvalidatedResolutions;
110719             filesWithInvalidatedResolutions = undefined;
110720             return function (path) { return (!!collected && collected.has(path)) ||
110721                 isFileWithInvalidatedNonRelativeUnresolvedImports(path); };
110722         }
110723         function clearPerDirectoryResolutions() {
110724             perDirectoryResolvedModuleNames.clear();
110725             nonRelativeModuleNameCache.clear();
110726             perDirectoryResolvedTypeReferenceDirectives.clear();
110727             nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
110728             nonRelativeExternalModuleResolutions.clear();
110729         }
110730         function finishCachingPerDirectoryResolution() {
110731             filesWithInvalidatedNonRelativeUnresolvedImports = undefined;
110732             clearPerDirectoryResolutions();
110733             directoryWatchesOfFailedLookups.forEach(function (watcher, path) {
110734                 if (watcher.refCount === 0) {
110735                     directoryWatchesOfFailedLookups.delete(path);
110736                     watcher.watcher.close();
110737                 }
110738             });
110739             hasChangedAutomaticTypeDirectiveNames = false;
110740         }
110741         function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) {
110742             var _a;
110743             var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference);
110744             // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
110745             if (!resolutionHost.getGlobalCache) {
110746                 return primaryResult;
110747             }
110748             // otherwise try to load typings from @types
110749             var globalCache = resolutionHost.getGlobalCache();
110750             if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) {
110751                 // create different collection of failed lookup locations for second pass
110752                 // if it will fail and we've already found something during the first pass - we don't want to pollute its results
110753                 var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations;
110754                 if (resolvedModule) {
110755                     // Modify existing resolution so its saved in the directory cache as well
110756                     primaryResult.resolvedModule = resolvedModule;
110757                     (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations);
110758                     return primaryResult;
110759                 }
110760             }
110761             // Default return the result from the first pass
110762             return primaryResult;
110763         }
110764         function resolveNamesWithLocalCache(_a) {
110765             var _b;
110766             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;
110767             var path = resolutionHost.toPath(containingFile);
110768             var resolutionsInFile = cache.get(path) || cache.set(path, new ts.Map()).get(path);
110769             var dirPath = ts.getDirectoryPath(path);
110770             var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
110771             var perDirectoryResolution = perDirectoryCache.get(dirPath);
110772             if (!perDirectoryResolution) {
110773                 perDirectoryResolution = new ts.Map();
110774                 perDirectoryCache.set(dirPath, perDirectoryResolution);
110775             }
110776             var resolvedModules = [];
110777             var compilerOptions = resolutionHost.getCompilationSettings();
110778             var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
110779             // All the resolutions in this file are invalidated if this file wasn't resolved using same redirect
110780             var program = resolutionHost.getCurrentProgram();
110781             var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile);
110782             var unmatchedRedirects = oldRedirect ?
110783                 !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path :
110784                 !!redirectedReference;
110785             var seenNamesInFile = new ts.Map();
110786             for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
110787                 var name = names_3[_i];
110788                 var resolution = resolutionsInFile.get(name);
110789                 // Resolution is valid if it is present and not invalidated
110790                 if (!seenNamesInFile.has(name) &&
110791                     unmatchedRedirects || !resolution || resolution.isInvalidated ||
110792                     // If the name is unresolved import that was invalidated, recalculate
110793                     (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
110794                     var existingResolution = resolution;
110795                     var resolutionInDirectory = perDirectoryResolution.get(name);
110796                     if (resolutionInDirectory) {
110797                         resolution = resolutionInDirectory;
110798                     }
110799                     else {
110800                         resolution = loader(name, containingFile, compilerOptions, ((_b = resolutionHost.getCompilerHost) === null || _b === void 0 ? void 0 : _b.call(resolutionHost)) || resolutionHost, redirectedReference);
110801                         perDirectoryResolution.set(name, resolution);
110802                     }
110803                     resolutionsInFile.set(name, resolution);
110804                     watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName);
110805                     if (existingResolution) {
110806                         stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName);
110807                     }
110808                     if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
110809                         filesWithChangedSetOfUnresolvedImports.push(path);
110810                         // reset log changes to avoid recording the same file multiple times
110811                         logChanges = false;
110812                     }
110813                 }
110814                 ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated);
110815                 seenNamesInFile.set(name, true);
110816                 resolvedModules.push(getResolutionWithResolvedFileName(resolution));
110817             }
110818             // Stop watching and remove the unused name
110819             resolutionsInFile.forEach(function (resolution, name) {
110820                 if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) {
110821                     stopWatchFailedLookupLocationOfResolution(resolution, path, getResolutionWithResolvedFileName);
110822                     resolutionsInFile.delete(name);
110823                 }
110824             });
110825             return resolvedModules;
110826             function resolutionIsEqualTo(oldResolution, newResolution) {
110827                 if (oldResolution === newResolution) {
110828                     return true;
110829                 }
110830                 if (!oldResolution || !newResolution) {
110831                     return false;
110832                 }
110833                 var oldResult = getResolutionWithResolvedFileName(oldResolution);
110834                 var newResult = getResolutionWithResolvedFileName(newResolution);
110835                 if (oldResult === newResult) {
110836                     return true;
110837                 }
110838                 if (!oldResult || !newResult) {
110839                     return false;
110840                 }
110841                 return oldResult.resolvedFileName === newResult.resolvedFileName;
110842             }
110843         }
110844         function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) {
110845             return resolveNamesWithLocalCache({
110846                 names: typeDirectiveNames,
110847                 containingFile: containingFile,
110848                 redirectedReference: redirectedReference,
110849                 cache: resolvedTypeReferenceDirectives,
110850                 perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives,
110851                 loader: ts.resolveTypeReferenceDirective,
110852                 getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective,
110853                 shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; },
110854             });
110855         }
110856         function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) {
110857             return resolveNamesWithLocalCache({
110858                 names: moduleNames,
110859                 containingFile: containingFile,
110860                 redirectedReference: redirectedReference,
110861                 cache: resolvedModuleNames,
110862                 perDirectoryCacheWithRedirects: perDirectoryResolvedModuleNames,
110863                 loader: resolveModuleName,
110864                 getResolutionWithResolvedFileName: getResolvedModule,
110865                 shouldRetryResolution: function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); },
110866                 reusedNames: reusedNames,
110867                 logChanges: logChangesWhenResolvingModule,
110868             });
110869         }
110870         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
110871             var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
110872             return cache && cache.get(moduleName);
110873         }
110874         function isNodeModulesAtTypesDirectory(dirPath) {
110875             return ts.endsWith(dirPath, "/node_modules/@types");
110876         }
110877         function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) {
110878             if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
110879                 // Ensure failed look up is normalized path
110880                 failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
110881                 var failedLookupPathSplit = failedLookupLocationPath.split(ts.directorySeparator);
110882                 var failedLookupSplit = failedLookupLocation.split(ts.directorySeparator);
110883                 ts.Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath);
110884                 if (failedLookupPathSplit.length > rootSplitLength + 1) {
110885                     // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution
110886                     return {
110887                         dir: failedLookupSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator),
110888                         dirPath: failedLookupPathSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator)
110889                     };
110890                 }
110891                 else {
110892                     // Always watch root directory non recursively
110893                     return {
110894                         dir: rootDir,
110895                         dirPath: rootPath,
110896                         nonRecursive: false
110897                     };
110898                 }
110899             }
110900             return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath));
110901         }
110902         function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) {
110903             // If directory path contains node module, get the most parent node_modules directory for watching
110904             while (ts.pathContainsNodeModules(dirPath)) {
110905                 dir = ts.getDirectoryPath(dir);
110906                 dirPath = ts.getDirectoryPath(dirPath);
110907             }
110908             // If the directory is node_modules use it to watch, always watch it recursively
110909             if (ts.isNodeModulesDirectory(dirPath)) {
110910                 return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined;
110911             }
110912             var nonRecursive = true;
110913             // Use some ancestor of the root directory
110914             var subDirectoryPath, subDirectory;
110915             if (rootPath !== undefined) {
110916                 while (!isInDirectoryPath(dirPath, rootPath)) {
110917                     var parentPath = ts.getDirectoryPath(dirPath);
110918                     if (parentPath === dirPath) {
110919                         break;
110920                     }
110921                     nonRecursive = false;
110922                     subDirectoryPath = dirPath;
110923                     subDirectory = dir;
110924                     dirPath = parentPath;
110925                     dir = ts.getDirectoryPath(dir);
110926                 }
110927             }
110928             return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined;
110929         }
110930         function isPathWithDefaultFailedLookupExtension(path) {
110931             return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
110932         }
110933         function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) {
110934             if (resolution.refCount) {
110935                 resolution.refCount++;
110936                 ts.Debug.assertDefined(resolution.files);
110937             }
110938             else {
110939                 resolution.refCount = 1;
110940                 ts.Debug.assert(ts.length(resolution.files) === 0); // This resolution shouldnt be referenced by any file yet
110941                 if (ts.isExternalModuleNameRelative(name)) {
110942                     watchFailedLookupLocationOfResolution(resolution);
110943                 }
110944                 else {
110945                     nonRelativeExternalModuleResolutions.add(name, resolution);
110946                 }
110947                 var resolved = getResolutionWithResolvedFileName(resolution);
110948                 if (resolved && resolved.resolvedFileName) {
110949                     resolvedFileToResolution.add(resolutionHost.toPath(resolved.resolvedFileName), resolution);
110950                 }
110951             }
110952             (resolution.files || (resolution.files = [])).push(filePath);
110953         }
110954         function watchFailedLookupLocationOfResolution(resolution) {
110955             ts.Debug.assert(!!resolution.refCount);
110956             var failedLookupLocations = resolution.failedLookupLocations;
110957             if (!failedLookupLocations.length)
110958                 return;
110959             resolutionsWithFailedLookups.push(resolution);
110960             var setAtRoot = false;
110961             for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
110962                 var failedLookupLocation = failedLookupLocations_1[_i];
110963                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
110964                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
110965                 if (toWatch) {
110966                     var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive;
110967                     // If the failed lookup location path is not one of the supported extensions,
110968                     // store it in the custom path
110969                     if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
110970                         var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
110971                         customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
110972                     }
110973                     if (dirPath === rootPath) {
110974                         ts.Debug.assert(!nonRecursive);
110975                         setAtRoot = true;
110976                     }
110977                     else {
110978                         setDirectoryWatcher(dir, dirPath, nonRecursive);
110979                     }
110980                 }
110981             }
110982             if (setAtRoot) {
110983                 // This is always non recursive
110984                 setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217
110985             }
110986         }
110987         function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
110988             var program = resolutionHost.getCurrentProgram();
110989             if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) {
110990                 resolutions.forEach(watchFailedLookupLocationOfResolution);
110991             }
110992         }
110993         function setDirectoryWatcher(dir, dirPath, nonRecursive) {
110994             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
110995             if (dirWatcher) {
110996                 ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
110997                 dirWatcher.refCount++;
110998             }
110999             else {
111000                 directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive });
111001             }
111002         }
111003         function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) {
111004             ts.unorderedRemoveItem(ts.Debug.assertDefined(resolution.files), filePath);
111005             resolution.refCount--;
111006             if (resolution.refCount) {
111007                 return;
111008             }
111009             var resolved = getResolutionWithResolvedFileName(resolution);
111010             if (resolved && resolved.resolvedFileName) {
111011                 resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution);
111012             }
111013             if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) {
111014                 // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups
111015                 return;
111016             }
111017             var failedLookupLocations = resolution.failedLookupLocations;
111018             var removeAtRoot = false;
111019             for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
111020                 var failedLookupLocation = failedLookupLocations_2[_i];
111021                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
111022                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
111023                 if (toWatch) {
111024                     var dirPath = toWatch.dirPath;
111025                     var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
111026                     if (refCount) {
111027                         if (refCount === 1) {
111028                             customFailedLookupPaths.delete(failedLookupLocationPath);
111029                         }
111030                         else {
111031                             ts.Debug.assert(refCount > 1);
111032                             customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
111033                         }
111034                     }
111035                     if (dirPath === rootPath) {
111036                         removeAtRoot = true;
111037                     }
111038                     else {
111039                         removeDirectoryWatcher(dirPath);
111040                     }
111041                 }
111042             }
111043             if (removeAtRoot) {
111044                 removeDirectoryWatcher(rootPath);
111045             }
111046         }
111047         function removeDirectoryWatcher(dirPath) {
111048             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
111049             // Do not close the watcher yet since it might be needed by other failed lookup locations.
111050             dirWatcher.refCount--;
111051         }
111052         function createDirectoryWatcher(directory, dirPath, nonRecursive) {
111053             return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
111054                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
111055                 if (cachedDirectoryStructureHost) {
111056                     // Since the file existence changed, update the sourceFiles cache
111057                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
111058                 }
111059                 scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath);
111060             }, nonRecursive ? 0 /* None */ : 1 /* Recursive */);
111061         }
111062         function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) {
111063             // Deleted file, stop watching failed lookups for all the resolutions in the file
111064             var resolutions = cache.get(filePath);
111065             if (resolutions) {
111066                 resolutions.forEach(function (resolution) { return stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName); });
111067                 cache.delete(filePath);
111068             }
111069         }
111070         function removeResolutionsFromProjectReferenceRedirects(filePath) {
111071             if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) {
111072                 return;
111073             }
111074             var program = resolutionHost.getCurrentProgram();
111075             if (!program) {
111076                 return;
111077             }
111078             // If this file is input file for the referenced project, get it
111079             var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath);
111080             if (!resolvedProjectReference) {
111081                 return;
111082             }
111083             // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution
111084             resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); });
111085         }
111086         function removeResolutionsOfFile(filePath) {
111087             removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule);
111088             removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective);
111089         }
111090         function invalidateResolutions(resolutions, canInvalidate) {
111091             if (!resolutions)
111092                 return false;
111093             var invalidated = false;
111094             for (var _i = 0, resolutions_1 = resolutions; _i < resolutions_1.length; _i++) {
111095                 var resolution = resolutions_1[_i];
111096                 if (resolution.isInvalidated || !canInvalidate(resolution))
111097                     continue;
111098                 resolution.isInvalidated = invalidated = true;
111099                 for (var _a = 0, _b = ts.Debug.assertDefined(resolution.files); _a < _b.length; _a++) {
111100                     var containingFilePath = _b[_a];
111101                     (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath);
111102                     // When its a file with inferred types resolution, invalidate type reference directive resolution
111103                     hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || ts.endsWith(containingFilePath, ts.inferredTypesContainingFile);
111104                 }
111105             }
111106             return invalidated;
111107         }
111108         function invalidateResolutionOfFile(filePath) {
111109             removeResolutionsOfFile(filePath);
111110             // Resolution is invalidated if the resulting file name is same as the deleted file path
111111             var prevHasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
111112             if (invalidateResolutions(resolvedFileToResolution.get(filePath), ts.returnTrue) &&
111113                 hasChangedAutomaticTypeDirectiveNames &&
111114                 !prevHasChangedAutomaticTypeDirectiveNames) {
111115                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
111116             }
111117         }
111118         function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) {
111119             ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined);
111120             filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
111121         }
111122         function scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) {
111123             if (isCreatingWatchedDirectory) {
111124                 // Watching directory is created
111125                 // Invalidate any resolution has failed lookup in this directory
111126                 isInDirectoryChecks.push(fileOrDirectoryPath);
111127             }
111128             else {
111129                 // If something to do with folder/file starting with "." in node_modules folder, skip it
111130                 var updatedPath = removeIgnoredPath(fileOrDirectoryPath);
111131                 if (!updatedPath)
111132                     return false;
111133                 fileOrDirectoryPath = updatedPath;
111134                 // prevent saving an open file from over-eagerly triggering invalidation
111135                 if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) {
111136                     return false;
111137                 }
111138                 // Some file or directory in the watching directory is created
111139                 // Return early if it does not have any of the watching extension or not the custom failed lookup path
111140                 var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
111141                 if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) ||
111142                     isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) {
111143                     // Invalidate any resolution from this directory
111144                     failedLookupChecks.push(fileOrDirectoryPath);
111145                     startsWithPathChecks.push(fileOrDirectoryPath);
111146                 }
111147                 else {
111148                     if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
111149                         return false;
111150                     }
111151                     // Ignore emits from the program
111152                     if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) {
111153                         return false;
111154                     }
111155                     // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
111156                     failedLookupChecks.push(fileOrDirectoryPath);
111157                 }
111158             }
111159             resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations();
111160         }
111161         function invalidateResolutionsOfFailedLookupLocations() {
111162             if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) {
111163                 return false;
111164             }
111165             var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution);
111166             failedLookupChecks.length = 0;
111167             startsWithPathChecks.length = 0;
111168             isInDirectoryChecks.length = 0;
111169             return invalidated;
111170         }
111171         function canInvalidateFailedLookupResolution(resolution) {
111172             return resolution.failedLookupLocations.some(function (location) {
111173                 var locationPath = resolutionHost.toPath(location);
111174                 return ts.contains(failedLookupChecks, locationPath) ||
111175                     startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) ||
111176                     isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); });
111177             });
111178         }
111179         function closeTypeRootsWatch() {
111180             ts.clearMap(typeRootsWatches, ts.closeFileWatcher);
111181         }
111182         function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) {
111183             if (isInDirectoryPath(rootPath, typeRootPath)) {
111184                 return rootPath;
111185             }
111186             var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath);
111187             return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined;
111188         }
111189         function createTypeRootsWatch(typeRootPath, typeRoot) {
111190             // Create new watch and recursive info
111191             return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
111192                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
111193                 if (cachedDirectoryStructureHost) {
111194                     // Since the file existence changed, update the sourceFiles cache
111195                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
111196                 }
111197                 // For now just recompile
111198                 // We could potentially store more data here about whether it was/would be really be used or not
111199                 // and with that determine to trigger compilation but for now this is enough
111200                 hasChangedAutomaticTypeDirectiveNames = true;
111201                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
111202                 // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered
111203                 // So handle to failed lookup locations here as well to ensure we are invalidating resolutions
111204                 var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath);
111205                 if (dirPath) {
111206                     scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath);
111207                 }
111208             }, 1 /* Recursive */);
111209         }
111210         /**
111211          * Watches the types that would get added as part of getAutomaticTypeDirectiveNames
111212          * To be called when compiler options change
111213          */
111214         function updateTypeRootsWatch() {
111215             var options = resolutionHost.getCompilationSettings();
111216             if (options.types) {
111217                 // No need to do any watch since resolution cache is going to handle the failed lookups
111218                 // for the types added by this
111219                 closeTypeRootsWatch();
111220                 return;
111221             }
111222             // we need to assume the directories exist to ensure that we can get all the type root directories that get included
111223             // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them
111224             var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory });
111225             if (typeRoots) {
111226                 ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), {
111227                     createNewValue: createTypeRootsWatch,
111228                     onDeleteValue: ts.closeFileWatcher
111229                 });
111230             }
111231             else {
111232                 closeTypeRootsWatch();
111233             }
111234         }
111235         /**
111236          * Use this function to return if directory exists to get type roots to watch
111237          * If we return directory exists then only the paths will be added to type roots
111238          * Hence return true for all directories except root directories which are filtered from watching
111239          */
111240         function directoryExistsForTypeRootWatch(nodeTypesDirectory) {
111241             var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory));
111242             var dirPath = resolutionHost.toPath(dir);
111243             return dirPath === rootPath || canWatchDirectory(dirPath);
111244         }
111245     }
111246     ts.createResolutionCache = createResolutionCache;
111247 })(ts || (ts = {}));
111248 // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
111249 /* @internal */
111250 var ts;
111251 (function (ts) {
111252     var moduleSpecifiers;
111253     (function (moduleSpecifiers) {
111254         var RelativePreference;
111255         (function (RelativePreference) {
111256             RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
111257             RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
111258             RelativePreference[RelativePreference["Shortest"] = 2] = "Shortest";
111259             RelativePreference[RelativePreference["ExternalNonRelative"] = 3] = "ExternalNonRelative";
111260         })(RelativePreference || (RelativePreference = {}));
111261         // See UserPreferences#importPathEnding
111262         var Ending;
111263         (function (Ending) {
111264             Ending[Ending["Minimal"] = 0] = "Minimal";
111265             Ending[Ending["Index"] = 1] = "Index";
111266             Ending[Ending["JsExtension"] = 2] = "JsExtension";
111267         })(Ending || (Ending = {}));
111268         function getPreferences(_a, compilerOptions, importingSourceFile) {
111269             var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
111270             return {
111271                 relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ :
111272                     importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ :
111273                         importModuleSpecifierPreference === "project-relative" ? 3 /* ExternalNonRelative */ :
111274                             2 /* Shortest */,
111275                 ending: getEnding(),
111276             };
111277             function getEnding() {
111278                 switch (importModuleSpecifierEnding) {
111279                     case "minimal": return 0 /* Minimal */;
111280                     case "index": return 1 /* Index */;
111281                     case "js": return 2 /* JsExtension */;
111282                     default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */
111283                         : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */;
111284                 }
111285             }
111286         }
111287         function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) {
111288             return {
111289                 relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */,
111290                 ending: ts.hasJSFileExtension(oldImportSpecifier) ?
111291                     2 /* JsExtension */ :
111292                     ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */,
111293             };
111294         }
111295         function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, oldImportSpecifier) {
111296             var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier));
111297             if (res === oldImportSpecifier)
111298                 return undefined;
111299             return res;
111300         }
111301         moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier;
111302         // Note: importingSourceFile is just for usesJsExtensionOnImports
111303         function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, preferences) {
111304             if (preferences === void 0) { preferences = {}; }
111305             return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferences(preferences, compilerOptions, importingSourceFile));
111306         }
111307         moduleSpecifiers.getModuleSpecifier = getModuleSpecifier;
111308         function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host) {
111309             var info = getInfo(importingSourceFileName, host);
111310             var modulePaths = getAllModulePaths(importingSourceFileName, nodeModulesFileName, host);
111311             return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions, /*packageNameOnly*/ true); });
111312         }
111313         moduleSpecifiers.getNodeModulesPackageName = getNodeModulesPackageName;
111314         function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, preferences) {
111315             var info = getInfo(importingSourceFileName, host);
111316             var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host);
111317             return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions); }) ||
111318                 getLocalModuleSpecifier(toFileName, info, compilerOptions, host, preferences);
111319         }
111320         /** Returns an import for each symlink and for the realpath. */
111321         function getModuleSpecifiers(moduleSymbol, checker, compilerOptions, importingSourceFile, host, userPreferences) {
111322             var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol, checker);
111323             if (ambient)
111324                 return [ambient];
111325             var info = getInfo(importingSourceFile.path, host);
111326             var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol));
111327             var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host);
111328             var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
111329             var existingSpecifier = ts.forEach(modulePaths, function (modulePath) { return ts.forEach(host.getFileIncludeReasons().get(ts.toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)), function (reason) {
111330                 if (reason.kind !== ts.FileIncludeKind.Import || reason.file !== importingSourceFile.path)
111331                     return undefined;
111332                 var specifier = ts.getModuleNameStringLiteralAt(importingSourceFile, reason.index).text;
111333                 // If the preference is for non relative and the module specifier is relative, ignore it
111334                 return preferences.relativePreference !== 1 /* NonRelative */ || !ts.pathIsRelative(specifier) ?
111335                     specifier :
111336                     undefined;
111337             }); });
111338             if (existingSpecifier)
111339                 return [existingSpecifier];
111340             var importedFileIsInNodeModules = ts.some(modulePaths, function (p) { return p.isInNodeModules; });
111341             // Module specifier priority:
111342             //   1. "Bare package specifiers" (e.g. "@foo/bar") resulting from a path through node_modules to a package.json's "types" entry
111343             //   2. Specifiers generated using "paths" from tsconfig
111344             //   3. Non-relative specfiers resulting from a path through node_modules (e.g. "@foo/bar/path/to/file")
111345             //   4. Relative paths
111346             var nodeModulesSpecifiers;
111347             var pathsSpecifiers;
111348             var relativeSpecifiers;
111349             for (var _i = 0, modulePaths_1 = modulePaths; _i < modulePaths_1.length; _i++) {
111350                 var modulePath = modulePaths_1[_i];
111351                 var specifier = tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions);
111352                 nodeModulesSpecifiers = ts.append(nodeModulesSpecifiers, specifier);
111353                 if (specifier && modulePath.isRedirect) {
111354                     // If we got a specifier for a redirect, it was a bare package specifier (e.g. "@foo/bar",
111355                     // not "@foo/bar/path/to/file"). No other specifier will be this good, so stop looking.
111356                     return nodeModulesSpecifiers;
111357                 }
111358                 if (!specifier && !modulePath.isRedirect) {
111359                     var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, preferences);
111360                     if (ts.pathIsBareSpecifier(local)) {
111361                         pathsSpecifiers = ts.append(pathsSpecifiers, local);
111362                     }
111363                     else if (!importedFileIsInNodeModules || modulePath.isInNodeModules) {
111364                         // Why this extra conditional, not just an `else`? If some path to the file contained
111365                         // 'node_modules', but we can't create a non-relative specifier (e.g. "@foo/bar/path/to/file"),
111366                         // that means we had to go through a *sibling's* node_modules, not one we can access directly.
111367                         // If some path to the file was in node_modules but another was not, this likely indicates that
111368                         // we have a monorepo structure with symlinks. In this case, the non-node_modules path is
111369                         // probably the realpath, e.g. "../bar/path/to/file", but a relative path to another package
111370                         // in a monorepo is probably not portable. So, the module specifier we actually go with will be
111371                         // the relative path through node_modules, so that the declaration emitter can produce a
111372                         // portability error. (See declarationEmitReexportedSymlinkReference3)
111373                         relativeSpecifiers = ts.append(relativeSpecifiers, local);
111374                     }
111375                 }
111376             }
111377             return (pathsSpecifiers === null || pathsSpecifiers === void 0 ? void 0 : pathsSpecifiers.length) ? pathsSpecifiers :
111378                 (nodeModulesSpecifiers === null || nodeModulesSpecifiers === void 0 ? void 0 : nodeModulesSpecifiers.length) ? nodeModulesSpecifiers :
111379                     ts.Debug.checkDefined(relativeSpecifiers);
111380         }
111381         moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
111382         // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
111383         function getInfo(importingSourceFileName, host) {
111384             var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
111385             var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
111386             return { getCanonicalFileName: getCanonicalFileName, importingSourceFileName: importingSourceFileName, sourceDirectory: sourceDirectory };
111387         }
111388         function getLocalModuleSpecifier(moduleFileName, info, compilerOptions, host, _a) {
111389             var ending = _a.ending, relativePreference = _a.relativePreference;
111390             var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
111391             var sourceDirectory = info.sourceDirectory, getCanonicalFileName = info.getCanonicalFileName;
111392             var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
111393                 removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
111394             if (!baseUrl && !paths || relativePreference === 0 /* Relative */) {
111395                 return relativePath;
111396             }
111397             var baseDirectory = ts.getPathsBasePath(compilerOptions, host) || baseUrl;
111398             var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName);
111399             if (!relativeToBaseUrl) {
111400                 return relativePath;
111401             }
111402             var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
111403             var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
111404             var nonRelative = fromPaths === undefined && baseUrl !== undefined ? importRelativeToBaseUrl : fromPaths;
111405             if (!nonRelative) {
111406                 return relativePath;
111407             }
111408             if (relativePreference === 1 /* NonRelative */) {
111409                 return nonRelative;
111410             }
111411             if (relativePreference === 3 /* ExternalNonRelative */) {
111412                 var projectDirectory = host.getCurrentDirectory();
111413                 var modulePath = ts.toPath(moduleFileName, projectDirectory, getCanonicalFileName);
111414                 var sourceIsInternal = ts.startsWith(sourceDirectory, projectDirectory);
111415                 var targetIsInternal = ts.startsWith(modulePath, projectDirectory);
111416                 if (sourceIsInternal && !targetIsInternal || !sourceIsInternal && targetIsInternal) {
111417                     // 1. The import path crosses the boundary of the tsconfig.json-containing directory.
111418                     //
111419                     //      src/
111420                     //        tsconfig.json
111421                     //        index.ts -------
111422                     //      lib/              | (path crosses tsconfig.json)
111423                     //        imported.ts <---
111424                     //
111425                     return nonRelative;
111426                 }
111427                 var nearestTargetPackageJson = getNearestAncestorDirectoryWithPackageJson(host, ts.getDirectoryPath(modulePath));
111428                 var nearestSourcePackageJson = getNearestAncestorDirectoryWithPackageJson(host, sourceDirectory);
111429                 if (nearestSourcePackageJson !== nearestTargetPackageJson) {
111430                     // 2. The importing and imported files are part of different packages.
111431                     //
111432                     //      packages/a/
111433                     //        package.json
111434                     //        index.ts --------
111435                     //      packages/b/        | (path crosses package.json)
111436                     //        package.json     |
111437                     //        component.ts <---
111438                     //
111439                     return nonRelative;
111440                 }
111441                 return relativePath;
111442             }
111443             if (relativePreference !== 2 /* Shortest */)
111444                 ts.Debug.assertNever(relativePreference);
111445             // Prefer a relative import over a baseUrl import if it has fewer components.
111446             return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
111447         }
111448         function countPathComponents(path) {
111449             var count = 0;
111450             for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
111451                 if (path.charCodeAt(i) === 47 /* slash */)
111452                     count++;
111453             }
111454             return count;
111455         }
111456         moduleSpecifiers.countPathComponents = countPathComponents;
111457         function usesJsExtensionOnImports(_a) {
111458             var imports = _a.imports;
111459             return ts.firstDefined(imports, function (_a) {
111460                 var text = _a.text;
111461                 return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined;
111462             }) || false;
111463         }
111464         function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) {
111465             return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareNumberOfDirectorySeparators(a.path, b.path);
111466         }
111467         function getNearestAncestorDirectoryWithPackageJson(host, fileName) {
111468             if (host.getNearestAncestorDirectoryWithPackageJson) {
111469                 return host.getNearestAncestorDirectoryWithPackageJson(fileName);
111470             }
111471             return !!ts.forEachAncestorDirectory(fileName, function (directory) {
111472                 return host.fileExists(ts.combinePaths(directory, "package.json")) ? true : undefined;
111473             });
111474         }
111475         function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) {
111476             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
111477             var cwd = host.getCurrentDirectory();
111478             var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined;
111479             var importedPath = ts.toPath(importedFileName, cwd, getCanonicalFileName);
111480             var redirects = host.redirectTargetsMap.get(importedPath) || ts.emptyArray;
111481             var importedFileNames = __spreadArray(__spreadArray(__spreadArray([], (referenceRedirect ? [referenceRedirect] : ts.emptyArray)), [importedFileName]), redirects);
111482             var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); });
111483             var shouldFilterIgnoredPaths = !ts.every(targets, ts.containsIgnoredPath);
111484             if (!preferSymlinks) {
111485                 // Symlinks inside ignored paths are already filtered out of the symlink cache,
111486                 // so we only need to remove them from the realpath filenames.
111487                 var result_15 = ts.forEach(targets, function (p) { return !(shouldFilterIgnoredPaths && ts.containsIgnoredPath(p)) && cb(p, referenceRedirect === p); });
111488                 if (result_15)
111489                     return result_15;
111490             }
111491             var links = host.getSymlinkCache
111492                 ? host.getSymlinkCache()
111493                 : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd);
111494             var symlinkedDirectories = links.getSymlinkedDirectoriesByRealpath();
111495             var fullImportedFileName = ts.getNormalizedAbsolutePath(importedFileName, cwd);
111496             var result = symlinkedDirectories && ts.forEachAncestorDirectory(ts.getDirectoryPath(fullImportedFileName), function (realPathDirectory) {
111497                 var symlinkDirectories = symlinkedDirectories.get(ts.ensureTrailingDirectorySeparator(ts.toPath(realPathDirectory, cwd, getCanonicalFileName)));
111498                 if (!symlinkDirectories)
111499                     return undefined; // Continue to ancestor directory
111500                 // Don't want to a package to globally import from itself (importNameCodeFix_symlink_own_package.ts)
111501                 if (ts.startsWithDirectory(importingFileName, realPathDirectory, getCanonicalFileName)) {
111502                     return false; // Stop search, each ancestor directory will also hit this condition
111503                 }
111504                 return ts.forEach(targets, function (target) {
111505                     if (!ts.startsWithDirectory(target, realPathDirectory, getCanonicalFileName)) {
111506                         return;
111507                     }
111508                     var relative = ts.getRelativePathFromDirectory(realPathDirectory, target, getCanonicalFileName);
111509                     for (var _i = 0, symlinkDirectories_1 = symlinkDirectories; _i < symlinkDirectories_1.length; _i++) {
111510                         var symlinkDirectory = symlinkDirectories_1[_i];
111511                         var option = ts.resolvePath(symlinkDirectory, relative);
111512                         var result_16 = cb(option, target === referenceRedirect);
111513                         shouldFilterIgnoredPaths = true; // We found a non-ignored path in symlinks, so we can reject ignored-path realpaths
111514                         if (result_16)
111515                             return result_16;
111516                     }
111517                 });
111518             });
111519             return result || (preferSymlinks
111520                 ? ts.forEach(targets, function (p) { return shouldFilterIgnoredPaths && ts.containsIgnoredPath(p) ? undefined : cb(p, p === referenceRedirect); })
111521                 : undefined);
111522         }
111523         moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule;
111524         /**
111525          * Looks for existing imports that use symlinks to this module.
111526          * Symlinks will be returned first so they are preferred over the real path.
111527          */
111528         function getAllModulePaths(importingFileName, importedFileName, host) {
111529             var cwd = host.getCurrentDirectory();
111530             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
111531             var allFileNames = new ts.Map();
111532             var importedFileFromNodeModules = false;
111533             forEachFileNameOfModule(importingFileName, importedFileName, host, 
111534             /*preferSymlinks*/ true, function (path, isRedirect) {
111535                 var isInNodeModules = ts.pathContainsNodeModules(path);
111536                 allFileNames.set(path, { path: getCanonicalFileName(path), isRedirect: isRedirect, isInNodeModules: isInNodeModules });
111537                 importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules;
111538                 // don't return value, so we collect everything
111539             });
111540             // Sort by paths closest to importing file Name directory
111541             var sortedPaths = [];
111542             var _loop_24 = function (directory) {
111543                 var directoryStart = ts.ensureTrailingDirectorySeparator(directory);
111544                 var pathsInDirectory;
111545                 allFileNames.forEach(function (_a, fileName) {
111546                     var path = _a.path, isRedirect = _a.isRedirect, isInNodeModules = _a.isInNodeModules;
111547                     if (ts.startsWith(path, directoryStart)) {
111548                         (pathsInDirectory || (pathsInDirectory = [])).push({ path: fileName, isRedirect: isRedirect, isInNodeModules: isInNodeModules });
111549                         allFileNames.delete(fileName);
111550                     }
111551                 });
111552                 if (pathsInDirectory) {
111553                     if (pathsInDirectory.length > 1) {
111554                         pathsInDirectory.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
111555                     }
111556                     sortedPaths.push.apply(sortedPaths, pathsInDirectory);
111557                 }
111558                 var newDirectory = ts.getDirectoryPath(directory);
111559                 if (newDirectory === directory)
111560                     return out_directory_1 = directory, "break";
111561                 directory = newDirectory;
111562                 out_directory_1 = directory;
111563             };
111564             var out_directory_1;
111565             for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) {
111566                 var state_8 = _loop_24(directory);
111567                 directory = out_directory_1;
111568                 if (state_8 === "break")
111569                     break;
111570             }
111571             if (allFileNames.size) {
111572                 var remainingPaths = ts.arrayFrom(allFileNames.values());
111573                 if (remainingPaths.length > 1)
111574                     remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
111575                 sortedPaths.push.apply(sortedPaths, remainingPaths);
111576             }
111577             return sortedPaths;
111578         }
111579         function tryGetModuleNameFromAmbientModule(moduleSymbol, checker) {
111580             var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
111581             if (decl) {
111582                 return decl.name.text;
111583             }
111584             // the module could be a namespace, which is export through "export=" from an ambient module.
111585             /**
111586              * declare module "m" {
111587              *     namespace ns {
111588              *         class c {}
111589              *     }
111590              *     export = ns;
111591              * }
111592              */
111593             // `import {c} from "m";` is valid, in which case, `moduleSymbol` is "ns", but the module name should be "m"
111594             var ambientModuleDeclareCandidates = ts.mapDefined(moduleSymbol.declarations, function (d) {
111595                 var _a, _b, _c, _d;
111596                 if (!ts.isModuleDeclaration(d))
111597                     return;
111598                 var topNamespace = getTopNamespace(d);
111599                 if (!(((_a = topNamespace === null || topNamespace === void 0 ? void 0 : topNamespace.parent) === null || _a === void 0 ? void 0 : _a.parent)
111600                     && ts.isModuleBlock(topNamespace.parent) && ts.isAmbientModule(topNamespace.parent.parent) && ts.isSourceFile(topNamespace.parent.parent.parent)))
111601                     return;
111602                 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;
111603                 if (!exportAssignment)
111604                     return;
111605                 var exportSymbol = checker.getSymbolAtLocation(exportAssignment);
111606                 if (!exportSymbol)
111607                     return;
111608                 var originalExportSymbol = (exportSymbol === null || exportSymbol === void 0 ? void 0 : exportSymbol.flags) & 2097152 /* Alias */ ? checker.getAliasedSymbol(exportSymbol) : exportSymbol;
111609                 if (originalExportSymbol === d.symbol)
111610                     return topNamespace.parent.parent;
111611                 function getTopNamespace(namespaceDeclaration) {
111612                     while (namespaceDeclaration.flags & 4 /* NestedNamespace */) {
111613                         namespaceDeclaration = namespaceDeclaration.parent;
111614                     }
111615                     return namespaceDeclaration;
111616                 }
111617             });
111618             var ambientModuleDeclare = ambientModuleDeclareCandidates[0];
111619             if (ambientModuleDeclare) {
111620                 return ambientModuleDeclare.name.text;
111621             }
111622         }
111623         function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
111624             for (var key in paths) {
111625                 for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
111626                     var patternText_1 = _a[_i];
111627                     var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
111628                     var indexOfStar = pattern.indexOf("*");
111629                     if (indexOfStar !== -1) {
111630                         var prefix = pattern.substr(0, indexOfStar);
111631                         var suffix = pattern.substr(indexOfStar + 1);
111632                         if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
111633                             ts.startsWith(relativeToBaseUrl, prefix) &&
111634                             ts.endsWith(relativeToBaseUrl, suffix) ||
111635                             !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) {
111636                             var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
111637                             return key.replace("*", matchedStar);
111638                         }
111639                     }
111640                     else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
111641                         return key;
111642                     }
111643                 }
111644             }
111645         }
111646         function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) {
111647             var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
111648             if (normalizedTargetPath === undefined) {
111649                 return undefined;
111650             }
111651             var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
111652             var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
111653             return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs
111654                 ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions)
111655                 : ts.removeFileExtension(relativePath);
111656         }
111657         function tryGetModuleNameAsNodeModule(_a, _b, host, options, packageNameOnly) {
111658             var path = _a.path, isRedirect = _a.isRedirect;
111659             var getCanonicalFileName = _b.getCanonicalFileName, sourceDirectory = _b.sourceDirectory;
111660             if (!host.fileExists || !host.readFile) {
111661                 return undefined;
111662             }
111663             var parts = getNodeModulePathParts(path);
111664             if (!parts) {
111665                 return undefined;
111666             }
111667             // Simplify the full file path to something that can be resolved by Node.
111668             var moduleSpecifier = path;
111669             var isPackageRootPath = false;
111670             if (!packageNameOnly) {
111671                 var packageRootIndex = parts.packageRootIndex;
111672                 var moduleFileNameForExtensionless = void 0;
111673                 while (true) {
111674                     // If the module could be imported by a directory name, use that directory's name
111675                     var _c = tryDirectoryWithPackageJson(packageRootIndex), moduleFileToTry = _c.moduleFileToTry, packageRootPath = _c.packageRootPath;
111676                     if (packageRootPath) {
111677                         moduleSpecifier = packageRootPath;
111678                         isPackageRootPath = true;
111679                         break;
111680                     }
111681                     if (!moduleFileNameForExtensionless)
111682                         moduleFileNameForExtensionless = moduleFileToTry;
111683                     // try with next level of directory
111684                     packageRootIndex = path.indexOf(ts.directorySeparator, packageRootIndex + 1);
111685                     if (packageRootIndex === -1) {
111686                         moduleSpecifier = getExtensionlessFileName(moduleFileNameForExtensionless);
111687                         break;
111688                     }
111689                 }
111690             }
111691             if (isRedirect && !isPackageRootPath) {
111692                 return undefined;
111693             }
111694             var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
111695             // Get a path that's relative to node_modules or the importing file's path
111696             // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
111697             var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
111698             if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
111699                 return undefined;
111700             }
111701             // If the module was found in @types, get the actual Node package name
111702             var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
111703             var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
111704             // For classic resolution, only allow importing from node_modules/@types, not other node_modules
111705             return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;
111706             function tryDirectoryWithPackageJson(packageRootIndex) {
111707                 var packageRootPath = path.substring(0, packageRootIndex);
111708                 var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
111709                 var moduleFileToTry = path;
111710                 if (host.fileExists(packageJsonPath)) {
111711                     var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
111712                     var versionPaths = packageJsonContent.typesVersions
111713                         ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
111714                         : undefined;
111715                     if (versionPaths) {
111716                         var subModuleName = path.slice(packageRootPath.length + 1);
111717                         var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths);
111718                         if (fromPaths !== undefined) {
111719                             moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths);
111720                         }
111721                     }
111722                     // If the file is the main module, it can be imported by the package name
111723                     var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
111724                     if (ts.isString(mainFileRelative)) {
111725                         var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
111726                         if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) {
111727                             return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry };
111728                         }
111729                     }
111730                 }
111731                 return { moduleFileToTry: moduleFileToTry };
111732             }
111733             function getExtensionlessFileName(path) {
111734                 // We still have a file name - remove the extension
111735                 var fullModulePathWithoutExtension = ts.removeFileExtension(path);
111736                 // If the file is /index, it can be imported by its directory name
111737                 // IFF there is not _also_ a file by the same name
111738                 if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
111739                     return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
111740                 }
111741                 return fullModulePathWithoutExtension;
111742             }
111743         }
111744         function tryGetAnyFileFromPath(host, path) {
111745             if (!host.fileExists)
111746                 return;
111747             // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
111748             var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]);
111749             for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) {
111750                 var e = extensions_3[_i];
111751                 var fullPath = path + e;
111752                 if (host.fileExists(fullPath)) {
111753                     return fullPath;
111754                 }
111755             }
111756         }
111757         function getNodeModulePathParts(fullPath) {
111758             // If fullPath can't be valid module file within node_modules, returns undefined.
111759             // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
111760             // Returns indices:                       ^            ^                                                      ^             ^
111761             var topLevelNodeModulesIndex = 0;
111762             var topLevelPackageNameIndex = 0;
111763             var packageRootIndex = 0;
111764             var fileNameIndex = 0;
111765             var States;
111766             (function (States) {
111767                 States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
111768                 States[States["NodeModules"] = 1] = "NodeModules";
111769                 States[States["Scope"] = 2] = "Scope";
111770                 States[States["PackageContent"] = 3] = "PackageContent";
111771             })(States || (States = {}));
111772             var partStart = 0;
111773             var partEnd = 0;
111774             var state = 0 /* BeforeNodeModules */;
111775             while (partEnd >= 0) {
111776                 partStart = partEnd;
111777                 partEnd = fullPath.indexOf("/", partStart + 1);
111778                 switch (state) {
111779                     case 0 /* BeforeNodeModules */:
111780                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
111781                             topLevelNodeModulesIndex = partStart;
111782                             topLevelPackageNameIndex = partEnd;
111783                             state = 1 /* NodeModules */;
111784                         }
111785                         break;
111786                     case 1 /* NodeModules */:
111787                     case 2 /* Scope */:
111788                         if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
111789                             state = 2 /* Scope */;
111790                         }
111791                         else {
111792                             packageRootIndex = partEnd;
111793                             state = 3 /* PackageContent */;
111794                         }
111795                         break;
111796                     case 3 /* PackageContent */:
111797                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
111798                             state = 1 /* NodeModules */;
111799                         }
111800                         else {
111801                             state = 3 /* PackageContent */;
111802                         }
111803                         break;
111804                 }
111805             }
111806             fileNameIndex = partStart;
111807             return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
111808         }
111809         function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
111810             return ts.firstDefined(rootDirs, function (rootDir) {
111811                 var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217
111812                 return isPathRelativeToParent(relativePath) ? undefined : relativePath;
111813             });
111814         }
111815         function removeExtensionAndIndexPostFix(fileName, ending, options) {
111816             if (ts.fileExtensionIs(fileName, ".json" /* Json */))
111817                 return fileName;
111818             var noExtension = ts.removeFileExtension(fileName);
111819             switch (ending) {
111820                 case 0 /* Minimal */:
111821                     return ts.removeSuffix(noExtension, "/index");
111822                 case 1 /* Index */:
111823                     return noExtension;
111824                 case 2 /* JsExtension */:
111825                     return noExtension + getJSExtensionForFile(fileName, options);
111826                 default:
111827                     return ts.Debug.assertNever(ending);
111828             }
111829         }
111830         function getJSExtensionForFile(fileName, options) {
111831             var ext = ts.extensionFromPath(fileName);
111832             switch (ext) {
111833                 case ".ts" /* Ts */:
111834                 case ".d.ts" /* Dts */:
111835                     return ".js" /* Js */;
111836                 case ".tsx" /* Tsx */:
111837                     return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
111838                 case ".js" /* Js */:
111839                 case ".jsx" /* Jsx */:
111840                 case ".json" /* Json */:
111841                     return ext;
111842                 case ".tsbuildinfo" /* TsBuildInfo */:
111843                     return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
111844                 default:
111845                     return ts.Debug.assertNever(ext);
111846             }
111847         }
111848         function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
111849             var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
111850             return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
111851         }
111852         function isPathRelativeToParent(path) {
111853             return ts.startsWith(path, "..");
111854         }
111855     })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
111856 })(ts || (ts = {}));
111857 /*@internal*/
111858 var ts;
111859 (function (ts) {
111860     var sysFormatDiagnosticsHost = ts.sys ? {
111861         getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
111862         getNewLine: function () { return ts.sys.newLine; },
111863         getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
111864     } : undefined; // TODO: GH#18217
111865     /**
111866      * Create a function that reports error by writing to the system and handles the formating of the diagnostic
111867      */
111868     function createDiagnosticReporter(system, pretty) {
111869         var host = system === ts.sys ? sysFormatDiagnosticsHost : {
111870             getCurrentDirectory: function () { return system.getCurrentDirectory(); },
111871             getNewLine: function () { return system.newLine; },
111872             getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames),
111873         };
111874         if (!pretty) {
111875             return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); };
111876         }
111877         var diagnostics = new Array(1);
111878         return function (diagnostic) {
111879             diagnostics[0] = diagnostic;
111880             system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
111881             diagnostics[0] = undefined; // TODO: GH#18217
111882         };
111883     }
111884     ts.createDiagnosticReporter = createDiagnosticReporter;
111885     /**
111886      * @returns Whether the screen was cleared.
111887      */
111888     function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
111889         if (system.clearScreen &&
111890             !options.preserveWatchOutput &&
111891             !options.extendedDiagnostics &&
111892             !options.diagnostics &&
111893             ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
111894             system.clearScreen();
111895             return true;
111896         }
111897         return false;
111898     }
111899     ts.screenStartingMessageCodes = [
111900         ts.Diagnostics.Starting_compilation_in_watch_mode.code,
111901         ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code,
111902     ];
111903     function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
111904         return ts.contains(ts.screenStartingMessageCodes, diagnostic.code)
111905             ? newLine + newLine
111906             : newLine;
111907     }
111908     /**
111909      * Get locale specific time based on whether we are in test mode
111910      */
111911     function getLocaleTimeString(system) {
111912         return !system.now ?
111913             new Date().toLocaleTimeString() :
111914             system.now().toLocaleTimeString("en-US", { timeZone: "UTC" });
111915     }
111916     ts.getLocaleTimeString = getLocaleTimeString;
111917     /**
111918      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
111919      */
111920     function createWatchStatusReporter(system, pretty) {
111921         return pretty ?
111922             function (diagnostic, newLine, options) {
111923                 clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
111924                 var output = "[" + ts.formatColorAndReset(getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] ";
111925                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine);
111926                 system.write(output);
111927             } :
111928             function (diagnostic, newLine, options) {
111929                 var output = "";
111930                 if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) {
111931                     output += newLine;
111932                 }
111933                 output += getLocaleTimeString(system) + " - ";
111934                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine);
111935                 system.write(output);
111936             };
111937     }
111938     ts.createWatchStatusReporter = createWatchStatusReporter;
111939     /** Parses config file using System interface */
111940     function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) {
111941         var host = system;
111942         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); };
111943         var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend);
111944         host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217
111945         return result;
111946     }
111947     ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
111948     function getErrorCountForSummary(diagnostics) {
111949         return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; });
111950     }
111951     ts.getErrorCountForSummary = getErrorCountForSummary;
111952     function getWatchErrorSummaryDiagnosticMessage(errorCount) {
111953         return errorCount === 1 ?
111954             ts.Diagnostics.Found_1_error_Watching_for_file_changes :
111955             ts.Diagnostics.Found_0_errors_Watching_for_file_changes;
111956     }
111957     ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage;
111958     function getErrorSummaryText(errorCount, newLine) {
111959         if (errorCount === 0)
111960             return "";
111961         var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount);
111962         return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine;
111963     }
111964     ts.getErrorSummaryText = getErrorSummaryText;
111965     function isBuilderProgram(program) {
111966         return !!program.getState;
111967     }
111968     ts.isBuilderProgram = isBuilderProgram;
111969     function listFiles(program, write) {
111970         var options = program.getCompilerOptions();
111971         if (options.explainFiles) {
111972             explainFiles(isBuilderProgram(program) ? program.getProgram() : program, write);
111973         }
111974         else if (options.listFiles || options.listFilesOnly) {
111975             ts.forEach(program.getSourceFiles(), function (file) {
111976                 write(file.fileName);
111977             });
111978         }
111979     }
111980     ts.listFiles = listFiles;
111981     function explainFiles(program, write) {
111982         var _a, _b;
111983         var reasons = program.getFileIncludeReasons();
111984         var getCanonicalFileName = ts.createGetCanonicalFileName(program.useCaseSensitiveFileNames());
111985         var relativeFileName = function (fileName) { return ts.convertToRelativePath(fileName, program.getCurrentDirectory(), getCanonicalFileName); };
111986         for (var _i = 0, _c = program.getSourceFiles(); _i < _c.length; _i++) {
111987             var file = _c[_i];
111988             write("" + toFileName(file, relativeFileName));
111989             (_a = reasons.get(file.path)) === null || _a === void 0 ? void 0 : _a.forEach(function (reason) { return write("  " + fileIncludeReasonToDiagnostics(program, reason, relativeFileName).messageText); });
111990             (_b = explainIfFileIsRedirect(file, relativeFileName)) === null || _b === void 0 ? void 0 : _b.forEach(function (d) { return write("  " + d.messageText); });
111991         }
111992     }
111993     ts.explainFiles = explainFiles;
111994     function explainIfFileIsRedirect(file, fileNameConvertor) {
111995         var result;
111996         if (file.path !== file.resolvedPath) {
111997             (result || (result = [])).push(ts.chainDiagnosticMessages(
111998             /*details*/ undefined, ts.Diagnostics.File_is_output_of_project_reference_source_0, toFileName(file.originalFileName, fileNameConvertor)));
111999         }
112000         if (file.redirectInfo) {
112001             (result || (result = [])).push(ts.chainDiagnosticMessages(
112002             /*details*/ undefined, ts.Diagnostics.File_redirects_to_file_0, toFileName(file.redirectInfo.redirectTarget, fileNameConvertor)));
112003         }
112004         return result;
112005     }
112006     ts.explainIfFileIsRedirect = explainIfFileIsRedirect;
112007     function getMatchedFileSpec(program, fileName) {
112008         var _a;
112009         var configFile = program.getCompilerOptions().configFile;
112010         if (!((_a = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _a === void 0 ? void 0 : _a.validatedFilesSpec))
112011             return undefined;
112012         var getCanonicalFileName = ts.createGetCanonicalFileName(program.useCaseSensitiveFileNames());
112013         var filePath = getCanonicalFileName(fileName);
112014         var basePath = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory()));
112015         return ts.find(configFile.configFileSpecs.validatedFilesSpec, function (fileSpec) { return getCanonicalFileName(ts.getNormalizedAbsolutePath(fileSpec, basePath)) === filePath; });
112016     }
112017     ts.getMatchedFileSpec = getMatchedFileSpec;
112018     function getMatchedIncludeSpec(program, fileName) {
112019         var _a, _b;
112020         var configFile = program.getCompilerOptions().configFile;
112021         if (!((_a = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _a === void 0 ? void 0 : _a.validatedIncludeSpecs))
112022             return undefined;
112023         var isJsonFile = ts.fileExtensionIs(fileName, ".json" /* Json */);
112024         var basePath = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFile.fileName, program.getCurrentDirectory()));
112025         var useCaseSensitiveFileNames = program.useCaseSensitiveFileNames();
112026         return ts.find((_b = configFile === null || configFile === void 0 ? void 0 : configFile.configFileSpecs) === null || _b === void 0 ? void 0 : _b.validatedIncludeSpecs, function (includeSpec) {
112027             if (isJsonFile && !ts.endsWith(includeSpec, ".json" /* Json */))
112028                 return false;
112029             var pattern = ts.getPatternFromSpec(includeSpec, basePath, "files");
112030             return !!pattern && ts.getRegexFromPattern("(" + pattern + ")$", useCaseSensitiveFileNames).test(fileName);
112031         });
112032     }
112033     ts.getMatchedIncludeSpec = getMatchedIncludeSpec;
112034     function fileIncludeReasonToDiagnostics(program, reason, fileNameConvertor) {
112035         var _a, _b;
112036         var options = program.getCompilerOptions();
112037         if (ts.isReferencedFile(reason)) {
112038             var referenceLocation = ts.getReferencedFileLocation(function (path) { return program.getSourceFileByPath(path); }, reason);
112039             var referenceText = ts.isReferenceFileLocation(referenceLocation) ? referenceLocation.file.text.substring(referenceLocation.pos, referenceLocation.end) : "\"" + referenceLocation.text + "\"";
112040             var message = void 0;
112041             ts.Debug.assert(ts.isReferenceFileLocation(referenceLocation) || reason.kind === ts.FileIncludeKind.Import, "Only synthetic references are imports");
112042             switch (reason.kind) {
112043                 case ts.FileIncludeKind.Import:
112044                     if (ts.isReferenceFileLocation(referenceLocation)) {
112045                         message = referenceLocation.packageId ?
112046                             ts.Diagnostics.Imported_via_0_from_file_1_with_packageId_2 :
112047                             ts.Diagnostics.Imported_via_0_from_file_1;
112048                     }
112049                     else if (referenceLocation.text === ts.externalHelpersModuleNameText) {
112050                         message = referenceLocation.packageId ?
112051                             ts.Diagnostics.Imported_via_0_from_file_1_with_packageId_2_to_import_importHelpers_as_specified_in_compilerOptions :
112052                             ts.Diagnostics.Imported_via_0_from_file_1_to_import_importHelpers_as_specified_in_compilerOptions;
112053                     }
112054                     else {
112055                         message = referenceLocation.packageId ?
112056                             ts.Diagnostics.Imported_via_0_from_file_1_with_packageId_2_to_import_jsx_and_jsxs_factory_functions :
112057                             ts.Diagnostics.Imported_via_0_from_file_1_to_import_jsx_and_jsxs_factory_functions;
112058                     }
112059                     break;
112060                 case ts.FileIncludeKind.ReferenceFile:
112061                     ts.Debug.assert(!referenceLocation.packageId);
112062                     message = ts.Diagnostics.Referenced_via_0_from_file_1;
112063                     break;
112064                 case ts.FileIncludeKind.TypeReferenceDirective:
112065                     message = referenceLocation.packageId ?
112066                         ts.Diagnostics.Type_library_referenced_via_0_from_file_1_with_packageId_2 :
112067                         ts.Diagnostics.Type_library_referenced_via_0_from_file_1;
112068                     break;
112069                 case ts.FileIncludeKind.LibReferenceDirective:
112070                     ts.Debug.assert(!referenceLocation.packageId);
112071                     message = ts.Diagnostics.Library_referenced_via_0_from_file_1;
112072                     break;
112073                 default:
112074                     ts.Debug.assertNever(reason);
112075             }
112076             return ts.chainDiagnosticMessages(
112077             /*details*/ undefined, message, referenceText, toFileName(referenceLocation.file, fileNameConvertor), referenceLocation.packageId && ts.packageIdToString(referenceLocation.packageId));
112078         }
112079         switch (reason.kind) {
112080             case ts.FileIncludeKind.RootFile:
112081                 if (!((_a = options.configFile) === null || _a === void 0 ? void 0 : _a.configFileSpecs))
112082                     return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Root_file_specified_for_compilation);
112083                 var fileName = ts.getNormalizedAbsolutePath(program.getRootFileNames()[reason.index], program.getCurrentDirectory());
112084                 var matchedByFiles = getMatchedFileSpec(program, fileName);
112085                 if (matchedByFiles)
112086                     return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Part_of_files_list_in_tsconfig_json);
112087                 var matchedByInclude = getMatchedIncludeSpec(program, fileName);
112088                 return matchedByInclude ?
112089                     ts.chainDiagnosticMessages(
112090                     /*details*/ undefined, ts.Diagnostics.Matched_by_include_pattern_0_in_1, matchedByInclude, toFileName(options.configFile, fileNameConvertor)) :
112091                     // Could be additional files specified as roots
112092                     ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Root_file_specified_for_compilation);
112093             case ts.FileIncludeKind.SourceFromProjectReference:
112094             case ts.FileIncludeKind.OutputFromProjectReference:
112095                 var isOutput = reason.kind === ts.FileIncludeKind.OutputFromProjectReference;
112096                 var referencedResolvedRef = ts.Debug.checkDefined((_b = program.getResolvedProjectReferences()) === null || _b === void 0 ? void 0 : _b[reason.index]);
112097                 return ts.chainDiagnosticMessages(
112098                 /*details*/ undefined, ts.outFile(options) ?
112099                     isOutput ?
112100                         ts.Diagnostics.Output_from_referenced_project_0_included_because_1_specified :
112101                         ts.Diagnostics.Source_from_referenced_project_0_included_because_1_specified :
112102                     isOutput ?
112103                         ts.Diagnostics.Output_from_referenced_project_0_included_because_module_is_specified_as_none :
112104                         ts.Diagnostics.Source_from_referenced_project_0_included_because_module_is_specified_as_none, toFileName(referencedResolvedRef.sourceFile.fileName, fileNameConvertor), options.outFile ? "--outFile" : "--out");
112105             case ts.FileIncludeKind.AutomaticTypeDirectiveFile:
112106                 return ts.chainDiagnosticMessages(
112107                 /*details*/ undefined, options.types ?
112108                     reason.packageId ?
112109                         ts.Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions_with_packageId_1 :
112110                         ts.Diagnostics.Entry_point_of_type_library_0_specified_in_compilerOptions :
112111                     reason.packageId ?
112112                         ts.Diagnostics.Entry_point_for_implicit_type_library_0_with_packageId_1 :
112113                         ts.Diagnostics.Entry_point_for_implicit_type_library_0, reason.typeReference, reason.packageId && ts.packageIdToString(reason.packageId));
112114             case ts.FileIncludeKind.LibFile:
112115                 if (reason.index !== undefined)
112116                     return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Library_0_specified_in_compilerOptions, options.lib[reason.index]);
112117                 var target = ts.forEachEntry(ts.targetOptionDeclaration.type, function (value, key) { return value === options.target ? key : undefined; });
112118                 return ts.chainDiagnosticMessages(
112119                 /*details*/ undefined, target ?
112120                     ts.Diagnostics.Default_library_for_target_0 :
112121                     ts.Diagnostics.Default_library, target);
112122             default:
112123                 ts.Debug.assertNever(reason);
112124         }
112125     }
112126     ts.fileIncludeReasonToDiagnostics = fileIncludeReasonToDiagnostics;
112127     function toFileName(file, fileNameConvertor) {
112128         var fileName = ts.isString(file) ? file : file.fileName;
112129         return fileNameConvertor ? fileNameConvertor(fileName) : fileName;
112130     }
112131     /**
112132      * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
112133      */
112134     function emitFilesAndReportErrors(program, reportDiagnostic, write, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
112135         var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
112136         // First get and report any syntactic errors.
112137         var allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
112138         var configFileParsingDiagnosticsLength = allDiagnostics.length;
112139         ts.addRange(allDiagnostics, program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
112140         // If we didn't have any syntactic errors, then also try getting the global and
112141         // semantic errors.
112142         if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
112143             ts.addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken));
112144             if (!isListFilesOnly) {
112145                 ts.addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken));
112146                 if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
112147                     ts.addRange(allDiagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
112148                 }
112149             }
112150         }
112151         // Emit and report any errors we ran into.
112152         var emitResult = isListFilesOnly
112153             ? { emitSkipped: true, diagnostics: ts.emptyArray }
112154             : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
112155         var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics;
112156         ts.addRange(allDiagnostics, emitDiagnostics);
112157         var diagnostics = ts.sortAndDeduplicateDiagnostics(allDiagnostics);
112158         diagnostics.forEach(reportDiagnostic);
112159         if (write) {
112160             var currentDir_1 = program.getCurrentDirectory();
112161             ts.forEach(emittedFiles, function (file) {
112162                 var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
112163                 write("TSFILE: " + filepath);
112164             });
112165             listFiles(program, write);
112166         }
112167         if (reportSummary) {
112168             reportSummary(getErrorCountForSummary(diagnostics));
112169         }
112170         return {
112171             emitResult: emitResult,
112172             diagnostics: diagnostics,
112173         };
112174     }
112175     ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
112176     function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, write, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
112177         var _a = emitFilesAndReportErrors(program, reportDiagnostic, write, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), emitResult = _a.emitResult, diagnostics = _a.diagnostics;
112178         if (emitResult.emitSkipped && diagnostics.length > 0) {
112179             // If the emitter didn't emit anything, then pass that value along.
112180             return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
112181         }
112182         else if (diagnostics.length > 0) {
112183             // The emitter emitted something, inform the caller if that happened in the presence
112184             // of diagnostics or not.
112185             return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated;
112186         }
112187         return ts.ExitStatus.Success;
112188     }
112189     ts.emitFilesAndReportErrorsAndGetExitStatus = emitFilesAndReportErrorsAndGetExitStatus;
112190     ts.noopFileWatcher = { close: ts.noop };
112191     ts.returnNoopFileWatcher = function () { return ts.noopFileWatcher; };
112192     function createWatchHost(system, reportWatchStatus) {
112193         if (system === void 0) { system = ts.sys; }
112194         var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
112195         return {
112196             onWatchStatusChange: onWatchStatusChange,
112197             watchFile: ts.maybeBind(system, system.watchFile) || ts.returnNoopFileWatcher,
112198             watchDirectory: ts.maybeBind(system, system.watchDirectory) || ts.returnNoopFileWatcher,
112199             setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop,
112200             clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop
112201         };
112202     }
112203     ts.createWatchHost = createWatchHost;
112204     ts.WatchType = {
112205         ConfigFile: "Config file",
112206         ExtendedConfigFile: "Extended config file",
112207         SourceFile: "Source file",
112208         MissingFile: "Missing file",
112209         WildcardDirectory: "Wild card directory",
112210         FailedLookupLocations: "Failed Lookup Locations",
112211         TypeRoots: "Type roots"
112212     };
112213     function createWatchFactory(host, options) {
112214         var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None;
112215         var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop;
112216         var result = ts.getWatchFactory(host, watchLogLevel, writeLog);
112217         result.writeLog = writeLog;
112218         return result;
112219     }
112220     ts.createWatchFactory = createWatchFactory;
112221     function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) {
112222         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
112223         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
112224         var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); });
112225         return {
112226             getSourceFile: function (fileName, languageVersion, onError) {
112227                 var text;
112228                 try {
112229                     ts.performance.mark("beforeIORead");
112230                     text = host.readFile(fileName, getCompilerOptions().charset);
112231                     ts.performance.mark("afterIORead");
112232                     ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
112233                 }
112234                 catch (e) {
112235                     if (onError) {
112236                         onError(e.message);
112237                     }
112238                     text = "";
112239                 }
112240                 return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined;
112241             },
112242             getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation),
112243             getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
112244             writeFile: writeFile,
112245             getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }),
112246             useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
112247             getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames),
112248             getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); },
112249             fileExists: function (f) { return host.fileExists(f); },
112250             readFile: function (f) { return host.readFile(f); },
112251             trace: ts.maybeBind(host, host.trace),
112252             directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists),
112253             getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories),
112254             realpath: ts.maybeBind(host, host.realpath),
112255             getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }),
112256             createHash: ts.maybeBind(host, host.createHash),
112257             readDirectory: ts.maybeBind(host, host.readDirectory),
112258         };
112259         function writeFile(fileName, text, writeByteOrderMark, onError) {
112260             try {
112261                 ts.performance.mark("beforeIOWrite");
112262                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
112263                 // the host.writeFile will do its own directory creation and
112264                 // the ensureDirectoriesExist call will always be redundant.
112265                 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); });
112266                 ts.performance.mark("afterIOWrite");
112267                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
112268             }
112269             catch (e) {
112270                 if (onError) {
112271                     onError(e.message);
112272                 }
112273             }
112274         }
112275     }
112276     ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
112277     function setGetSourceFileAsHashVersioned(compilerHost, host) {
112278         var originalGetSourceFile = compilerHost.getSourceFile;
112279         var computeHash = ts.maybeBind(host, host.createHash) || ts.generateDjb2Hash;
112280         compilerHost.getSourceFile = function () {
112281             var args = [];
112282             for (var _i = 0; _i < arguments.length; _i++) {
112283                 args[_i] = arguments[_i];
112284             }
112285             var result = originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArray([compilerHost], args));
112286             if (result) {
112287                 result.version = computeHash(result.text);
112288             }
112289             return result;
112290         };
112291     }
112292     ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
112293     /**
112294      * Creates the watch compiler host that can be extended with config file or root file names and options host
112295      */
112296     function createProgramHost(system, createProgram) {
112297         var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); });
112298         return {
112299             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
112300             getNewLine: function () { return system.newLine; },
112301             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
112302             getDefaultLibLocation: getDefaultLibLocation,
112303             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
112304             fileExists: function (path) { return system.fileExists(path); },
112305             readFile: function (path, encoding) { return system.readFile(path, encoding); },
112306             directoryExists: function (path) { return system.directoryExists(path); },
112307             getDirectories: function (path) { return system.getDirectories(path); },
112308             readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); },
112309             realpath: ts.maybeBind(system, system.realpath),
112310             getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable),
112311             trace: function (s) { return system.write(s + system.newLine); },
112312             createDirectory: function (path) { return system.createDirectory(path); },
112313             writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
112314             createHash: ts.maybeBind(system, system.createHash),
112315             createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
112316         };
112317     }
112318     ts.createProgramHost = createProgramHost;
112319     /**
112320      * Creates the watch compiler host that can be extended with config file or root file names and options host
112321      */
112322     function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
112323         if (system === void 0) { system = ts.sys; }
112324         var write = function (s) { return system.write(s + system.newLine); };
112325         var result = createProgramHost(system, createProgram);
112326         ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
112327         result.afterProgramCreate = function (builderProgram) {
112328             var compilerOptions = builderProgram.getCompilerOptions();
112329             var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; });
112330             emitFilesAndReportErrors(builderProgram, reportDiagnostic, write, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions, errorCount); });
112331         };
112332         return result;
112333     }
112334     /**
112335      * Report error and exit
112336      */
112337     function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
112338         reportDiagnostic(diagnostic);
112339         system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
112340     }
112341     /**
112342      * Creates the watch compiler host from system for config file in watch mode
112343      */
112344     function createWatchCompilerHostOfConfigFile(_a) {
112345         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;
112346         var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
112347         var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus);
112348         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); };
112349         host.configFileName = configFileName;
112350         host.optionsToExtend = optionsToExtend;
112351         host.watchOptionsToExtend = watchOptionsToExtend;
112352         host.extraFileExtensions = extraFileExtensions;
112353         return host;
112354     }
112355     ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile;
112356     /**
112357      * Creates the watch compiler host from system for compiling root files and options in watch mode
112358      */
112359     function createWatchCompilerHostOfFilesAndCompilerOptions(_a) {
112360         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;
112361         var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus);
112362         host.rootFiles = rootFiles;
112363         host.options = options;
112364         host.watchOptions = watchOptions;
112365         host.projectReferences = projectReferences;
112366         return host;
112367     }
112368     ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
112369     function performIncrementalCompilation(input) {
112370         var system = input.system || ts.sys;
112371         var host = input.host || (input.host = ts.createIncrementalCompilerHost(input.options, system));
112372         var builderProgram = ts.createIncrementalProgram(input);
112373         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);
112374         if (input.afterProgramEmitAndDiagnostics)
112375             input.afterProgramEmitAndDiagnostics(builderProgram);
112376         return exitStatus;
112377     }
112378     ts.performIncrementalCompilation = performIncrementalCompilation;
112379 })(ts || (ts = {}));
112380 var ts;
112381 (function (ts) {
112382     function readBuilderProgram(compilerOptions, host) {
112383         if (ts.outFile(compilerOptions))
112384             return undefined;
112385         var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions);
112386         if (!buildInfoPath)
112387             return undefined;
112388         var content = host.readFile(buildInfoPath);
112389         if (!content)
112390             return undefined;
112391         var buildInfo = ts.getBuildInfo(content);
112392         if (buildInfo.version !== ts.version)
112393             return undefined;
112394         if (!buildInfo.program)
112395             return undefined;
112396         return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host);
112397     }
112398     ts.readBuilderProgram = readBuilderProgram;
112399     function createIncrementalCompilerHost(options, system) {
112400         if (system === void 0) { system = ts.sys; }
112401         var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
112402         host.createHash = ts.maybeBind(system, system.createHash);
112403         ts.setGetSourceFileAsHashVersioned(host, system);
112404         ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
112405         return host;
112406     }
112407     ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
112408     function createIncrementalProgram(_a) {
112409         var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
112410         host = host || createIncrementalCompilerHost(options);
112411         createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
112412         var oldProgram = readBuilderProgram(options, host);
112413         return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
112414     }
112415     ts.createIncrementalProgram = createIncrementalProgram;
112416     function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) {
112417         if (ts.isArray(rootFilesOrConfigFileName)) {
112418             return ts.createWatchCompilerHostOfFilesAndCompilerOptions({
112419                 rootFiles: rootFilesOrConfigFileName,
112420                 options: options,
112421                 watchOptions: watchOptionsOrExtraFileExtensions,
112422                 projectReferences: projectReferencesOrWatchOptionsToExtend,
112423                 system: system,
112424                 createProgram: createProgram,
112425                 reportDiagnostic: reportDiagnostic,
112426                 reportWatchStatus: reportWatchStatus,
112427             });
112428         }
112429         else {
112430             return ts.createWatchCompilerHostOfConfigFile({
112431                 configFileName: rootFilesOrConfigFileName,
112432                 optionsToExtend: options,
112433                 watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend,
112434                 extraFileExtensions: watchOptionsOrExtraFileExtensions,
112435                 system: system,
112436                 createProgram: createProgram,
112437                 reportDiagnostic: reportDiagnostic,
112438                 reportWatchStatus: reportWatchStatus,
112439             });
112440         }
112441     }
112442     ts.createWatchCompilerHost = createWatchCompilerHost;
112443     function createWatchProgram(host) {
112444         var builderProgram;
112445         var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
112446         var extendedConfigFilesMap; // Map of file watchers for the extended config files
112447         var missingFilesMap; // Map of file watchers for the missing files
112448         var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file
112449         var timerToUpdateProgram; // timer callback to recompile the program
112450         var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations
112451         var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info
112452         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
112453         var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
112454         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
112455         var currentDirectory = host.getCurrentDirectory();
112456         var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram;
112457         var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences;
112458         var wildcardDirectories;
112459         var configFileParsingDiagnostics;
112460         var canConfigFileJsonReportNoInputFiles = false;
112461         var hasChangedConfigFileParsingErrors = false;
112462         var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
112463         var directoryStructureHost = cachedDirectoryStructureHost || host;
112464         var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost);
112465         // From tsc we want to get already parsed result and hence check for rootFileNames
112466         var newLine = updateNewLine();
112467         if (configFileName && host.configFileParsingResult) {
112468             setConfigFileParsingResult(host.configFileParsingResult);
112469             newLine = updateNewLine();
112470         }
112471         reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode);
112472         if (configFileName && !host.configFileParsingResult) {
112473             newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); });
112474             ts.Debug.assert(!rootFileNames);
112475             parseConfigFile();
112476             newLine = updateNewLine();
112477         }
112478         var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
112479         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
112480         writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
112481         var configFileWatcher;
112482         if (configFileName) {
112483             configFileWatcher = watchFile(configFileName, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ConfigFile);
112484         }
112485         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
112486         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
112487         // Members for CompilerHost
112488         var getNewSourceFile = compilerHost.getSourceFile;
112489         compilerHost.getSourceFile = function (fileName) {
112490             var args = [];
112491             for (var _i = 1; _i < arguments.length; _i++) {
112492                 args[_i - 1] = arguments[_i];
112493             }
112494             return getVersionedSourceFileByPath.apply(void 0, __spreadArray([fileName, toPath(fileName)], args));
112495         };
112496         compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
112497         compilerHost.getNewLine = function () { return newLine; };
112498         compilerHost.fileExists = fileExists;
112499         compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
112500         // Members for ResolutionCacheHost
112501         compilerHost.toPath = toPath;
112502         compilerHost.getCompilationSettings = function () { return compilerOptions; };
112503         compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect);
112504         compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); };
112505         compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); };
112506         compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; };
112507         compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations = scheduleInvalidateResolutionsOfFailedLookupLocations;
112508         compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
112509         compilerHost.onChangedAutomaticTypeDirectiveNames = scheduleProgramUpdate;
112510         compilerHost.fileIsOpen = ts.returnFalse;
112511         compilerHost.getCurrentProgram = getCurrentProgram;
112512         compilerHost.writeLog = writeLog;
112513         // Cache for the module resolution
112514         var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ?
112515             ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) :
112516             currentDirectory, 
112517         /*logChangesWhenResolvingModule*/ false);
112518         // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
112519         compilerHost.resolveModuleNames = host.resolveModuleNames ?
112520             (function () {
112521                 var args = [];
112522                 for (var _i = 0; _i < arguments.length; _i++) {
112523                     args[_i] = arguments[_i];
112524                 }
112525                 return host.resolveModuleNames.apply(host, args);
112526             }) :
112527             (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); });
112528         compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
112529             (function () {
112530                 var args = [];
112531                 for (var _i = 0; _i < arguments.length; _i++) {
112532                     args[_i] = arguments[_i];
112533                 }
112534                 return host.resolveTypeReferenceDirectives.apply(host, args);
112535             }) :
112536             (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
112537         var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
112538         builderProgram = readBuilderProgram(compilerOptions, compilerHost);
112539         synchronizeProgram();
112540         // Update the wild card directory watch
112541         watchConfigFileWildCardDirectories();
112542         // Update extended config file watch
112543         watchExtendedConfigFiles();
112544         return configFileName ?
112545             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } :
112546             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close };
112547         function close() {
112548             clearInvalidateResolutionsOfFailedLookupLocations();
112549             resolutionCache.clear();
112550             ts.clearMap(sourceFilesCache, function (value) {
112551                 if (value && value.fileWatcher) {
112552                     value.fileWatcher.close();
112553                     value.fileWatcher = undefined;
112554                 }
112555             });
112556             if (configFileWatcher) {
112557                 configFileWatcher.close();
112558                 configFileWatcher = undefined;
112559             }
112560             if (extendedConfigFilesMap) {
112561                 ts.clearMap(extendedConfigFilesMap, ts.closeFileWatcher);
112562                 extendedConfigFilesMap = undefined;
112563             }
112564             if (watchedWildcardDirectories) {
112565                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
112566                 watchedWildcardDirectories = undefined;
112567             }
112568             if (missingFilesMap) {
112569                 ts.clearMap(missingFilesMap, ts.closeFileWatcher);
112570                 missingFilesMap = undefined;
112571             }
112572         }
112573         function getCurrentBuilderProgram() {
112574             return builderProgram;
112575         }
112576         function getCurrentProgram() {
112577             return builderProgram && builderProgram.getProgramOrUndefined();
112578         }
112579         function synchronizeProgram() {
112580             writeLog("Synchronizing program");
112581             clearInvalidateResolutionsOfFailedLookupLocations();
112582             var program = getCurrentBuilderProgram();
112583             if (hasChangedCompilerOptions) {
112584                 newLine = updateNewLine();
112585                 if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
112586                     resolutionCache.clear();
112587                 }
112588             }
112589             // All resolutions are invalid if user provided resolutions
112590             var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution);
112591             if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
112592                 if (hasChangedConfigFileParsingErrors) {
112593                     builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
112594                     hasChangedConfigFileParsingErrors = false;
112595                 }
112596             }
112597             else {
112598                 createNewProgram(hasInvalidatedResolution);
112599             }
112600             if (host.afterProgramCreate && program !== builderProgram) {
112601                 host.afterProgramCreate(builderProgram);
112602             }
112603             return builderProgram;
112604         }
112605         function createNewProgram(hasInvalidatedResolution) {
112606             // Compile the program
112607             writeLog("CreatingProgramWith::");
112608             writeLog("  roots: " + JSON.stringify(rootFileNames));
112609             writeLog("  options: " + JSON.stringify(compilerOptions));
112610             var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
112611             hasChangedCompilerOptions = false;
112612             hasChangedConfigFileParsingErrors = false;
112613             resolutionCache.startCachingPerDirectoryResolution();
112614             compilerHost.hasInvalidatedResolution = hasInvalidatedResolution;
112615             compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
112616             builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
112617             resolutionCache.finishCachingPerDirectoryResolution();
112618             // Update watches
112619             ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = new ts.Map()), watchMissingFilePath);
112620             if (needsUpdateInTypeRootWatch) {
112621                 resolutionCache.updateTypeRootsWatch();
112622             }
112623             if (missingFilePathsRequestedForRelease) {
112624                 // These are the paths that program creater told us as not in use any more but were missing on the disk.
112625                 // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO,
112626                 // if there is already watcher for it (for missing files)
112627                 // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed
112628                 // so that at later time we have correct result of their presence
112629                 for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) {
112630                     var missingFilePath = missingFilePathsRequestedForRelease_1[_i];
112631                     if (!missingFilesMap.has(missingFilePath)) {
112632                         sourceFilesCache.delete(missingFilePath);
112633                     }
112634                 }
112635                 missingFilePathsRequestedForRelease = undefined;
112636             }
112637         }
112638         function updateRootFileNames(files) {
112639             ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode");
112640             rootFileNames = files;
112641             scheduleProgramUpdate();
112642         }
112643         function updateNewLine() {
112644             return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); });
112645         }
112646         function toPath(fileName) {
112647             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
112648         }
112649         function isFileMissingOnHost(hostSourceFile) {
112650             return typeof hostSourceFile === "boolean";
112651         }
112652         function isFilePresenceUnknownOnHost(hostSourceFile) {
112653             return typeof hostSourceFile.version === "boolean";
112654         }
112655         function fileExists(fileName) {
112656             var path = toPath(fileName);
112657             // If file is missing on host from cache, we can definitely say file doesnt exist
112658             // otherwise we need to ensure from the disk
112659             if (isFileMissingOnHost(sourceFilesCache.get(path))) {
112660                 return false;
112661             }
112662             return directoryStructureHost.fileExists(fileName);
112663         }
112664         function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) {
112665             var hostSourceFile = sourceFilesCache.get(path);
112666             // No source file on the host
112667             if (isFileMissingOnHost(hostSourceFile)) {
112668                 return undefined;
112669             }
112670             // Create new source file if requested or the versions dont match
112671             if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
112672                 var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
112673                 if (hostSourceFile) {
112674                     if (sourceFile) {
112675                         // Set the source file and create file watcher now that file was present on the disk
112676                         hostSourceFile.sourceFile = sourceFile;
112677                         hostSourceFile.version = sourceFile.version;
112678                         if (!hostSourceFile.fileWatcher) {
112679                             hostSourceFile.fileWatcher = watchFilePath(path, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, ts.WatchType.SourceFile);
112680                         }
112681                     }
112682                     else {
112683                         // There is no source file on host any more, close the watch, missing file paths will track it
112684                         if (hostSourceFile.fileWatcher) {
112685                             hostSourceFile.fileWatcher.close();
112686                         }
112687                         sourceFilesCache.set(path, false);
112688                     }
112689                 }
112690                 else {
112691                     if (sourceFile) {
112692                         var fileWatcher = watchFilePath(path, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, ts.WatchType.SourceFile);
112693                         sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
112694                     }
112695                     else {
112696                         sourceFilesCache.set(path, false);
112697                     }
112698                 }
112699                 return sourceFile;
112700             }
112701             return hostSourceFile.sourceFile;
112702         }
112703         function nextSourceFileVersion(path) {
112704             var hostSourceFile = sourceFilesCache.get(path);
112705             if (hostSourceFile !== undefined) {
112706                 if (isFileMissingOnHost(hostSourceFile)) {
112707                     // The next version, lets set it as presence unknown file
112708                     sourceFilesCache.set(path, { version: false });
112709                 }
112710                 else {
112711                     hostSourceFile.version = false;
112712                 }
112713             }
112714         }
112715         function getSourceVersion(path) {
112716             var hostSourceFile = sourceFilesCache.get(path);
112717             return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
112718         }
112719         function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
112720             var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
112721             // If this is the source file thats in the cache and new program doesnt need it,
112722             // remove the cached entry.
112723             // Note we arent deleting entry if file became missing in new program or
112724             // there was version update and new source file was created.
112725             if (hostSourceFileInfo !== undefined) {
112726                 // record the missing file paths so they can be removed later if watchers arent tracking them
112727                 if (isFileMissingOnHost(hostSourceFileInfo)) {
112728                     (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
112729                 }
112730                 else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
112731                     if (hostSourceFileInfo.fileWatcher) {
112732                         hostSourceFileInfo.fileWatcher.close();
112733                     }
112734                     sourceFilesCache.delete(oldSourceFile.resolvedPath);
112735                     if (!hasSourceFileByPath) {
112736                         resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
112737                     }
112738                 }
112739             }
112740         }
112741         function reportWatchDiagnostic(message) {
112742             if (host.onWatchStatusChange) {
112743                 host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile);
112744             }
112745         }
112746         function hasChangedAutomaticTypeDirectiveNames() {
112747             return resolutionCache.hasChangedAutomaticTypeDirectiveNames();
112748         }
112749         function clearInvalidateResolutionsOfFailedLookupLocations() {
112750             if (!timerToInvalidateFailedLookupResolutions)
112751                 return false;
112752             host.clearTimeout(timerToInvalidateFailedLookupResolutions);
112753             timerToInvalidateFailedLookupResolutions = undefined;
112754             return true;
112755         }
112756         function scheduleInvalidateResolutionsOfFailedLookupLocations() {
112757             if (!host.setTimeout || !host.clearTimeout) {
112758                 return resolutionCache.invalidateResolutionsOfFailedLookupLocations();
112759             }
112760             var pending = clearInvalidateResolutionsOfFailedLookupLocations();
112761             writeLog("Scheduling invalidateFailedLookup" + (pending ? ", Cancelled earlier one" : ""));
112762             timerToInvalidateFailedLookupResolutions = host.setTimeout(invalidateResolutionsOfFailedLookup, 250);
112763         }
112764         function invalidateResolutionsOfFailedLookup() {
112765             timerToInvalidateFailedLookupResolutions = undefined;
112766             if (resolutionCache.invalidateResolutionsOfFailedLookupLocations()) {
112767                 scheduleProgramUpdate();
112768             }
112769         }
112770         // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch
112771         // operations (such as saving all modified files in an editor) a chance to complete before we kick
112772         // off a new compilation.
112773         function scheduleProgramUpdate() {
112774             if (!host.setTimeout || !host.clearTimeout) {
112775                 return;
112776             }
112777             if (timerToUpdateProgram) {
112778                 host.clearTimeout(timerToUpdateProgram);
112779             }
112780             writeLog("Scheduling update");
112781             timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250);
112782         }
112783         function scheduleProgramReload() {
112784             ts.Debug.assert(!!configFileName);
112785             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
112786             scheduleProgramUpdate();
112787         }
112788         function updateProgramWithWatchStatus() {
112789             timerToUpdateProgram = undefined;
112790             reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
112791             updateProgram();
112792         }
112793         function updateProgram() {
112794             switch (reloadLevel) {
112795                 case ts.ConfigFileProgramReloadLevel.Partial:
112796                     ts.perfLogger.logStartUpdateProgram("PartialConfigReload");
112797                     reloadFileNamesFromConfigFile();
112798                     break;
112799                 case ts.ConfigFileProgramReloadLevel.Full:
112800                     ts.perfLogger.logStartUpdateProgram("FullConfigReload");
112801                     reloadConfigFile();
112802                     break;
112803                 default:
112804                     ts.perfLogger.logStartUpdateProgram("SynchronizeProgram");
112805                     synchronizeProgram();
112806                     break;
112807             }
112808             ts.perfLogger.logStopUpdateProgram("Done");
112809             return getCurrentBuilderProgram();
112810         }
112811         function reloadFileNamesFromConfigFile() {
112812             writeLog("Reloading new file names and options");
112813             rootFileNames = ts.getFileNamesFromConfigSpecs(compilerOptions.configFile.configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions);
112814             if (ts.updateErrorForNoInputFiles(rootFileNames, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), compilerOptions.configFile.configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
112815                 hasChangedConfigFileParsingErrors = true;
112816             }
112817             // Update the program
112818             synchronizeProgram();
112819         }
112820         function reloadConfigFile() {
112821             writeLog("Reloading config file: " + configFileName);
112822             reloadLevel = ts.ConfigFileProgramReloadLevel.None;
112823             if (cachedDirectoryStructureHost) {
112824                 cachedDirectoryStructureHost.clearCache();
112825             }
112826             parseConfigFile();
112827             hasChangedCompilerOptions = true;
112828             synchronizeProgram();
112829             // Update the wild card directory watch
112830             watchConfigFileWildCardDirectories();
112831             // Update extended config file watch
112832             watchExtendedConfigFiles();
112833         }
112834         function parseConfigFile() {
112835             setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217
112836         }
112837         function setConfigFileParsingResult(configFileParseResult) {
112838             rootFileNames = configFileParseResult.fileNames;
112839             compilerOptions = configFileParseResult.options;
112840             watchOptions = configFileParseResult.watchOptions;
112841             projectReferences = configFileParseResult.projectReferences;
112842             wildcardDirectories = configFileParseResult.wildcardDirectories;
112843             configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice();
112844             canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInputFiles(configFileParseResult.raw);
112845             hasChangedConfigFileParsingErrors = true;
112846         }
112847         function watchFilePath(path, file, callback, pollingInterval, options, watchType) {
112848             return watchFile(file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options, watchType);
112849         }
112850         function onSourceFileChange(fileName, eventKind, path) {
112851             updateCachedSystemWithFile(fileName, path, eventKind);
112852             // Update the source file cache
112853             if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
112854                 resolutionCache.invalidateResolutionOfFile(path);
112855             }
112856             resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
112857             nextSourceFileVersion(path);
112858             // Update the program
112859             scheduleProgramUpdate();
112860         }
112861         function updateCachedSystemWithFile(fileName, path, eventKind) {
112862             if (cachedDirectoryStructureHost) {
112863                 cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind);
112864             }
112865         }
112866         function watchMissingFilePath(missingFilePath) {
112867             return watchFilePath(missingFilePath, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, ts.WatchType.MissingFile);
112868         }
112869         function onMissingFileChange(fileName, eventKind, missingFilePath) {
112870             updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
112871             if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) {
112872                 missingFilesMap.get(missingFilePath).close();
112873                 missingFilesMap.delete(missingFilePath);
112874                 // Delete the entry in the source files cache so that new source file is created
112875                 nextSourceFileVersion(missingFilePath);
112876                 // When a missing file is created, we should update the graph.
112877                 scheduleProgramUpdate();
112878             }
112879         }
112880         function watchConfigFileWildCardDirectories() {
112881             if (wildcardDirectories) {
112882                 ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = new ts.Map()), new ts.Map(ts.getEntries(wildcardDirectories)), watchWildcardDirectory);
112883             }
112884             else if (watchedWildcardDirectories) {
112885                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
112886             }
112887         }
112888         function watchWildcardDirectory(directory, flags) {
112889             return watchDirectory(directory, function (fileOrDirectory) {
112890                 ts.Debug.assert(!!configFileName);
112891                 var fileOrDirectoryPath = toPath(fileOrDirectory);
112892                 // Since the file existence changed, update the sourceFiles cache
112893                 if (cachedDirectoryStructureHost) {
112894                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
112895                 }
112896                 nextSourceFileVersion(fileOrDirectoryPath);
112897                 if (ts.isIgnoredFileFromWildCardWatching({
112898                     watchedDirPath: toPath(directory),
112899                     fileOrDirectory: fileOrDirectory,
112900                     fileOrDirectoryPath: fileOrDirectoryPath,
112901                     configFileName: configFileName,
112902                     extraFileExtensions: extraFileExtensions,
112903                     options: compilerOptions,
112904                     program: getCurrentBuilderProgram(),
112905                     currentDirectory: currentDirectory,
112906                     useCaseSensitiveFileNames: useCaseSensitiveFileNames,
112907                     writeLog: writeLog
112908                 }))
112909                     return;
112910                 // Reload is pending, do the reload
112911                 if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) {
112912                     reloadLevel = ts.ConfigFileProgramReloadLevel.Partial;
112913                     // Schedule Update the program
112914                     scheduleProgramUpdate();
112915                 }
112916             }, flags, watchOptions, ts.WatchType.WildcardDirectory);
112917         }
112918         function watchExtendedConfigFiles() {
112919             var _a;
112920             // Update the extended config files watcher
112921             ts.mutateMap(extendedConfigFilesMap || (extendedConfigFilesMap = new ts.Map()), ts.arrayToMap(((_a = compilerOptions.configFile) === null || _a === void 0 ? void 0 : _a.extendedSourceFiles) || ts.emptyArray, toPath), {
112922                 // Watch the extended config files
112923                 createNewValue: watchExtendedConfigFile,
112924                 // Config files that are no longer extended should no longer be watched.
112925                 onDeleteValue: ts.closeFileWatcher
112926             });
112927         }
112928         function watchExtendedConfigFile(extendedConfigFile) {
112929             return watchFile(extendedConfigFile, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ExtendedConfigFile);
112930         }
112931     }
112932     ts.createWatchProgram = createWatchProgram;
112933 })(ts || (ts = {}));
112934 /*@internal*/
112935 var ts;
112936 (function (ts) {
112937     var UpToDateStatusType;
112938     (function (UpToDateStatusType) {
112939         UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
112940         UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
112941         /**
112942          * The project appears out of date because its upstream inputs are newer than its outputs,
112943          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
112944          * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
112945          */
112946         UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
112947         /**
112948          * The project appears out of date because its upstream inputs are newer than its outputs,
112949          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
112950          * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
112951          */
112952         UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
112953         UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
112954         UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
112955         UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
112956         UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
112957         UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
112958         UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
112959         UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
112960         /**
112961          * Projects with no outputs (i.e. "solution" files)
112962          */
112963         UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
112964     })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
112965     function resolveConfigFileProjectName(project) {
112966         if (ts.fileExtensionIs(project, ".json" /* Json */)) {
112967             return project;
112968         }
112969         return ts.combinePaths(project, "tsconfig.json");
112970     }
112971     ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
112972 })(ts || (ts = {}));
112973 var ts;
112974 (function (ts) {
112975     var minimumDate = new Date(-8640000000000000);
112976     var maximumDate = new Date(8640000000000000);
112977     var BuildResultFlags;
112978     (function (BuildResultFlags) {
112979         BuildResultFlags[BuildResultFlags["None"] = 0] = "None";
112980         /**
112981          * No errors of any kind occurred during build
112982          */
112983         BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success";
112984         /**
112985          * None of the .d.ts files emitted by this build were
112986          * different from the existing files on disk
112987          */
112988         BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged";
112989         BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors";
112990         BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors";
112991         BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors";
112992         BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors";
112993         BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors";
112994         BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors";
112995     })(BuildResultFlags || (BuildResultFlags = {}));
112996     function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) {
112997         var existingValue = configFileMap.get(resolved);
112998         var newValue;
112999         if (!existingValue) {
113000             newValue = createT();
113001             configFileMap.set(resolved, newValue);
113002         }
113003         return existingValue || newValue;
113004     }
113005     function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
113006         return getOrCreateValueFromConfigFileMap(configFileMap, resolved, function () { return new ts.Map(); });
113007     }
113008     function newer(date1, date2) {
113009         return date2 > date1 ? date2 : date1;
113010     }
113011     function isDeclarationFile(fileName) {
113012         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
113013     }
113014     /*@internal*/
113015     function isCircularBuildOrder(buildOrder) {
113016         return !!buildOrder && !!buildOrder.buildOrder;
113017     }
113018     ts.isCircularBuildOrder = isCircularBuildOrder;
113019     /*@internal*/
113020     function getBuildOrderFromAnyBuildOrder(anyBuildOrder) {
113021         return isCircularBuildOrder(anyBuildOrder) ? anyBuildOrder.buildOrder : anyBuildOrder;
113022     }
113023     ts.getBuildOrderFromAnyBuildOrder = getBuildOrderFromAnyBuildOrder;
113024     /**
113025      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
113026      */
113027     function createBuilderStatusReporter(system, pretty) {
113028         return function (diagnostic) {
113029             var output = pretty ? "[" + ts.formatColorAndReset(ts.getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] " : ts.getLocaleTimeString(system) + " - ";
113030             output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine);
113031             system.write(output);
113032         };
113033     }
113034     ts.createBuilderStatusReporter = createBuilderStatusReporter;
113035     function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
113036         var host = ts.createProgramHost(system, createProgram);
113037         host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
113038         host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
113039         host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
113040         host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
113041         host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
113042         host.now = ts.maybeBind(system, system.now); // For testing
113043         return host;
113044     }
113045     function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
113046         if (system === void 0) { system = ts.sys; }
113047         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
113048         host.reportErrorSummary = reportErrorSummary;
113049         return host;
113050     }
113051     ts.createSolutionBuilderHost = createSolutionBuilderHost;
113052     function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
113053         if (system === void 0) { system = ts.sys; }
113054         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
113055         var watchHost = ts.createWatchHost(system, reportWatchStatus);
113056         ts.copyProperties(host, watchHost);
113057         return host;
113058     }
113059     ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost;
113060     function getCompilerOptionsOfBuildOptions(buildOptions) {
113061         var result = {};
113062         ts.commonOptionsWithBuild.forEach(function (option) {
113063             if (ts.hasProperty(buildOptions, option.name))
113064                 result[option.name] = buildOptions[option.name];
113065         });
113066         return result;
113067     }
113068     function createSolutionBuilder(host, rootNames, defaultOptions) {
113069         return createSolutionBuilderWorker(/*watch*/ false, host, rootNames, defaultOptions);
113070     }
113071     ts.createSolutionBuilder = createSolutionBuilder;
113072     function createSolutionBuilderWithWatch(host, rootNames, defaultOptions, baseWatchOptions) {
113073         return createSolutionBuilderWorker(/*watch*/ true, host, rootNames, defaultOptions, baseWatchOptions);
113074     }
113075     ts.createSolutionBuilderWithWatch = createSolutionBuilderWithWatch;
113076     function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
113077         var host = hostOrHostWithWatch;
113078         var hostWithWatch = hostOrHostWithWatch;
113079         var currentDirectory = host.getCurrentDirectory();
113080         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
113081         // State of the solution
113082         var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
113083         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return state.projectCompilerOptions; });
113084         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
113085         compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); };
113086         compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames);
113087         compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives);
113088         var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined;
113089         if (!compilerHost.resolveModuleNames) {
113090             var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; };
113091             compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) {
113092                 return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3);
113093             };
113094         }
113095         var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
113096         var state = {
113097             host: host,
113098             hostWithWatch: hostWithWatch,
113099             currentDirectory: currentDirectory,
113100             getCanonicalFileName: getCanonicalFileName,
113101             parseConfigFileHost: ts.parseConfigHostFromCompilerHostLike(host),
113102             write: ts.maybeBind(host, host.trace),
113103             // State of solution
113104             options: options,
113105             baseCompilerOptions: baseCompilerOptions,
113106             rootNames: rootNames,
113107             baseWatchOptions: baseWatchOptions,
113108             resolvedConfigFilePaths: new ts.Map(),
113109             configFileCache: new ts.Map(),
113110             projectStatus: new ts.Map(),
113111             buildInfoChecked: new ts.Map(),
113112             extendedConfigCache: new ts.Map(),
113113             builderPrograms: new ts.Map(),
113114             diagnostics: new ts.Map(),
113115             projectPendingBuild: new ts.Map(),
113116             projectErrorsReported: new ts.Map(),
113117             compilerHost: compilerHost,
113118             moduleResolutionCache: moduleResolutionCache,
113119             // Mutable state
113120             buildOrder: undefined,
113121             readFileWithCache: function (f) { return host.readFile(f); },
113122             projectCompilerOptions: baseCompilerOptions,
113123             cache: undefined,
113124             allProjectBuildPending: true,
113125             needsSummary: true,
113126             watchAllProjectsPending: watch,
113127             currentInvalidatedProject: undefined,
113128             // Watch state
113129             watch: watch,
113130             allWatchedWildcardDirectories: new ts.Map(),
113131             allWatchedInputFiles: new ts.Map(),
113132             allWatchedConfigFiles: new ts.Map(),
113133             allWatchedExtendedConfigFiles: new ts.Map(),
113134             timerToBuildInvalidatedProject: undefined,
113135             reportFileChangeDetected: false,
113136             watchFile: watchFile,
113137             watchDirectory: watchDirectory,
113138             writeLog: writeLog,
113139         };
113140         return state;
113141     }
113142     function toPath(state, fileName) {
113143         return ts.toPath(fileName, state.currentDirectory, state.getCanonicalFileName);
113144     }
113145     function toResolvedConfigFilePath(state, fileName) {
113146         var resolvedConfigFilePaths = state.resolvedConfigFilePaths;
113147         var path = resolvedConfigFilePaths.get(fileName);
113148         if (path !== undefined)
113149             return path;
113150         var resolvedPath = toPath(state, fileName);
113151         resolvedConfigFilePaths.set(fileName, resolvedPath);
113152         return resolvedPath;
113153     }
113154     function isParsedCommandLine(entry) {
113155         return !!entry.options;
113156     }
113157     function parseConfigFile(state, configFileName, configFilePath) {
113158         var configFileCache = state.configFileCache;
113159         var value = configFileCache.get(configFilePath);
113160         if (value) {
113161             return isParsedCommandLine(value) ? value : undefined;
113162         }
113163         var diagnostic;
113164         var parseConfigFileHost = state.parseConfigFileHost, baseCompilerOptions = state.baseCompilerOptions, baseWatchOptions = state.baseWatchOptions, extendedConfigCache = state.extendedConfigCache, host = state.host;
113165         var parsed;
113166         if (host.getParsedCommandLine) {
113167             parsed = host.getParsedCommandLine(configFileName);
113168             if (!parsed)
113169                 diagnostic = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
113170         }
113171         else {
113172             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; };
113173             parsed = ts.getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions);
113174             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop;
113175         }
113176         configFileCache.set(configFilePath, parsed || diagnostic);
113177         return parsed;
113178     }
113179     function resolveProjectName(state, name) {
113180         return ts.resolveConfigFileProjectName(ts.resolvePath(state.currentDirectory, name));
113181     }
113182     function createBuildOrder(state, roots) {
113183         var temporaryMarks = new ts.Map();
113184         var permanentMarks = new ts.Map();
113185         var circularityReportStack = [];
113186         var buildOrder;
113187         var circularDiagnostics;
113188         for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
113189             var root = roots_1[_i];
113190             visit(root);
113191         }
113192         return circularDiagnostics ?
113193             { buildOrder: buildOrder || ts.emptyArray, circularDiagnostics: circularDiagnostics } :
113194             buildOrder || ts.emptyArray;
113195         function visit(configFileName, inCircularContext) {
113196             var projPath = toResolvedConfigFilePath(state, configFileName);
113197             // Already visited
113198             if (permanentMarks.has(projPath))
113199                 return;
113200             // Circular
113201             if (temporaryMarks.has(projPath)) {
113202                 if (!inCircularContext) {
113203                     (circularDiagnostics || (circularDiagnostics = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")));
113204                 }
113205                 return;
113206             }
113207             temporaryMarks.set(projPath, true);
113208             circularityReportStack.push(configFileName);
113209             var parsed = parseConfigFile(state, configFileName, projPath);
113210             if (parsed && parsed.projectReferences) {
113211                 for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) {
113212                     var ref = _a[_i];
113213                     var resolvedRefPath = resolveProjectName(state, ref.path);
113214                     visit(resolvedRefPath, inCircularContext || ref.circular);
113215                 }
113216             }
113217             circularityReportStack.pop();
113218             permanentMarks.set(projPath, true);
113219             (buildOrder || (buildOrder = [])).push(configFileName);
113220         }
113221     }
113222     function getBuildOrder(state) {
113223         return state.buildOrder || createStateBuildOrder(state);
113224     }
113225     function createStateBuildOrder(state) {
113226         var buildOrder = createBuildOrder(state, state.rootNames.map(function (f) { return resolveProjectName(state, f); }));
113227         // Clear all to ResolvedConfigFilePaths cache to start fresh
113228         state.resolvedConfigFilePaths.clear();
113229         // TODO(rbuckton): Should be a `Set`, but that requires changing the code below that uses `mutateMapSkippingNewValues`
113230         var currentProjects = new ts.Map(getBuildOrderFromAnyBuildOrder(buildOrder).map(function (resolved) { return [toResolvedConfigFilePath(state, resolved), true]; }));
113231         var noopOnDelete = { onDeleteValue: ts.noop };
113232         // Config file cache
113233         ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete);
113234         ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete);
113235         ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete);
113236         ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete);
113237         ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete);
113238         ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete);
113239         ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete);
113240         // Remove watches for the program no longer in the solution
113241         if (state.watch) {
113242             ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher });
113243             state.allWatchedExtendedConfigFiles.forEach(function (watcher) {
113244                 watcher.projects.forEach(function (project) {
113245                     if (!currentProjects.has(project)) {
113246                         watcher.projects.delete(project);
113247                     }
113248                 });
113249                 watcher.close();
113250             });
113251             ts.mutateMapSkippingNewValues(state.allWatchedWildcardDirectories, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcherOf); } });
113252             ts.mutateMapSkippingNewValues(state.allWatchedInputFiles, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcher); } });
113253         }
113254         return state.buildOrder = buildOrder;
113255     }
113256     function getBuildOrderFor(state, project, onlyReferences) {
113257         var resolvedProject = project && resolveProjectName(state, project);
113258         var buildOrderFromState = getBuildOrder(state);
113259         if (isCircularBuildOrder(buildOrderFromState))
113260             return buildOrderFromState;
113261         if (resolvedProject) {
113262             var projectPath_1 = toResolvedConfigFilePath(state, resolvedProject);
113263             var projectIndex = ts.findIndex(buildOrderFromState, function (configFileName) { return toResolvedConfigFilePath(state, configFileName) === projectPath_1; });
113264             if (projectIndex === -1)
113265                 return undefined;
113266         }
113267         var buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState;
113268         ts.Debug.assert(!isCircularBuildOrder(buildOrder));
113269         ts.Debug.assert(!onlyReferences || resolvedProject !== undefined);
113270         ts.Debug.assert(!onlyReferences || buildOrder[buildOrder.length - 1] === resolvedProject);
113271         return onlyReferences ? buildOrder.slice(0, buildOrder.length - 1) : buildOrder;
113272     }
113273     function enableCache(state) {
113274         if (state.cache) {
113275             disableCache(state);
113276         }
113277         var compilerHost = state.compilerHost, host = state.host;
113278         var originalReadFileWithCache = state.readFileWithCache;
113279         var originalGetSourceFile = compilerHost.getSourceFile;
113280         var _a = ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return toPath(state, fileName); }, function () {
113281             var args = [];
113282             for (var _i = 0; _i < arguments.length; _i++) {
113283                 args[_i] = arguments[_i];
113284             }
113285             return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArray([compilerHost], args));
113286         }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, readFileWithCache = _a.readFileWithCache;
113287         state.readFileWithCache = readFileWithCache;
113288         compilerHost.getSourceFile = getSourceFileWithCache;
113289         state.cache = {
113290             originalReadFile: originalReadFile,
113291             originalFileExists: originalFileExists,
113292             originalDirectoryExists: originalDirectoryExists,
113293             originalCreateDirectory: originalCreateDirectory,
113294             originalWriteFile: originalWriteFile,
113295             originalReadFileWithCache: originalReadFileWithCache,
113296             originalGetSourceFile: originalGetSourceFile,
113297         };
113298     }
113299     function disableCache(state) {
113300         if (!state.cache)
113301             return;
113302         var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache;
113303         host.readFile = cache.originalReadFile;
113304         host.fileExists = cache.originalFileExists;
113305         host.directoryExists = cache.originalDirectoryExists;
113306         host.createDirectory = cache.originalCreateDirectory;
113307         host.writeFile = cache.originalWriteFile;
113308         compilerHost.getSourceFile = cache.originalGetSourceFile;
113309         state.readFileWithCache = cache.originalReadFileWithCache;
113310         extendedConfigCache.clear();
113311         if (moduleResolutionCache) {
113312             moduleResolutionCache.directoryToModuleNameMap.clear();
113313             moduleResolutionCache.moduleNameToDirectoryMap.clear();
113314         }
113315         state.cache = undefined;
113316     }
113317     function clearProjectStatus(state, resolved) {
113318         state.projectStatus.delete(resolved);
113319         state.diagnostics.delete(resolved);
113320     }
113321     function addProjToQueue(_a, proj, reloadLevel) {
113322         var projectPendingBuild = _a.projectPendingBuild;
113323         var value = projectPendingBuild.get(proj);
113324         if (value === undefined) {
113325             projectPendingBuild.set(proj, reloadLevel);
113326         }
113327         else if (value < reloadLevel) {
113328             projectPendingBuild.set(proj, reloadLevel);
113329         }
113330     }
113331     function setupInitialBuild(state, cancellationToken) {
113332         // Set initial build if not already built
113333         if (!state.allProjectBuildPending)
113334             return;
113335         state.allProjectBuildPending = false;
113336         if (state.options.watch) {
113337             reportWatchStatus(state, ts.Diagnostics.Starting_compilation_in_watch_mode);
113338         }
113339         enableCache(state);
113340         var buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state));
113341         buildOrder.forEach(function (configFileName) {
113342             return state.projectPendingBuild.set(toResolvedConfigFilePath(state, configFileName), ts.ConfigFileProgramReloadLevel.None);
113343         });
113344         if (cancellationToken) {
113345             cancellationToken.throwIfCancellationRequested();
113346         }
113347     }
113348     var InvalidatedProjectKind;
113349     (function (InvalidatedProjectKind) {
113350         InvalidatedProjectKind[InvalidatedProjectKind["Build"] = 0] = "Build";
113351         InvalidatedProjectKind[InvalidatedProjectKind["UpdateBundle"] = 1] = "UpdateBundle";
113352         InvalidatedProjectKind[InvalidatedProjectKind["UpdateOutputFileStamps"] = 2] = "UpdateOutputFileStamps";
113353     })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {}));
113354     function doneInvalidatedProject(state, projectPath) {
113355         state.projectPendingBuild.delete(projectPath);
113356         state.currentInvalidatedProject = undefined;
113357         return state.diagnostics.has(projectPath) ?
113358             ts.ExitStatus.DiagnosticsPresent_OutputsSkipped :
113359             ts.ExitStatus.Success;
113360     }
113361     function createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder) {
113362         var updateOutputFileStampsPending = true;
113363         return {
113364             kind: InvalidatedProjectKind.UpdateOutputFileStamps,
113365             project: project,
113366             projectPath: projectPath,
113367             buildOrder: buildOrder,
113368             getCompilerOptions: function () { return config.options; },
113369             getCurrentDirectory: function () { return state.currentDirectory; },
113370             updateOutputFileStatmps: function () {
113371                 updateOutputTimestamps(state, config, projectPath);
113372                 updateOutputFileStampsPending = false;
113373             },
113374             done: function () {
113375                 if (updateOutputFileStampsPending) {
113376                     updateOutputTimestamps(state, config, projectPath);
113377                 }
113378                 return doneInvalidatedProject(state, projectPath);
113379             }
113380         };
113381     }
113382     var BuildStep;
113383     (function (BuildStep) {
113384         BuildStep[BuildStep["CreateProgram"] = 0] = "CreateProgram";
113385         BuildStep[BuildStep["SyntaxDiagnostics"] = 1] = "SyntaxDiagnostics";
113386         BuildStep[BuildStep["SemanticDiagnostics"] = 2] = "SemanticDiagnostics";
113387         BuildStep[BuildStep["Emit"] = 3] = "Emit";
113388         BuildStep[BuildStep["EmitBundle"] = 4] = "EmitBundle";
113389         BuildStep[BuildStep["EmitBuildInfo"] = 5] = "EmitBuildInfo";
113390         BuildStep[BuildStep["BuildInvalidatedProjectOfBundle"] = 6] = "BuildInvalidatedProjectOfBundle";
113391         BuildStep[BuildStep["QueueReferencingProjects"] = 7] = "QueueReferencingProjects";
113392         BuildStep[BuildStep["Done"] = 8] = "Done";
113393     })(BuildStep || (BuildStep = {}));
113394     function createBuildOrUpdateInvalidedProject(kind, state, project, projectPath, projectIndex, config, buildOrder) {
113395         var step = kind === InvalidatedProjectKind.Build ? BuildStep.CreateProgram : BuildStep.EmitBundle;
113396         var program;
113397         var buildResult;
113398         var invalidatedProjectOfBundle;
113399         return kind === InvalidatedProjectKind.Build ?
113400             {
113401                 kind: kind,
113402                 project: project,
113403                 projectPath: projectPath,
113404                 buildOrder: buildOrder,
113405                 getCompilerOptions: function () { return config.options; },
113406                 getCurrentDirectory: function () { return state.currentDirectory; },
113407                 getBuilderProgram: function () { return withProgramOrUndefined(ts.identity); },
113408                 getProgram: function () {
113409                     return withProgramOrUndefined(function (program) { return program.getProgramOrUndefined(); });
113410                 },
113411                 getSourceFile: function (fileName) {
113412                     return withProgramOrUndefined(function (program) { return program.getSourceFile(fileName); });
113413                 },
113414                 getSourceFiles: function () {
113415                     return withProgramOrEmptyArray(function (program) { return program.getSourceFiles(); });
113416                 },
113417                 getOptionsDiagnostics: function (cancellationToken) {
113418                     return withProgramOrEmptyArray(function (program) { return program.getOptionsDiagnostics(cancellationToken); });
113419                 },
113420                 getGlobalDiagnostics: function (cancellationToken) {
113421                     return withProgramOrEmptyArray(function (program) { return program.getGlobalDiagnostics(cancellationToken); });
113422                 },
113423                 getConfigFileParsingDiagnostics: function () {
113424                     return withProgramOrEmptyArray(function (program) { return program.getConfigFileParsingDiagnostics(); });
113425                 },
113426                 getSyntacticDiagnostics: function (sourceFile, cancellationToken) {
113427                     return withProgramOrEmptyArray(function (program) { return program.getSyntacticDiagnostics(sourceFile, cancellationToken); });
113428                 },
113429                 getAllDependencies: function (sourceFile) {
113430                     return withProgramOrEmptyArray(function (program) { return program.getAllDependencies(sourceFile); });
113431                 },
113432                 getSemanticDiagnostics: function (sourceFile, cancellationToken) {
113433                     return withProgramOrEmptyArray(function (program) { return program.getSemanticDiagnostics(sourceFile, cancellationToken); });
113434                 },
113435                 getSemanticDiagnosticsOfNextAffectedFile: function (cancellationToken, ignoreSourceFile) {
113436                     return withProgramOrUndefined(function (program) {
113437                         return (program.getSemanticDiagnosticsOfNextAffectedFile) &&
113438                             program.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile);
113439                     });
113440                 },
113441                 emit: function (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
113442                     if (targetSourceFile || emitOnlyDtsFiles) {
113443                         return withProgramOrUndefined(function (program) { return program.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); });
113444                     }
113445                     executeSteps(BuildStep.SemanticDiagnostics, cancellationToken);
113446                     if (step === BuildStep.EmitBuildInfo) {
113447                         return emitBuildInfo(writeFile, cancellationToken);
113448                     }
113449                     if (step !== BuildStep.Emit)
113450                         return undefined;
113451                     return emit(writeFile, cancellationToken, customTransformers);
113452                 },
113453                 done: done
113454             } :
113455             {
113456                 kind: kind,
113457                 project: project,
113458                 projectPath: projectPath,
113459                 buildOrder: buildOrder,
113460                 getCompilerOptions: function () { return config.options; },
113461                 getCurrentDirectory: function () { return state.currentDirectory; },
113462                 emit: function (writeFile, customTransformers) {
113463                     if (step !== BuildStep.EmitBundle)
113464                         return invalidatedProjectOfBundle;
113465                     return emitBundle(writeFile, customTransformers);
113466                 },
113467                 done: done,
113468             };
113469         function done(cancellationToken, writeFile, customTransformers) {
113470             executeSteps(BuildStep.Done, cancellationToken, writeFile, customTransformers);
113471             return doneInvalidatedProject(state, projectPath);
113472         }
113473         function withProgramOrUndefined(action) {
113474             executeSteps(BuildStep.CreateProgram);
113475             return program && action(program);
113476         }
113477         function withProgramOrEmptyArray(action) {
113478             return withProgramOrUndefined(action) || ts.emptyArray;
113479         }
113480         function createProgram() {
113481             ts.Debug.assert(program === undefined);
113482             if (state.options.dry) {
113483                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project);
113484                 buildResult = BuildResultFlags.Success;
113485                 step = BuildStep.QueueReferencingProjects;
113486                 return;
113487             }
113488             if (state.options.verbose)
113489                 reportStatus(state, ts.Diagnostics.Building_project_0, project);
113490             if (config.fileNames.length === 0) {
113491                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
113492                 // Nothing to build - must be a solution file, basically
113493                 buildResult = BuildResultFlags.None;
113494                 step = BuildStep.QueueReferencingProjects;
113495                 return;
113496             }
113497             var host = state.host, compilerHost = state.compilerHost;
113498             state.projectCompilerOptions = config.options;
113499             // Update module resolution cache if needed
113500             updateModuleResolutionCache(state, project, config);
113501             // Create program
113502             program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences);
113503             if (state.watch) {
113504                 state.builderPrograms.set(projectPath, program);
113505             }
113506             step++;
113507         }
113508         function handleDiagnostics(diagnostics, errorFlags, errorType) {
113509             var _a;
113510             if (diagnostics.length) {
113511                 (_a = buildErrors(state, projectPath, program, config, diagnostics, errorFlags, errorType), buildResult = _a.buildResult, step = _a.step);
113512             }
113513             else {
113514                 step++;
113515             }
113516         }
113517         function getSyntaxDiagnostics(cancellationToken) {
113518             ts.Debug.assertIsDefined(program);
113519             handleDiagnostics(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], program.getConfigFileParsingDiagnostics()), program.getOptionsDiagnostics(cancellationToken)), program.getGlobalDiagnostics(cancellationToken)), program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)), BuildResultFlags.SyntaxErrors, "Syntactic");
113520         }
113521         function getSemanticDiagnostics(cancellationToken) {
113522             handleDiagnostics(ts.Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, "Semantic");
113523         }
113524         function emit(writeFileCallback, cancellationToken, customTransformers) {
113525             var _a;
113526             ts.Debug.assertIsDefined(program);
113527             ts.Debug.assert(step === BuildStep.Emit);
113528             // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
113529             program.backupState();
113530             var declDiagnostics;
113531             var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
113532             var outputFiles = [];
113533             var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, 
113534             /*write*/ undefined, 
113535             /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, 
113536             /*emitOnlyDts*/ false, customTransformers).emitResult;
113537             // Don't emit .d.ts if there are decl file errors
113538             if (declDiagnostics) {
113539                 program.restoreState();
113540                 (_a = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"), buildResult = _a.buildResult, step = _a.step);
113541                 return {
113542                     emitSkipped: true,
113543                     diagnostics: emitResult.diagnostics
113544                 };
113545             }
113546             // Actual Emit
113547             var host = state.host, compilerHost = state.compilerHost;
113548             var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
113549             var newestDeclarationFileContentChangedTime = minimumDate;
113550             var anyDtsChanged = false;
113551             var emitterDiagnostics = ts.createDiagnosticCollection();
113552             var emittedOutputs = new ts.Map();
113553             outputFiles.forEach(function (_a) {
113554                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
113555                 var priorChangeTime;
113556                 if (!anyDtsChanged && isDeclarationFile(name)) {
113557                     // Check for unchanged .d.ts files
113558                     if (host.fileExists(name) && state.readFileWithCache(name) === text) {
113559                         priorChangeTime = host.getModifiedTime(name);
113560                     }
113561                     else {
113562                         resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
113563                         anyDtsChanged = true;
113564                     }
113565                 }
113566                 emittedOutputs.set(toPath(state, name), name);
113567                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
113568                 if (priorChangeTime !== undefined) {
113569                     newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
113570                 }
113571             });
113572             finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, 
113573             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags);
113574             return emitResult;
113575         }
113576         function emitBuildInfo(writeFileCallback, cancellationToken) {
113577             ts.Debug.assertIsDefined(program);
113578             ts.Debug.assert(step === BuildStep.EmitBuildInfo);
113579             var emitResult = program.emitBuildInfo(writeFileCallback, cancellationToken);
113580             if (emitResult.diagnostics.length) {
113581                 reportErrors(state, emitResult.diagnostics);
113582                 state.diagnostics.set(projectPath, __spreadArray(__spreadArray([], state.diagnostics.get(projectPath)), emitResult.diagnostics));
113583                 buildResult = BuildResultFlags.EmitErrors & buildResult;
113584             }
113585             if (emitResult.emittedFiles && state.write) {
113586                 emitResult.emittedFiles.forEach(function (name) { return listEmittedFile(state, config, name); });
113587             }
113588             afterProgramDone(state, program, config);
113589             step = BuildStep.QueueReferencingProjects;
113590             return emitResult;
113591         }
113592         function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) {
113593             var _a;
113594             var emitDiagnostics = emitterDiagnostics.getDiagnostics();
113595             if (emitDiagnostics.length) {
113596                 (_a = buildErrors(state, projectPath, program, config, emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"), buildResult = _a.buildResult, step = _a.step);
113597                 return emitDiagnostics;
113598             }
113599             if (state.write) {
113600                 emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); });
113601             }
113602             // Update time stamps for rest of the outputs
113603             var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
113604             state.diagnostics.delete(projectPath);
113605             state.projectStatus.set(projectPath, {
113606                 type: ts.UpToDateStatusType.UpToDate,
113607                 newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ?
113608                     maximumDate :
113609                     newestDeclarationFileContentChangedTime,
113610                 oldestOutputFileName: oldestOutputFileName
113611             });
113612             afterProgramDone(state, program, config);
113613             step = BuildStep.QueueReferencingProjects;
113614             buildResult = resultFlags;
113615             return emitDiagnostics;
113616         }
113617         function emitBundle(writeFileCallback, customTransformers) {
113618             ts.Debug.assert(kind === InvalidatedProjectKind.UpdateBundle);
113619             if (state.options.dry) {
113620                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, project);
113621                 buildResult = BuildResultFlags.Success;
113622                 step = BuildStep.QueueReferencingProjects;
113623                 return undefined;
113624             }
113625             if (state.options.verbose)
113626                 reportStatus(state, ts.Diagnostics.Updating_output_of_project_0, project);
113627             // Update js, and source map
113628             var compilerHost = state.compilerHost;
113629             state.projectCompilerOptions = config.options;
113630             var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) {
113631                 var refName = resolveProjectName(state, ref.path);
113632                 return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName));
113633             }, customTransformers);
113634             if (ts.isString(outputFiles)) {
113635                 reportStatus(state, ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, project, relName(state, outputFiles));
113636                 step = BuildStep.BuildInvalidatedProjectOfBundle;
113637                 return invalidatedProjectOfBundle = createBuildOrUpdateInvalidedProject(InvalidatedProjectKind.Build, state, project, projectPath, projectIndex, config, buildOrder);
113638             }
113639             // Actual Emit
113640             ts.Debug.assert(!!outputFiles.length);
113641             var emitterDiagnostics = ts.createDiagnosticCollection();
113642             var emittedOutputs = new ts.Map();
113643             outputFiles.forEach(function (_a) {
113644                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
113645                 emittedOutputs.set(toPath(state, name), name);
113646                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
113647             });
113648             var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, 
113649             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged);
113650             return { emitSkipped: false, diagnostics: emitDiagnostics };
113651         }
113652         function executeSteps(till, cancellationToken, writeFile, customTransformers) {
113653             while (step <= till && step < BuildStep.Done) {
113654                 var currentStep = step;
113655                 switch (step) {
113656                     case BuildStep.CreateProgram:
113657                         createProgram();
113658                         break;
113659                     case BuildStep.SyntaxDiagnostics:
113660                         getSyntaxDiagnostics(cancellationToken);
113661                         break;
113662                     case BuildStep.SemanticDiagnostics:
113663                         getSemanticDiagnostics(cancellationToken);
113664                         break;
113665                     case BuildStep.Emit:
113666                         emit(writeFile, cancellationToken, customTransformers);
113667                         break;
113668                     case BuildStep.EmitBuildInfo:
113669                         emitBuildInfo(writeFile, cancellationToken);
113670                         break;
113671                     case BuildStep.EmitBundle:
113672                         emitBundle(writeFile, customTransformers);
113673                         break;
113674                     case BuildStep.BuildInvalidatedProjectOfBundle:
113675                         ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken);
113676                         step = BuildStep.Done;
113677                         break;
113678                     case BuildStep.QueueReferencingProjects:
113679                         queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, ts.Debug.checkDefined(buildResult));
113680                         step++;
113681                         break;
113682                     // Should never be done
113683                     case BuildStep.Done:
113684                     default:
113685                         ts.assertType(step);
113686                 }
113687                 ts.Debug.assert(step > currentStep);
113688             }
113689         }
113690     }
113691     function needsBuild(_a, status, config) {
113692         var options = _a.options;
113693         if (status.type !== ts.UpToDateStatusType.OutOfDateWithPrepend || options.force)
113694             return true;
113695         return config.fileNames.length === 0 ||
113696             !!ts.getConfigFileParsingDiagnostics(config).length ||
113697             !ts.isIncrementalCompilation(config.options);
113698     }
113699     function getNextInvalidatedProject(state, buildOrder, reportQueue) {
113700         if (!state.projectPendingBuild.size)
113701             return undefined;
113702         if (isCircularBuildOrder(buildOrder))
113703             return undefined;
113704         if (state.currentInvalidatedProject) {
113705             // Only if same buildOrder the currentInvalidated project can be sent again
113706             return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ?
113707                 state.currentInvalidatedProject :
113708                 undefined;
113709         }
113710         var options = state.options, projectPendingBuild = state.projectPendingBuild;
113711         for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) {
113712             var project = buildOrder[projectIndex];
113713             var projectPath = toResolvedConfigFilePath(state, project);
113714             var reloadLevel = state.projectPendingBuild.get(projectPath);
113715             if (reloadLevel === undefined)
113716                 continue;
113717             if (reportQueue) {
113718                 reportQueue = false;
113719                 reportBuildQueue(state, buildOrder);
113720             }
113721             var config = parseConfigFile(state, project, projectPath);
113722             if (!config) {
113723                 reportParseConfigFileDiagnostic(state, projectPath);
113724                 projectPendingBuild.delete(projectPath);
113725                 continue;
113726             }
113727             if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
113728                 watchConfigFile(state, project, projectPath, config);
113729                 watchExtendedConfigFiles(state, projectPath, config);
113730                 watchWildCardDirectories(state, project, projectPath, config);
113731                 watchInputFiles(state, project, projectPath, config);
113732             }
113733             else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
113734                 // Update file names
113735                 config.fileNames = ts.getFileNamesFromConfigSpecs(config.options.configFile.configFileSpecs, ts.getDirectoryPath(project), config.options, state.parseConfigFileHost);
113736                 ts.updateErrorForNoInputFiles(config.fileNames, project, config.options.configFile.configFileSpecs, config.errors, ts.canJsonReportNoInputFiles(config.raw));
113737                 watchInputFiles(state, project, projectPath, config);
113738             }
113739             var status = getUpToDateStatus(state, config, projectPath);
113740             verboseReportProjectStatus(state, project, status);
113741             if (!options.force) {
113742                 if (status.type === ts.UpToDateStatusType.UpToDate) {
113743                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
113744                     projectPendingBuild.delete(projectPath);
113745                     // Up to date, skip
113746                     if (options.dry) {
113747                         // In a dry build, inform the user of this fact
113748                         reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date, project);
113749                     }
113750                     continue;
113751                 }
113752                 if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) {
113753                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
113754                     return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder);
113755                 }
113756             }
113757             if (status.type === ts.UpToDateStatusType.UpstreamBlocked) {
113758                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
113759                 projectPendingBuild.delete(projectPath);
113760                 if (options.verbose) {
113761                     reportStatus(state, status.upstreamProjectBlocked ?
113762                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built :
113763                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, project, status.upstreamProjectName);
113764                 }
113765                 continue;
113766             }
113767             if (status.type === ts.UpToDateStatusType.ContainerOnly) {
113768                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
113769                 projectPendingBuild.delete(projectPath);
113770                 // Do nothing
113771                 continue;
113772             }
113773             return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ?
113774                 InvalidatedProjectKind.Build :
113775                 InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder);
113776         }
113777         return undefined;
113778     }
113779     function listEmittedFile(_a, proj, file) {
113780         var write = _a.write;
113781         if (write && proj.options.listEmittedFiles) {
113782             write("TSFILE: " + file);
113783         }
113784     }
113785     function getOldProgram(_a, proj, parsed) {
113786         var options = _a.options, builderPrograms = _a.builderPrograms, compilerHost = _a.compilerHost;
113787         if (options.force)
113788             return undefined;
113789         var value = builderPrograms.get(proj);
113790         if (value)
113791             return value;
113792         return ts.readBuilderProgram(parsed.options, compilerHost);
113793     }
113794     function afterProgramDone(state, program, config) {
113795         if (program) {
113796             if (program && state.write)
113797                 ts.listFiles(program, state.write);
113798             if (state.host.afterProgramEmitAndDiagnostics) {
113799                 state.host.afterProgramEmitAndDiagnostics(program);
113800             }
113801             program.releaseProgram();
113802         }
113803         else if (state.host.afterEmitBundle) {
113804             state.host.afterEmitBundle(config);
113805         }
113806         state.projectCompilerOptions = state.baseCompilerOptions;
113807     }
113808     function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) {
113809         var canEmitBuildInfo = !(buildResult & BuildResultFlags.SyntaxErrors) && program && !ts.outFile(program.getCompilerOptions());
113810         reportAndStoreErrors(state, resolvedPath, diagnostics);
113811         state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
113812         if (canEmitBuildInfo)
113813             return { buildResult: buildResult, step: BuildStep.EmitBuildInfo };
113814         afterProgramDone(state, program, config);
113815         return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects };
113816     }
113817     function updateModuleResolutionCache(state, proj, config) {
113818         if (!state.moduleResolutionCache)
113819             return;
113820         // Update module resolution cache if needed
113821         var moduleResolutionCache = state.moduleResolutionCache;
113822         var projPath = toPath(state, proj);
113823         if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) {
113824             // The own map will be for projectCompilerOptions
113825             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0);
113826             moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap);
113827             moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap);
113828         }
113829         else {
113830             // Set correct own map
113831             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0);
113832             var ref = {
113833                 sourceFile: config.options.configFile,
113834                 commandLine: config
113835             };
113836             moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref));
113837             moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref));
113838         }
113839         moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options);
113840         moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options);
113841     }
113842     function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) {
113843         // Check tsconfig time
113844         var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
113845         if (oldestOutputFileTime < tsconfigTime) {
113846             return {
113847                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
113848                 outOfDateOutputFileName: oldestOutputFileName,
113849                 newerInputFileName: configFile
113850             };
113851         }
113852     }
113853     function getUpToDateStatusWorker(state, project, resolvedPath) {
113854         var newestInputFileName = undefined;
113855         var newestInputFileTime = minimumDate;
113856         var host = state.host;
113857         // Get timestamps of input files
113858         for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
113859             var inputFile = _a[_i];
113860             if (!host.fileExists(inputFile)) {
113861                 return {
113862                     type: ts.UpToDateStatusType.Unbuildable,
113863                     reason: inputFile + " does not exist"
113864                 };
113865             }
113866             var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime;
113867             if (inputTime > newestInputFileTime) {
113868                 newestInputFileName = inputFile;
113869                 newestInputFileTime = inputTime;
113870             }
113871         }
113872         // Container if no files are specified in the project
113873         if (!project.fileNames.length && !ts.canJsonReportNoInputFiles(project.raw)) {
113874             return {
113875                 type: ts.UpToDateStatusType.ContainerOnly
113876             };
113877         }
113878         // Collect the expected outputs of this project
113879         var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
113880         // Now see if all outputs are newer than the newest input
113881         var oldestOutputFileName = "(none)";
113882         var oldestOutputFileTime = maximumDate;
113883         var newestOutputFileName = "(none)";
113884         var newestOutputFileTime = minimumDate;
113885         var missingOutputFileName;
113886         var newestDeclarationFileContentChangedTime = minimumDate;
113887         var isOutOfDateWithInputs = false;
113888         for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) {
113889             var output = outputs_1[_b];
113890             // Output is missing; can stop checking
113891             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
113892             if (!host.fileExists(output)) {
113893                 missingOutputFileName = output;
113894                 break;
113895             }
113896             var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
113897             if (outputTime < oldestOutputFileTime) {
113898                 oldestOutputFileTime = outputTime;
113899                 oldestOutputFileName = output;
113900             }
113901             // If an output is older than the newest input, we can stop checking
113902             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
113903             if (outputTime < newestInputFileTime) {
113904                 isOutOfDateWithInputs = true;
113905                 break;
113906             }
113907             if (outputTime > newestOutputFileTime) {
113908                 newestOutputFileTime = outputTime;
113909                 newestOutputFileName = output;
113910             }
113911             // Keep track of when the most recent time a .d.ts file was changed.
113912             // In addition to file timestamps, we also keep track of when a .d.ts file
113913             // had its file touched but not had its contents changed - this allows us
113914             // to skip a downstream typecheck
113915             if (isDeclarationFile(output)) {
113916                 var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
113917                 newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
113918             }
113919         }
113920         var pseudoUpToDate = false;
113921         var usesPrepend = false;
113922         var upstreamChangedProject;
113923         if (project.projectReferences) {
113924             state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream });
113925             for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
113926                 var ref = _d[_c];
113927                 usesPrepend = usesPrepend || !!(ref.prepend);
113928                 var resolvedRef = ts.resolveProjectReferencePath(ref);
113929                 var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef);
113930                 var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath);
113931                 // Its a circular reference ignore the status of this project
113932                 if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream ||
113933                     refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project
113934                     continue;
113935                 }
113936                 // An upstream project is blocked
113937                 if (refStatus.type === ts.UpToDateStatusType.Unbuildable ||
113938                     refStatus.type === ts.UpToDateStatusType.UpstreamBlocked) {
113939                     return {
113940                         type: ts.UpToDateStatusType.UpstreamBlocked,
113941                         upstreamProjectName: ref.path,
113942                         upstreamProjectBlocked: refStatus.type === ts.UpToDateStatusType.UpstreamBlocked
113943                     };
113944                 }
113945                 // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
113946                 if (refStatus.type !== ts.UpToDateStatusType.UpToDate) {
113947                     return {
113948                         type: ts.UpToDateStatusType.UpstreamOutOfDate,
113949                         upstreamProjectName: ref.path
113950                     };
113951                 }
113952                 // Check oldest output file name only if there is no missing output file name
113953                 if (!missingOutputFileName) {
113954                     // If the upstream project's newest file is older than our oldest output, we
113955                     // can't be out of date because of it
113956                     if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
113957                         continue;
113958                     }
113959                     // If the upstream project has only change .d.ts files, and we've built
113960                     // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
113961                     if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
113962                         pseudoUpToDate = true;
113963                         upstreamChangedProject = ref.path;
113964                         continue;
113965                     }
113966                     // We have an output older than an upstream output - we are out of date
113967                     ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
113968                     return {
113969                         type: ts.UpToDateStatusType.OutOfDateWithUpstream,
113970                         outOfDateOutputFileName: oldestOutputFileName,
113971                         newerProjectName: ref.path
113972                     };
113973                 }
113974             }
113975         }
113976         if (missingOutputFileName !== undefined) {
113977             return {
113978                 type: ts.UpToDateStatusType.OutputMissing,
113979                 missingOutputFileName: missingOutputFileName
113980             };
113981         }
113982         if (isOutOfDateWithInputs) {
113983             return {
113984                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
113985                 outOfDateOutputFileName: oldestOutputFileName,
113986                 newerInputFileName: newestInputFileName
113987             };
113988         }
113989         else {
113990             // Check tsconfig time
113991             var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
113992             if (configStatus)
113993                 return configStatus;
113994             // Check extended config time
113995             var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); });
113996             if (extendedConfigStatus)
113997                 return extendedConfigStatus;
113998         }
113999         if (!state.buildInfoChecked.has(resolvedPath)) {
114000             state.buildInfoChecked.set(resolvedPath, true);
114001             var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options);
114002             if (buildInfoPath) {
114003                 var value = state.readFileWithCache(buildInfoPath);
114004                 var buildInfo = value && ts.getBuildInfo(value);
114005                 if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) {
114006                     return {
114007                         type: ts.UpToDateStatusType.TsVersionOutputOfDate,
114008                         version: buildInfo.version
114009                     };
114010                 }
114011             }
114012         }
114013         if (usesPrepend && pseudoUpToDate) {
114014             return {
114015                 type: ts.UpToDateStatusType.OutOfDateWithPrepend,
114016                 outOfDateOutputFileName: oldestOutputFileName,
114017                 newerProjectName: upstreamChangedProject
114018             };
114019         }
114020         // Up to date
114021         return {
114022             type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate,
114023             newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
114024             newestInputFileTime: newestInputFileTime,
114025             newestOutputFileTime: newestOutputFileTime,
114026             newestInputFileName: newestInputFileName,
114027             newestOutputFileName: newestOutputFileName,
114028             oldestOutputFileName: oldestOutputFileName
114029         };
114030     }
114031     function getUpToDateStatus(state, project, resolvedPath) {
114032         if (project === undefined) {
114033             return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
114034         }
114035         var prior = state.projectStatus.get(resolvedPath);
114036         if (prior !== undefined) {
114037             return prior;
114038         }
114039         var actual = getUpToDateStatusWorker(state, project, resolvedPath);
114040         state.projectStatus.set(resolvedPath, actual);
114041         return actual;
114042     }
114043     function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
114044         var host = state.host;
114045         var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
114046         if (!skipOutputs || outputs.length !== skipOutputs.size) {
114047             var reportVerbose = !!state.options.verbose;
114048             var now = host.now ? host.now() : new Date();
114049             for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) {
114050                 var file = outputs_2[_i];
114051                 if (skipOutputs && skipOutputs.has(toPath(state, file))) {
114052                     continue;
114053                 }
114054                 if (reportVerbose) {
114055                     reportVerbose = false;
114056                     reportStatus(state, verboseMessage, proj.options.configFilePath);
114057                 }
114058                 if (isDeclarationFile(file)) {
114059                     priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime);
114060                 }
114061                 host.setModifiedTime(file, now);
114062             }
114063         }
114064         return priorNewestUpdateTime;
114065     }
114066     function updateOutputTimestamps(state, proj, resolvedPath) {
114067         if (state.options.dry) {
114068             return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
114069         }
114070         var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
114071         state.projectStatus.set(resolvedPath, {
114072             type: ts.UpToDateStatusType.UpToDate,
114073             newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
114074             oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames())
114075         });
114076     }
114077     function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) {
114078         // Queue only if there are no errors
114079         if (buildResult & BuildResultFlags.AnyErrors)
114080             return;
114081         // Only composite projects can be referenced by other projects
114082         if (!config.options.composite)
114083             return;
114084         // Always use build order to queue projects
114085         for (var index = projectIndex + 1; index < buildOrder.length; index++) {
114086             var nextProject = buildOrder[index];
114087             var nextProjectPath = toResolvedConfigFilePath(state, nextProject);
114088             if (state.projectPendingBuild.has(nextProjectPath))
114089                 continue;
114090             var nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath);
114091             if (!nextProjectConfig || !nextProjectConfig.projectReferences)
114092                 continue;
114093             for (var _i = 0, _a = nextProjectConfig.projectReferences; _i < _a.length; _i++) {
114094                 var ref = _a[_i];
114095                 var resolvedRefPath = resolveProjectName(state, ref.path);
114096                 if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath)
114097                     continue;
114098                 // If the project is referenced with prepend, always build downstream projects,
114099                 // If declaration output is changed, build the project
114100                 // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
114101                 var status = state.projectStatus.get(nextProjectPath);
114102                 if (status) {
114103                     switch (status.type) {
114104                         case ts.UpToDateStatusType.UpToDate:
114105                             if (buildResult & BuildResultFlags.DeclarationOutputUnchanged) {
114106                                 if (ref.prepend) {
114107                                     state.projectStatus.set(nextProjectPath, {
114108                                         type: ts.UpToDateStatusType.OutOfDateWithPrepend,
114109                                         outOfDateOutputFileName: status.oldestOutputFileName,
114110                                         newerProjectName: project
114111                                     });
114112                                 }
114113                                 else {
114114                                     status.type = ts.UpToDateStatusType.UpToDateWithUpstreamTypes;
114115                                 }
114116                                 break;
114117                             }
114118                         // falls through
114119                         case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
114120                         case ts.UpToDateStatusType.OutOfDateWithPrepend:
114121                             if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
114122                                 state.projectStatus.set(nextProjectPath, {
114123                                     type: ts.UpToDateStatusType.OutOfDateWithUpstream,
114124                                     outOfDateOutputFileName: status.type === ts.UpToDateStatusType.OutOfDateWithPrepend ? status.outOfDateOutputFileName : status.oldestOutputFileName,
114125                                     newerProjectName: project
114126                                 });
114127                             }
114128                             break;
114129                         case ts.UpToDateStatusType.UpstreamBlocked:
114130                             if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) {
114131                                 clearProjectStatus(state, nextProjectPath);
114132                             }
114133                             break;
114134                     }
114135                 }
114136                 addProjToQueue(state, nextProjectPath, ts.ConfigFileProgramReloadLevel.None);
114137                 break;
114138             }
114139         }
114140     }
114141     function build(state, project, cancellationToken, onlyReferences) {
114142         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
114143         if (!buildOrder)
114144             return ts.ExitStatus.InvalidProject_OutputsSkipped;
114145         setupInitialBuild(state, cancellationToken);
114146         var reportQueue = true;
114147         var successfulProjects = 0;
114148         while (true) {
114149             var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue);
114150             if (!invalidatedProject)
114151                 break;
114152             reportQueue = false;
114153             invalidatedProject.done(cancellationToken);
114154             if (!state.diagnostics.has(invalidatedProject.projectPath))
114155                 successfulProjects++;
114156         }
114157         disableCache(state);
114158         reportErrorSummary(state, buildOrder);
114159         startWatching(state, buildOrder);
114160         return isCircularBuildOrder(buildOrder)
114161             ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped
114162             : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); })
114163                 ? ts.ExitStatus.Success
114164                 : successfulProjects
114165                     ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated
114166                     : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
114167     }
114168     function clean(state, project, onlyReferences) {
114169         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
114170         if (!buildOrder)
114171             return ts.ExitStatus.InvalidProject_OutputsSkipped;
114172         if (isCircularBuildOrder(buildOrder)) {
114173             reportErrors(state, buildOrder.circularDiagnostics);
114174             return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped;
114175         }
114176         var options = state.options, host = state.host;
114177         var filesToDelete = options.dry ? [] : undefined;
114178         for (var _i = 0, buildOrder_1 = buildOrder; _i < buildOrder_1.length; _i++) {
114179             var proj = buildOrder_1[_i];
114180             var resolvedPath = toResolvedConfigFilePath(state, proj);
114181             var parsed = parseConfigFile(state, proj, resolvedPath);
114182             if (parsed === undefined) {
114183                 // File has gone missing; fine to ignore here
114184                 reportParseConfigFileDiagnostic(state, resolvedPath);
114185                 continue;
114186             }
114187             var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
114188             for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) {
114189                 var output = outputs_3[_a];
114190                 if (host.fileExists(output)) {
114191                     if (filesToDelete) {
114192                         filesToDelete.push(output);
114193                     }
114194                     else {
114195                         host.deleteFile(output);
114196                         invalidateProject(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None);
114197                     }
114198                 }
114199             }
114200         }
114201         if (filesToDelete) {
114202             reportStatus(state, ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join(""));
114203         }
114204         return ts.ExitStatus.Success;
114205     }
114206     function invalidateProject(state, resolved, reloadLevel) {
114207         // If host implements getParsedCommandLine, we cant get list of files from parseConfigFileHost
114208         if (state.host.getParsedCommandLine && reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
114209             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
114210         }
114211         if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
114212             state.configFileCache.delete(resolved);
114213             state.buildOrder = undefined;
114214         }
114215         state.needsSummary = true;
114216         clearProjectStatus(state, resolved);
114217         addProjToQueue(state, resolved, reloadLevel);
114218         enableCache(state);
114219     }
114220     function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) {
114221         state.reportFileChangeDetected = true;
114222         invalidateProject(state, resolvedPath, reloadLevel);
114223         scheduleBuildInvalidatedProject(state);
114224     }
114225     function scheduleBuildInvalidatedProject(state) {
114226         var hostWithWatch = state.hostWithWatch;
114227         if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
114228             return;
114229         }
114230         if (state.timerToBuildInvalidatedProject) {
114231             hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject);
114232         }
114233         state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state);
114234     }
114235     function buildNextInvalidatedProject(state) {
114236         state.timerToBuildInvalidatedProject = undefined;
114237         if (state.reportFileChangeDetected) {
114238             state.reportFileChangeDetected = false;
114239             state.projectErrorsReported.clear();
114240             reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
114241         }
114242         var buildOrder = getBuildOrder(state);
114243         var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false);
114244         if (invalidatedProject) {
114245             invalidatedProject.done();
114246             if (state.projectPendingBuild.size) {
114247                 // Schedule next project for build
114248                 if (state.watch && !state.timerToBuildInvalidatedProject) {
114249                     scheduleBuildInvalidatedProject(state);
114250                 }
114251                 return;
114252             }
114253         }
114254         disableCache(state);
114255         reportErrorSummary(state, buildOrder);
114256     }
114257     function watchConfigFile(state, resolved, resolvedPath, parsed) {
114258         if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath))
114259             return;
114260         state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(resolved, function () {
114261             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full);
114262         }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved));
114263     }
114264     function watchExtendedConfigFiles(state, resolvedPath, parsed) {
114265         ts.updateSharedExtendedConfigFileWatcher(resolvedPath, parsed, state.allWatchedExtendedConfigFiles, function (extendedConfigFileName, extendedConfigFilePath) { return state.watchFile(extendedConfigFileName, function () {
114266             var _a;
114267             return (_a = state.allWatchedExtendedConfigFiles.get(extendedConfigFilePath)) === null || _a === void 0 ? void 0 : _a.projects.forEach(function (projectConfigFilePath) {
114268                 return invalidateProjectAndScheduleBuilds(state, projectConfigFilePath, ts.ConfigFileProgramReloadLevel.Full);
114269             });
114270         }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ExtendedConfigFile); }, function (fileName) { return toPath(state, fileName); });
114271     }
114272     function watchWildCardDirectories(state, resolved, resolvedPath, parsed) {
114273         if (!state.watch)
114274             return;
114275         ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), new ts.Map(ts.getEntries(parsed.wildcardDirectories)), function (dir, flags) { return state.watchDirectory(dir, function (fileOrDirectory) {
114276             if (ts.isIgnoredFileFromWildCardWatching({
114277                 watchedDirPath: toPath(state, dir),
114278                 fileOrDirectory: fileOrDirectory,
114279                 fileOrDirectoryPath: toPath(state, fileOrDirectory),
114280                 configFileName: resolved,
114281                 currentDirectory: state.currentDirectory,
114282                 options: parsed.options,
114283                 program: state.builderPrograms.get(resolvedPath),
114284                 useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames,
114285                 writeLog: function (s) { return state.writeLog(s); }
114286             }))
114287                 return;
114288             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial);
114289         }, flags, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.WildcardDirectory, resolved); });
114290     }
114291     function watchInputFiles(state, resolved, resolvedPath, parsed) {
114292         if (!state.watch)
114293             return;
114294         ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), {
114295             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); },
114296             onDeleteValue: ts.closeFileWatcher,
114297         });
114298     }
114299     function startWatching(state, buildOrder) {
114300         if (!state.watchAllProjectsPending)
114301             return;
114302         state.watchAllProjectsPending = false;
114303         for (var _i = 0, _a = getBuildOrderFromAnyBuildOrder(buildOrder); _i < _a.length; _i++) {
114304             var resolved = _a[_i];
114305             var resolvedPath = toResolvedConfigFilePath(state, resolved);
114306             var cfg = parseConfigFile(state, resolved, resolvedPath);
114307             // Watch this file
114308             watchConfigFile(state, resolved, resolvedPath, cfg);
114309             watchExtendedConfigFiles(state, resolvedPath, cfg);
114310             if (cfg) {
114311                 // Update watchers for wildcard directories
114312                 watchWildCardDirectories(state, resolved, resolvedPath, cfg);
114313                 // Watch input files
114314                 watchInputFiles(state, resolved, resolvedPath, cfg);
114315             }
114316         }
114317     }
114318     function stopWatching(state) {
114319         ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher);
114320         ts.clearMap(state.allWatchedExtendedConfigFiles, function (watcher) {
114321             watcher.projects.clear();
114322             watcher.close();
114323         });
114324         ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); });
114325         ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); });
114326     }
114327     function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
114328         var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions);
114329         return {
114330             build: function (project, cancellationToken) { return build(state, project, cancellationToken); },
114331             clean: function (project) { return clean(state, project); },
114332             buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); },
114333             cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); },
114334             getNextInvalidatedProject: function (cancellationToken) {
114335                 setupInitialBuild(state, cancellationToken);
114336                 return getNextInvalidatedProject(state, getBuildOrder(state), /*reportQueue*/ false);
114337             },
114338             getBuildOrder: function () { return getBuildOrder(state); },
114339             getUpToDateStatusOfProject: function (project) {
114340                 var configFileName = resolveProjectName(state, project);
114341                 var configFilePath = toResolvedConfigFilePath(state, configFileName);
114342                 return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath);
114343             },
114344             invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); },
114345             buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); },
114346             getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); },
114347             close: function () { return stopWatching(state); },
114348         };
114349     }
114350     function relName(state, path) {
114351         return ts.convertToRelativePath(path, state.currentDirectory, function (f) { return state.getCanonicalFileName(f); });
114352     }
114353     function reportStatus(state, message) {
114354         var args = [];
114355         for (var _i = 2; _i < arguments.length; _i++) {
114356             args[_i - 2] = arguments[_i];
114357         }
114358         state.host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, __spreadArray([message], args)));
114359     }
114360     function reportWatchStatus(state, message) {
114361         var _a, _b;
114362         var args = [];
114363         for (var _i = 2; _i < arguments.length; _i++) {
114364             args[_i - 2] = arguments[_i];
114365         }
114366         (_b = (_a = state.hostWithWatch).onWatchStatusChange) === null || _b === void 0 ? void 0 : _b.call(_a, ts.createCompilerDiagnostic.apply(void 0, __spreadArray([message], args)), state.host.getNewLine(), state.baseCompilerOptions);
114367     }
114368     function reportErrors(_a, errors) {
114369         var host = _a.host;
114370         errors.forEach(function (err) { return host.reportDiagnostic(err); });
114371     }
114372     function reportAndStoreErrors(state, proj, errors) {
114373         reportErrors(state, errors);
114374         state.projectErrorsReported.set(proj, true);
114375         if (errors.length) {
114376             state.diagnostics.set(proj, errors);
114377         }
114378     }
114379     function reportParseConfigFileDiagnostic(state, proj) {
114380         reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]);
114381     }
114382     function reportErrorSummary(state, buildOrder) {
114383         if (!state.needsSummary)
114384             return;
114385         state.needsSummary = false;
114386         var canReportSummary = state.watch || !!state.host.reportErrorSummary;
114387         var diagnostics = state.diagnostics;
114388         var totalErrors = 0;
114389         if (isCircularBuildOrder(buildOrder)) {
114390             reportBuildQueue(state, buildOrder.buildOrder);
114391             reportErrors(state, buildOrder.circularDiagnostics);
114392             if (canReportSummary)
114393                 totalErrors += ts.getErrorCountForSummary(buildOrder.circularDiagnostics);
114394         }
114395         else {
114396             // Report errors from the other projects
114397             buildOrder.forEach(function (project) {
114398                 var projectPath = toResolvedConfigFilePath(state, project);
114399                 if (!state.projectErrorsReported.has(projectPath)) {
114400                     reportErrors(state, diagnostics.get(projectPath) || ts.emptyArray);
114401                 }
114402             });
114403             if (canReportSummary)
114404                 diagnostics.forEach(function (singleProjectErrors) { return totalErrors += ts.getErrorCountForSummary(singleProjectErrors); });
114405         }
114406         if (state.watch) {
114407             reportWatchStatus(state, ts.getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
114408         }
114409         else if (state.host.reportErrorSummary) {
114410             state.host.reportErrorSummary(totalErrors);
114411         }
114412     }
114413     /**
114414      * Report the build ordering inferred from the current project graph if we're in verbose mode
114415      */
114416     function reportBuildQueue(state, buildQueue) {
114417         if (state.options.verbose) {
114418             reportStatus(state, ts.Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map(function (s) { return "\r\n    * " + relName(state, s); }).join(""));
114419         }
114420     }
114421     function reportUpToDateStatus(state, configFileName, status) {
114422         switch (status.type) {
114423             case ts.UpToDateStatusType.OutOfDateWithSelf:
114424                 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));
114425             case ts.UpToDateStatusType.OutOfDateWithUpstream:
114426                 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));
114427             case ts.UpToDateStatusType.OutputMissing:
114428                 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));
114429             case ts.UpToDateStatusType.UpToDate:
114430                 if (status.newestInputFileTime !== undefined) {
114431                     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 || ""));
114432                 }
114433                 // Don't report anything for "up to date because it was already built" -- too verbose
114434                 break;
114435             case ts.UpToDateStatusType.OutOfDateWithPrepend:
114436                 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));
114437             case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
114438                 return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName));
114439             case ts.UpToDateStatusType.UpstreamOutOfDate:
114440                 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));
114441             case ts.UpToDateStatusType.UpstreamBlocked:
114442                 return reportStatus(state, status.upstreamProjectBlocked ?
114443                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built :
114444                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(state, configFileName), relName(state, status.upstreamProjectName));
114445             case ts.UpToDateStatusType.Unbuildable:
114446                 return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason);
114447             case ts.UpToDateStatusType.TsVersionOutputOfDate:
114448                 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);
114449             case ts.UpToDateStatusType.ContainerOnly:
114450             // Don't report status on "solution" projects
114451             // falls through
114452             case ts.UpToDateStatusType.ComputingUpstream:
114453                 // Should never leak from getUptoDateStatusWorker
114454                 break;
114455             default:
114456                 ts.assertType(status);
114457         }
114458     }
114459     /**
114460      * Report the up-to-date status of a project if we're in verbose mode
114461      */
114462     function verboseReportProjectStatus(state, configFileName, status) {
114463         if (state.options.verbose) {
114464             reportUpToDateStatus(state, configFileName, status);
114465         }
114466     }
114467 })(ts || (ts = {}));
114468 var ts;
114469 (function (ts) {
114470     var server;
114471     (function (server) {
114472         /* @internal */
114473         server.ActionSet = "action::set";
114474         /* @internal */
114475         server.ActionInvalidate = "action::invalidate";
114476         /* @internal */
114477         server.ActionPackageInstalled = "action::packageInstalled";
114478         /* @internal */
114479         server.EventTypesRegistry = "event::typesRegistry";
114480         /* @internal */
114481         server.EventBeginInstallTypes = "event::beginInstallTypes";
114482         /* @internal */
114483         server.EventEndInstallTypes = "event::endInstallTypes";
114484         /* @internal */
114485         server.EventInitializationFailed = "event::initializationFailed";
114486         /* @internal */
114487         var Arguments;
114488         (function (Arguments) {
114489             Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation";
114490             Arguments.LogFile = "--logFile";
114491             Arguments.EnableTelemetry = "--enableTelemetry";
114492             Arguments.TypingSafeListLocation = "--typingSafeListLocation";
114493             Arguments.TypesMapLocation = "--typesMapLocation";
114494             /**
114495              * This argument specifies the location of the NPM executable.
114496              * typingsInstaller will run the command with `${npmLocation} install ...`.
114497              */
114498             Arguments.NpmLocation = "--npmLocation";
114499             /**
114500              * Flag indicating that the typings installer should try to validate the default npm location.
114501              * If the default npm is not found when this flag is enabled, fallback to `npm install`
114502              */
114503             Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
114504         })(Arguments = server.Arguments || (server.Arguments = {}));
114505         /* @internal */
114506         function hasArgument(argumentName) {
114507             return ts.sys.args.indexOf(argumentName) >= 0;
114508         }
114509         server.hasArgument = hasArgument;
114510         /* @internal */
114511         function findArgument(argumentName) {
114512             var index = ts.sys.args.indexOf(argumentName);
114513             return index >= 0 && index < ts.sys.args.length - 1
114514                 ? ts.sys.args[index + 1]
114515                 : undefined;
114516         }
114517         server.findArgument = findArgument;
114518         /* @internal */
114519         function nowString() {
114520             // E.g. "12:34:56.789"
114521             var d = new Date();
114522             return ts.padLeft(d.getHours().toString(), 2, "0") + ":" + ts.padLeft(d.getMinutes().toString(), 2, "0") + ":" + ts.padLeft(d.getSeconds().toString(), 2, "0") + "." + ts.padLeft(d.getMilliseconds().toString(), 3, "0");
114523         }
114524         server.nowString = nowString;
114525     })(server = ts.server || (ts.server = {}));
114526 })(ts || (ts = {}));
114527 /* @internal */
114528 var ts;
114529 (function (ts) {
114530     var JsTyping;
114531     (function (JsTyping) {
114532         function isTypingUpToDate(cachedTyping, availableTypingVersions) {
114533             var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest"));
114534             return availableVersion.compareTo(cachedTyping.version) <= 0;
114535         }
114536         JsTyping.isTypingUpToDate = isTypingUpToDate;
114537         JsTyping.nodeCoreModuleList = [
114538             "assert",
114539             "async_hooks",
114540             "buffer",
114541             "child_process",
114542             "cluster",
114543             "console",
114544             "constants",
114545             "crypto",
114546             "dgram",
114547             "dns",
114548             "domain",
114549             "events",
114550             "fs",
114551             "http",
114552             "https",
114553             "http2",
114554             "inspector",
114555             "net",
114556             "os",
114557             "path",
114558             "perf_hooks",
114559             "process",
114560             "punycode",
114561             "querystring",
114562             "readline",
114563             "repl",
114564             "stream",
114565             "string_decoder",
114566             "timers",
114567             "tls",
114568             "tty",
114569             "url",
114570             "util",
114571             "v8",
114572             "vm",
114573             "zlib"
114574         ];
114575         JsTyping.nodeCoreModules = new ts.Set(JsTyping.nodeCoreModuleList);
114576         function nonRelativeModuleNameForTypingCache(moduleName) {
114577             return JsTyping.nodeCoreModules.has(moduleName) ? "node" : moduleName;
114578         }
114579         JsTyping.nonRelativeModuleNameForTypingCache = nonRelativeModuleNameForTypingCache;
114580         function loadSafeList(host, safeListPath) {
114581             var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
114582             return new ts.Map(ts.getEntries(result.config));
114583         }
114584         JsTyping.loadSafeList = loadSafeList;
114585         function loadTypesMap(host, typesMapPath) {
114586             var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); });
114587             if (result.config) {
114588                 return new ts.Map(ts.getEntries(result.config.simpleMap));
114589             }
114590             return undefined;
114591         }
114592         JsTyping.loadTypesMap = loadTypesMap;
114593         /**
114594          * @param host is the object providing I/O related operations.
114595          * @param fileNames are the file names that belong to the same project
114596          * @param projectRootPath is the path to the project root directory
114597          * @param safeListPath is the path used to retrieve the safe list
114598          * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions
114599          * @param typeAcquisition is used to customize the typing acquisition process
114600          * @param compilerOptions are used as a source for typing inference
114601          */
114602         function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) {
114603             if (!typeAcquisition || !typeAcquisition.enable) {
114604                 return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
114605             }
114606             // A typing name to typing file path mapping
114607             var inferredTypings = new ts.Map();
114608             // Only infer typings for .js and .jsx files
114609             fileNames = ts.mapDefined(fileNames, function (fileName) {
114610                 var path = ts.normalizePath(fileName);
114611                 if (ts.hasJSFileExtension(path)) {
114612                     return path;
114613                 }
114614             });
114615             var filesToWatch = [];
114616             if (typeAcquisition.include)
114617                 addInferredTypings(typeAcquisition.include, "Explicitly included types");
114618             var exclude = typeAcquisition.exclude || [];
114619             // Directories to search for package.json, bower.json and other typing information
114620             var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath));
114621             possibleSearchDirs.add(projectRootPath);
114622             possibleSearchDirs.forEach(function (searchDir) {
114623                 var packageJsonPath = ts.combinePaths(searchDir, "package.json");
114624                 getTypingNamesFromJson(packageJsonPath, filesToWatch);
114625                 var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
114626                 getTypingNamesFromJson(bowerJsonPath, filesToWatch);
114627                 var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components");
114628                 getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch);
114629                 var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
114630                 getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch);
114631             });
114632             if (!typeAcquisition.disableFilenameBasedTypeAcquisition) {
114633                 getTypingNamesFromSourceFileNames(fileNames);
114634             }
114635             // add typings for unresolved imports
114636             if (unresolvedImports) {
114637                 var module_1 = ts.deduplicate(unresolvedImports.map(nonRelativeModuleNameForTypingCache), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
114638                 addInferredTypings(module_1, "Inferred typings from unresolved imports");
114639             }
114640             // Add the cached typing locations for inferred typings that are already installed
114641             packageNameToTypingLocation.forEach(function (typing, name) {
114642                 var registryEntry = typesRegistry.get(name);
114643                 if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) {
114644                     inferredTypings.set(name, typing.typingLocation);
114645                 }
114646             });
114647             // Remove typings that the user has added to the exclude list
114648             for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) {
114649                 var excludeTypingName = exclude_1[_i];
114650                 var didDelete = inferredTypings.delete(excludeTypingName);
114651                 if (didDelete && log)
114652                     log("Typing for " + excludeTypingName + " is in exclude list, will be ignored.");
114653             }
114654             var newTypingNames = [];
114655             var cachedTypingPaths = [];
114656             inferredTypings.forEach(function (inferred, typing) {
114657                 if (inferred !== undefined) {
114658                     cachedTypingPaths.push(inferred);
114659                 }
114660                 else {
114661                     newTypingNames.push(typing);
114662                 }
114663             });
114664             var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
114665             if (log)
114666                 log("Result: " + JSON.stringify(result));
114667             return result;
114668             function addInferredTyping(typingName) {
114669                 if (!inferredTypings.has(typingName)) {
114670                     inferredTypings.set(typingName, undefined); // TODO: GH#18217
114671                 }
114672             }
114673             function addInferredTypings(typingNames, message) {
114674                 if (log)
114675                     log(message + ": " + JSON.stringify(typingNames));
114676                 ts.forEach(typingNames, addInferredTyping);
114677             }
114678             /**
114679              * Get the typing info from common package manager json files like package.json or bower.json
114680              */
114681             function getTypingNamesFromJson(jsonPath, filesToWatch) {
114682                 if (!host.fileExists(jsonPath)) {
114683                     return;
114684                 }
114685                 filesToWatch.push(jsonPath);
114686                 var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config;
114687                 var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys);
114688                 addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies");
114689             }
114690             /**
114691              * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
114692              * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
114693              * to the 'angular-route' typing name.
114694              * @param fileNames are the names for source files in the project
114695              */
114696             function getTypingNamesFromSourceFileNames(fileNames) {
114697                 var fromFileNames = ts.mapDefined(fileNames, function (j) {
114698                     if (!ts.hasJSFileExtension(j))
114699                         return undefined;
114700                     var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase()));
114701                     var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
114702                     return safeList.get(cleanedTypingName);
114703                 });
114704                 if (fromFileNames.length) {
114705                     addInferredTypings(fromFileNames, "Inferred typings from file names");
114706                 }
114707                 var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); });
114708                 if (hasJsxFile) {
114709                     if (log)
114710                         log("Inferred 'react' typings due to presence of '.jsx' extension");
114711                     addInferredTyping("react");
114712                 }
114713             }
114714             /**
114715              * Infer typing names from packages folder (ex: node_module, bower_components)
114716              * @param packagesFolderPath is the path to the packages folder
114717              */
114718             function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) {
114719                 filesToWatch.push(packagesFolderPath);
114720                 // Todo: add support for ModuleResolutionHost too
114721                 if (!host.directoryExists(packagesFolderPath)) {
114722                     return;
114723                 }
114724                 // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar`
114725                 var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
114726                 if (log)
114727                     log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames));
114728                 var packageNames = [];
114729                 for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
114730                     var fileName = fileNames_1[_i];
114731                     var normalizedFileName = ts.normalizePath(fileName);
114732                     var baseFileName = ts.getBaseFileName(normalizedFileName);
114733                     if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
114734                         continue;
114735                     }
114736                     var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
114737                     var packageJson = result_1.config;
114738                     // npm 3's package.json contains a "_requiredBy" field
114739                     // we should include all the top level module names for npm 2, and only module names whose
114740                     // "_requiredBy" field starts with "#" or equals "/" for npm 3.
114741                     if (baseFileName === "package.json" && packageJson._requiredBy &&
114742                         ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
114743                         continue;
114744                     }
114745                     // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
114746                     // to download d.ts files from DefinitelyTyped
114747                     if (!packageJson.name) {
114748                         continue;
114749                     }
114750                     var ownTypes = packageJson.types || packageJson.typings;
114751                     if (ownTypes) {
114752                         var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName));
114753                         if (log)
114754                             log("    Package '" + packageJson.name + "' provides its own types.");
114755                         inferredTypings.set(packageJson.name, absolutePath);
114756                     }
114757                     else {
114758                         packageNames.push(packageJson.name);
114759                     }
114760                 }
114761                 addInferredTypings(packageNames, "    Found package names");
114762             }
114763         }
114764         JsTyping.discoverTypings = discoverTypings;
114765         var NameValidationResult;
114766         (function (NameValidationResult) {
114767             NameValidationResult[NameValidationResult["Ok"] = 0] = "Ok";
114768             NameValidationResult[NameValidationResult["EmptyName"] = 1] = "EmptyName";
114769             NameValidationResult[NameValidationResult["NameTooLong"] = 2] = "NameTooLong";
114770             NameValidationResult[NameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot";
114771             NameValidationResult[NameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
114772             NameValidationResult[NameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
114773         })(NameValidationResult = JsTyping.NameValidationResult || (JsTyping.NameValidationResult = {}));
114774         var maxPackageNameLength = 214;
114775         /**
114776          * Validates package name using rules defined at https://docs.npmjs.com/files/package.json
114777          */
114778         function validatePackageName(packageName) {
114779             return validatePackageNameWorker(packageName, /*supportScopedPackage*/ true);
114780         }
114781         JsTyping.validatePackageName = validatePackageName;
114782         function validatePackageNameWorker(packageName, supportScopedPackage) {
114783             if (!packageName) {
114784                 return 1 /* EmptyName */;
114785             }
114786             if (packageName.length > maxPackageNameLength) {
114787                 return 2 /* NameTooLong */;
114788             }
114789             if (packageName.charCodeAt(0) === 46 /* dot */) {
114790                 return 3 /* NameStartsWithDot */;
114791             }
114792             if (packageName.charCodeAt(0) === 95 /* _ */) {
114793                 return 4 /* NameStartsWithUnderscore */;
114794             }
114795             // check if name is scope package like: starts with @ and has one '/' in the middle
114796             // scoped packages are not currently supported
114797             if (supportScopedPackage) {
114798                 var matches = /^@([^/]+)\/([^/]+)$/.exec(packageName);
114799                 if (matches) {
114800                     var scopeResult = validatePackageNameWorker(matches[1], /*supportScopedPackage*/ false);
114801                     if (scopeResult !== 0 /* Ok */) {
114802                         return { name: matches[1], isScopeName: true, result: scopeResult };
114803                     }
114804                     var packageResult = validatePackageNameWorker(matches[2], /*supportScopedPackage*/ false);
114805                     if (packageResult !== 0 /* Ok */) {
114806                         return { name: matches[2], isScopeName: false, result: packageResult };
114807                     }
114808                     return 0 /* Ok */;
114809                 }
114810             }
114811             if (encodeURIComponent(packageName) !== packageName) {
114812                 return 5 /* NameContainsNonURISafeCharacters */;
114813             }
114814             return 0 /* Ok */;
114815         }
114816         function renderPackageNameValidationFailure(result, typing) {
114817             return typeof result === "object" ?
114818                 renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) :
114819                 renderPackageNameValidationFailureWorker(typing, result, typing, /*isScopeName*/ false);
114820         }
114821         JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
114822         function renderPackageNameValidationFailureWorker(typing, result, name, isScopeName) {
114823             var kind = isScopeName ? "Scope" : "Package";
114824             switch (result) {
114825                 case 1 /* EmptyName */:
114826                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot be empty";
114827                 case 2 /* NameTooLong */:
114828                     return "'" + typing + "':: " + kind + " name '" + name + "' should be less than " + maxPackageNameLength + " characters";
114829                 case 3 /* NameStartsWithDot */:
114830                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '.'";
114831                 case 4 /* NameStartsWithUnderscore */:
114832                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '_'";
114833                 case 5 /* NameContainsNonURISafeCharacters */:
114834                     return "'" + typing + "':: " + kind + " name '" + name + "' contains non URI safe characters";
114835                 case 0 /* Ok */:
114836                     return ts.Debug.fail(); // Shouldn't have called this.
114837                 default:
114838                     throw ts.Debug.assertNever(result);
114839             }
114840         }
114841     })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
114842 })(ts || (ts = {}));
114843 var ts;
114844 (function (ts) {
114845     var server;
114846     (function (server) {
114847         var typingsInstaller;
114848         (function (typingsInstaller) {
114849             var nullLog = {
114850                 isEnabled: function () { return false; },
114851                 writeLine: ts.noop
114852             };
114853             function typingToFileName(cachePath, packageName, installTypingHost, log) {
114854                 try {
114855                     var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost);
114856                     return result.resolvedModule && result.resolvedModule.resolvedFileName;
114857                 }
114858                 catch (e) {
114859                     if (log.isEnabled()) {
114860                         log.writeLine("Failed to resolve " + packageName + " in folder '" + cachePath + "': " + e.message);
114861                     }
114862                     return undefined;
114863                 }
114864             }
114865             /*@internal*/
114866             function installNpmPackages(npmPath, tsVersion, packageNames, install) {
114867                 var hasError = false;
114868                 for (var remaining = packageNames.length; remaining > 0;) {
114869                     var result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining);
114870                     remaining = result.remaining;
114871                     hasError = install(result.command) || hasError;
114872                 }
114873                 return hasError;
114874             }
114875             typingsInstaller.installNpmPackages = installNpmPackages;
114876             /*@internal*/
114877             function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) {
114878                 var sliceStart = packageNames.length - remaining;
114879                 var command, toSlice = remaining;
114880                 while (true) {
114881                     command = npmPath + " install --ignore-scripts " + (toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ") + " --save-dev --user-agent=\"typesInstaller/" + tsVersion + "\"";
114882                     if (command.length < 8000) {
114883                         break;
114884                     }
114885                     toSlice = toSlice - Math.floor(toSlice / 2);
114886                 }
114887                 return { command: command, remaining: remaining - toSlice };
114888             }
114889             typingsInstaller.getNpmCommandForInstallation = getNpmCommandForInstallation;
114890             function endsWith(str, suffix, caseSensitive) {
114891                 var expectedPos = str.length - suffix.length;
114892                 return expectedPos >= 0 &&
114893                     (str.indexOf(suffix, expectedPos) === expectedPos ||
114894                         (!caseSensitive && ts.compareStringsCaseInsensitive(str.substr(expectedPos), suffix) === 0 /* EqualTo */));
114895             }
114896             function isPackageOrBowerJson(fileName, caseSensitive) {
114897                 return endsWith(fileName, "/package.json", caseSensitive) || endsWith(fileName, "/bower.json", caseSensitive);
114898             }
114899             function sameFiles(a, b, caseSensitive) {
114900                 return a === b || (!caseSensitive && ts.compareStringsCaseInsensitive(a, b) === 0 /* EqualTo */);
114901             }
114902             var ProjectWatcherType;
114903             (function (ProjectWatcherType) {
114904                 ProjectWatcherType["FileWatcher"] = "FileWatcher";
114905                 ProjectWatcherType["DirectoryWatcher"] = "DirectoryWatcher";
114906             })(ProjectWatcherType || (ProjectWatcherType = {}));
114907             function getDetailWatchInfo(projectName, watchers) {
114908                 return "Project: " + projectName + " watcher already invoked: " + watchers.isInvoked;
114909             }
114910             var TypingsInstaller = /** @class */ (function () {
114911                 function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log) {
114912                     var _this = this;
114913                     if (log === void 0) { log = nullLog; }
114914                     this.installTypingHost = installTypingHost;
114915                     this.globalCachePath = globalCachePath;
114916                     this.safeListPath = safeListPath;
114917                     this.typesMapLocation = typesMapLocation;
114918                     this.throttleLimit = throttleLimit;
114919                     this.log = log;
114920                     this.packageNameToTypingLocation = new ts.Map();
114921                     this.missingTypingsSet = new ts.Set();
114922                     this.knownCachesSet = new ts.Set();
114923                     this.projectWatchers = new ts.Map();
114924                     this.pendingRunRequests = [];
114925                     this.installRunCount = 1;
114926                     this.inFlightRequestCount = 0;
114927                     this.latestDistTag = "latest";
114928                     this.toCanonicalFileName = ts.createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames);
114929                     this.globalCachePackageJsonPath = ts.combinePaths(globalCachePath, "package.json");
114930                     var isLoggingEnabled = this.log.isEnabled();
114931                     if (isLoggingEnabled) {
114932                         this.log.writeLine("Global cache location '" + globalCachePath + "', safe file path '" + safeListPath + "', types map path " + typesMapLocation);
114933                     }
114934                     this.watchFactory = ts.getWatchFactory(this.installTypingHost, isLoggingEnabled ? ts.WatchLogLevel.Verbose : ts.WatchLogLevel.None, function (s) { return _this.log.writeLine(s); }, getDetailWatchInfo);
114935                     this.processCacheLocation(this.globalCachePath);
114936                 }
114937                 TypingsInstaller.prototype.closeProject = function (req) {
114938                     this.closeWatchers(req.projectName);
114939                 };
114940                 TypingsInstaller.prototype.closeWatchers = function (projectName) {
114941                     if (this.log.isEnabled()) {
114942                         this.log.writeLine("Closing file watchers for project '" + projectName + "'");
114943                     }
114944                     var watchers = this.projectWatchers.get(projectName);
114945                     if (!watchers) {
114946                         if (this.log.isEnabled()) {
114947                             this.log.writeLine("No watchers are registered for project '" + projectName + "'");
114948                         }
114949                         return;
114950                     }
114951                     ts.clearMap(watchers, ts.closeFileWatcher);
114952                     this.projectWatchers.delete(projectName);
114953                     if (this.log.isEnabled()) {
114954                         this.log.writeLine("Closing file watchers for project '" + projectName + "' - done.");
114955                     }
114956                 };
114957                 TypingsInstaller.prototype.install = function (req) {
114958                     var _this = this;
114959                     if (this.log.isEnabled()) {
114960                         this.log.writeLine("Got install request " + JSON.stringify(req));
114961                     }
114962                     // load existing typing information from the cache
114963                     if (req.cachePath) {
114964                         if (this.log.isEnabled()) {
114965                             this.log.writeLine("Request specifies cache path '" + req.cachePath + "', loading cached information...");
114966                         }
114967                         this.processCacheLocation(req.cachePath);
114968                     }
114969                     if (this.safeList === undefined) {
114970                         this.initializeSafeList();
114971                     }
114972                     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);
114973                     if (this.log.isEnabled()) {
114974                         this.log.writeLine("Finished typings discovery: " + JSON.stringify(discoverTypingsResult));
114975                     }
114976                     // start watching files
114977                     this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch, req.projectRootPath, req.watchOptions);
114978                     // install typings
114979                     if (discoverTypingsResult.newTypingNames.length) {
114980                         this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames);
114981                     }
114982                     else {
114983                         this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths));
114984                         if (this.log.isEnabled()) {
114985                             this.log.writeLine("No new typings were requested as a result of typings discovery");
114986                         }
114987                     }
114988                 };
114989                 TypingsInstaller.prototype.initializeSafeList = function () {
114990                     // Prefer the safe list from the types map if it exists
114991                     if (this.typesMapLocation) {
114992                         var safeListFromMap = ts.JsTyping.loadTypesMap(this.installTypingHost, this.typesMapLocation);
114993                         if (safeListFromMap) {
114994                             this.log.writeLine("Loaded safelist from types map file '" + this.typesMapLocation + "'");
114995                             this.safeList = safeListFromMap;
114996                             return;
114997                         }
114998                         this.log.writeLine("Failed to load safelist from types map file '" + this.typesMapLocation + "'");
114999                     }
115000                     this.safeList = ts.JsTyping.loadSafeList(this.installTypingHost, this.safeListPath);
115001                 };
115002                 TypingsInstaller.prototype.processCacheLocation = function (cacheLocation) {
115003                     if (this.log.isEnabled()) {
115004                         this.log.writeLine("Processing cache location '" + cacheLocation + "'");
115005                     }
115006                     if (this.knownCachesSet.has(cacheLocation)) {
115007                         if (this.log.isEnabled()) {
115008                             this.log.writeLine("Cache location was already processed...");
115009                         }
115010                         return;
115011                     }
115012                     var packageJson = ts.combinePaths(cacheLocation, "package.json");
115013                     var packageLockJson = ts.combinePaths(cacheLocation, "package-lock.json");
115014                     if (this.log.isEnabled()) {
115015                         this.log.writeLine("Trying to find '" + packageJson + "'...");
115016                     }
115017                     if (this.installTypingHost.fileExists(packageJson) && this.installTypingHost.fileExists(packageLockJson)) {
115018                         var npmConfig = JSON.parse(this.installTypingHost.readFile(packageJson)); // TODO: GH#18217
115019                         var npmLock = JSON.parse(this.installTypingHost.readFile(packageLockJson)); // TODO: GH#18217
115020                         if (this.log.isEnabled()) {
115021                             this.log.writeLine("Loaded content of '" + packageJson + "': " + JSON.stringify(npmConfig));
115022                             this.log.writeLine("Loaded content of '" + packageLockJson + "'");
115023                         }
115024                         if (npmConfig.devDependencies && npmLock.dependencies) {
115025                             for (var key in npmConfig.devDependencies) {
115026                                 if (!ts.hasProperty(npmLock.dependencies, key)) {
115027                                     // if package in package.json but not package-lock.json, skip adding to cache so it is reinstalled on next use
115028                                     continue;
115029                                 }
115030                                 // key is @types/<package name>
115031                                 var packageName = ts.getBaseFileName(key);
115032                                 if (!packageName) {
115033                                     continue;
115034                                 }
115035                                 var typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log);
115036                                 if (!typingFile) {
115037                                     this.missingTypingsSet.add(packageName);
115038                                     continue;
115039                                 }
115040                                 var existingTypingFile = this.packageNameToTypingLocation.get(packageName);
115041                                 if (existingTypingFile) {
115042                                     if (existingTypingFile.typingLocation === typingFile) {
115043                                         continue;
115044                                     }
115045                                     if (this.log.isEnabled()) {
115046                                         this.log.writeLine("New typing for package " + packageName + " from '" + typingFile + "' conflicts with existing typing file '" + existingTypingFile + "'");
115047                                     }
115048                                 }
115049                                 if (this.log.isEnabled()) {
115050                                     this.log.writeLine("Adding entry into typings cache: '" + packageName + "' => '" + typingFile + "'");
115051                                 }
115052                                 var info = ts.getProperty(npmLock.dependencies, key);
115053                                 var version_1 = info && info.version;
115054                                 if (!version_1) {
115055                                     continue;
115056                                 }
115057                                 var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) };
115058                                 this.packageNameToTypingLocation.set(packageName, newTyping);
115059                             }
115060                         }
115061                     }
115062                     if (this.log.isEnabled()) {
115063                         this.log.writeLine("Finished processing cache location '" + cacheLocation + "'");
115064                     }
115065                     this.knownCachesSet.add(cacheLocation);
115066                 };
115067                 TypingsInstaller.prototype.filterTypings = function (typingsToInstall) {
115068                     var _this = this;
115069                     return ts.mapDefined(typingsToInstall, function (typing) {
115070                         var typingKey = ts.mangleScopedPackageName(typing);
115071                         if (_this.missingTypingsSet.has(typingKey)) {
115072                             if (_this.log.isEnabled())
115073                                 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' is in missingTypingsSet - skipping...");
115074                             return undefined;
115075                         }
115076                         var validationResult = ts.JsTyping.validatePackageName(typing);
115077                         if (validationResult !== 0 /* Ok */) {
115078                             // add typing name to missing set so we won't process it again
115079                             _this.missingTypingsSet.add(typingKey);
115080                             if (_this.log.isEnabled())
115081                                 _this.log.writeLine(ts.JsTyping.renderPackageNameValidationFailure(validationResult, typing));
115082                             return undefined;
115083                         }
115084                         if (!_this.typesRegistry.has(typingKey)) {
115085                             if (_this.log.isEnabled())
115086                                 _this.log.writeLine("'" + typing + "':: Entry for package '" + typingKey + "' does not exist in local types registry - skipping...");
115087                             return undefined;
115088                         }
115089                         if (_this.packageNameToTypingLocation.get(typingKey) && ts.JsTyping.isTypingUpToDate(_this.packageNameToTypingLocation.get(typingKey), _this.typesRegistry.get(typingKey))) {
115090                             if (_this.log.isEnabled())
115091                                 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' already has an up-to-date typing - skipping...");
115092                             return undefined;
115093                         }
115094                         return typingKey;
115095                     });
115096                 };
115097                 TypingsInstaller.prototype.ensurePackageDirectoryExists = function (directory) {
115098                     var npmConfigPath = ts.combinePaths(directory, "package.json");
115099                     if (this.log.isEnabled()) {
115100                         this.log.writeLine("Npm config file: " + npmConfigPath);
115101                     }
115102                     if (!this.installTypingHost.fileExists(npmConfigPath)) {
115103                         if (this.log.isEnabled()) {
115104                             this.log.writeLine("Npm config file: '" + npmConfigPath + "' is missing, creating new one...");
115105                         }
115106                         this.ensureDirectoryExists(directory, this.installTypingHost);
115107                         this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }');
115108                     }
115109                 };
115110                 TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) {
115111                     var _this = this;
115112                     if (this.log.isEnabled()) {
115113                         this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall));
115114                     }
115115                     var filteredTypings = this.filterTypings(typingsToInstall);
115116                     if (filteredTypings.length === 0) {
115117                         if (this.log.isEnabled()) {
115118                             this.log.writeLine("All typings are known to be missing or invalid - no need to install more typings");
115119                         }
115120                         this.sendResponse(this.createSetTypings(req, currentlyCachedTypings));
115121                         return;
115122                     }
115123                     this.ensurePackageDirectoryExists(cachePath);
115124                     var requestId = this.installRunCount;
115125                     this.installRunCount++;
115126                     // send progress event
115127                     this.sendResponse({
115128                         kind: server.EventBeginInstallTypes,
115129                         eventId: requestId,
115130                         // qualified explicitly to prevent occasional shadowing
115131                         // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
115132                         typingsInstallerVersion: ts.version,
115133                         projectName: req.projectName
115134                     });
115135                     var scopedTypings = filteredTypings.map(typingsName);
115136                     this.installTypingsAsync(requestId, scopedTypings, cachePath, function (ok) {
115137                         try {
115138                             if (!ok) {
115139                                 if (_this.log.isEnabled()) {
115140                                     _this.log.writeLine("install request failed, marking packages as missing to prevent repeated requests: " + JSON.stringify(filteredTypings));
115141                                 }
115142                                 for (var _i = 0, filteredTypings_1 = filteredTypings; _i < filteredTypings_1.length; _i++) {
115143                                     var typing = filteredTypings_1[_i];
115144                                     _this.missingTypingsSet.add(typing);
115145                                 }
115146                                 return;
115147                             }
115148                             // TODO: watch project directory
115149                             if (_this.log.isEnabled()) {
115150                                 _this.log.writeLine("Installed typings " + JSON.stringify(scopedTypings));
115151                             }
115152                             var installedTypingFiles = [];
115153                             for (var _a = 0, filteredTypings_2 = filteredTypings; _a < filteredTypings_2.length; _a++) {
115154                                 var packageName = filteredTypings_2[_a];
115155                                 var typingFile = typingToFileName(cachePath, packageName, _this.installTypingHost, _this.log);
115156                                 if (!typingFile) {
115157                                     _this.missingTypingsSet.add(packageName);
115158                                     continue;
115159                                 }
115160                                 // packageName is guaranteed to exist in typesRegistry by filterTypings
115161                                 var distTags = _this.typesRegistry.get(packageName);
115162                                 var newVersion = new ts.Version(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]);
115163                                 var newTyping = { typingLocation: typingFile, version: newVersion };
115164                                 _this.packageNameToTypingLocation.set(packageName, newTyping);
115165                                 installedTypingFiles.push(typingFile);
115166                             }
115167                             if (_this.log.isEnabled()) {
115168                                 _this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles));
115169                             }
115170                             _this.sendResponse(_this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles)));
115171                         }
115172                         finally {
115173                             var response = {
115174                                 kind: server.EventEndInstallTypes,
115175                                 eventId: requestId,
115176                                 projectName: req.projectName,
115177                                 packagesToInstall: scopedTypings,
115178                                 installSuccess: ok,
115179                                 // qualified explicitly to prevent occasional shadowing
115180                                 // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
115181                                 typingsInstallerVersion: ts.version
115182                             };
115183                             _this.sendResponse(response);
115184                         }
115185                     });
115186                 };
115187                 TypingsInstaller.prototype.ensureDirectoryExists = function (directory, host) {
115188                     var directoryName = ts.getDirectoryPath(directory);
115189                     if (!host.directoryExists(directoryName)) {
115190                         this.ensureDirectoryExists(directoryName, host);
115191                     }
115192                     if (!host.directoryExists(directory)) {
115193                         host.createDirectory(directory);
115194                     }
115195                 };
115196                 TypingsInstaller.prototype.watchFiles = function (projectName, files, projectRootPath, options) {
115197                     var _this = this;
115198                     if (!files.length) {
115199                         // shut down existing watchers
115200                         this.closeWatchers(projectName);
115201                         return;
115202                     }
115203                     var watchers = this.projectWatchers.get(projectName);
115204                     var toRemove = new ts.Map();
115205                     if (!watchers) {
115206                         watchers = new ts.Map();
115207                         this.projectWatchers.set(projectName, watchers);
115208                     }
115209                     else {
115210                         ts.copyEntries(watchers, toRemove);
115211                     }
115212                     // handler should be invoked once for the entire set of files since it will trigger full rediscovery of typings
115213                     watchers.isInvoked = false;
115214                     var isLoggingEnabled = this.log.isEnabled();
115215                     var createProjectWatcher = function (path, projectWatcherType) {
115216                         var canonicalPath = _this.toCanonicalFileName(path);
115217                         toRemove.delete(canonicalPath);
115218                         if (watchers.has(canonicalPath)) {
115219                             return;
115220                         }
115221                         if (isLoggingEnabled) {
115222                             _this.log.writeLine(projectWatcherType + ":: Added:: WatchInfo: " + path);
115223                         }
115224                         var watcher = projectWatcherType === "FileWatcher" /* FileWatcher */ ?
115225                             _this.watchFactory.watchFile(path, function () {
115226                                 if (!watchers.isInvoked) {
115227                                     watchers.isInvoked = true;
115228                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
115229                                 }
115230                             }, ts.PollingInterval.High, options, projectName, watchers) :
115231                             _this.watchFactory.watchDirectory(path, function (f) {
115232                                 if (watchers.isInvoked || !ts.fileExtensionIs(f, ".json" /* Json */)) {
115233                                     return;
115234                                 }
115235                                 if (isPackageOrBowerJson(f, _this.installTypingHost.useCaseSensitiveFileNames) &&
115236                                     !sameFiles(f, _this.globalCachePackageJsonPath, _this.installTypingHost.useCaseSensitiveFileNames)) {
115237                                     watchers.isInvoked = true;
115238                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
115239                                 }
115240                             }, 1 /* Recursive */, options, projectName, watchers);
115241                         watchers.set(canonicalPath, isLoggingEnabled ? {
115242                             close: function () {
115243                                 _this.log.writeLine(projectWatcherType + ":: Closed:: WatchInfo: " + path);
115244                                 watcher.close();
115245                             }
115246                         } : watcher);
115247                     };
115248                     // Create watches from list of files
115249                     for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
115250                         var file = files_1[_i];
115251                         if (file.endsWith("/package.json") || file.endsWith("/bower.json")) {
115252                             // package.json or bower.json exists, watch the file to detect changes and update typings
115253                             createProjectWatcher(file, "FileWatcher" /* FileWatcher */);
115254                             continue;
115255                         }
115256                         // path in projectRoot, watch project root
115257                         if (ts.containsPath(projectRootPath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
115258                             var subDirectory = file.indexOf(ts.directorySeparator, projectRootPath.length + 1);
115259                             if (subDirectory !== -1) {
115260                                 // Watch subDirectory
115261                                 createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */);
115262                             }
115263                             else {
115264                                 // Watch the directory itself
115265                                 createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
115266                             }
115267                             continue;
115268                         }
115269                         // path in global cache, watch global cache
115270                         if (ts.containsPath(this.globalCachePath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
115271                             createProjectWatcher(this.globalCachePath, "DirectoryWatcher" /* DirectoryWatcher */);
115272                             continue;
115273                         }
115274                         // watch node_modules or bower_components
115275                         createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
115276                     }
115277                     // Remove unused watches
115278                     toRemove.forEach(function (watch, path) {
115279                         watch.close();
115280                         watchers.delete(path);
115281                     });
115282                 };
115283                 TypingsInstaller.prototype.createSetTypings = function (request, typings) {
115284                     return {
115285                         projectName: request.projectName,
115286                         typeAcquisition: request.typeAcquisition,
115287                         compilerOptions: request.compilerOptions,
115288                         typings: typings,
115289                         unresolvedImports: request.unresolvedImports,
115290                         kind: server.ActionSet
115291                     };
115292                 };
115293                 TypingsInstaller.prototype.installTypingsAsync = function (requestId, packageNames, cwd, onRequestCompleted) {
115294                     this.pendingRunRequests.unshift({ requestId: requestId, packageNames: packageNames, cwd: cwd, onRequestCompleted: onRequestCompleted });
115295                     this.executeWithThrottling();
115296                 };
115297                 TypingsInstaller.prototype.executeWithThrottling = function () {
115298                     var _this = this;
115299                     var _loop_1 = function () {
115300                         this_1.inFlightRequestCount++;
115301                         var request = this_1.pendingRunRequests.pop();
115302                         this_1.installWorker(request.requestId, request.packageNames, request.cwd, function (ok) {
115303                             _this.inFlightRequestCount--;
115304                             request.onRequestCompleted(ok);
115305                             _this.executeWithThrottling();
115306                         });
115307                     };
115308                     var this_1 = this;
115309                     while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) {
115310                         _loop_1();
115311                     }
115312                 };
115313                 return TypingsInstaller;
115314             }());
115315             typingsInstaller.TypingsInstaller = TypingsInstaller;
115316             /* @internal */
115317             function typingsName(packageName) {
115318                 return "@types/" + packageName + "@ts" + ts.versionMajorMinor;
115319             }
115320             typingsInstaller.typingsName = typingsName;
115321         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
115322     })(server = ts.server || (ts.server = {}));
115323 })(ts || (ts = {}));
115324 var ts;
115325 (function (ts) {
115326     var server;
115327     (function (server) {
115328         var typingsInstaller;
115329         (function (typingsInstaller) {
115330             var fs = require("fs");
115331             var path = require("path");
115332             var FileLog = (function () {
115333                 function FileLog(logFile) {
115334                     var _this = this;
115335                     this.logFile = logFile;
115336                     this.isEnabled = function () {
115337                         return typeof _this.logFile === "string";
115338                     };
115339                     this.writeLine = function (text) {
115340                         if (typeof _this.logFile !== "string")
115341                             return;
115342                         try {
115343                             fs.appendFileSync(_this.logFile, "[" + server.nowString() + "] " + text + ts.sys.newLine);
115344                         }
115345                         catch (e) {
115346                             _this.logFile = undefined;
115347                         }
115348                     };
115349                 }
115350                 return FileLog;
115351             }());
115352             function getDefaultNPMLocation(processName, validateDefaultNpmLocation, host) {
115353                 if (path.basename(processName).indexOf("node") === 0) {
115354                     var npmPath = path.join(path.dirname(process.argv[0]), "npm");
115355                     if (!validateDefaultNpmLocation) {
115356                         return npmPath;
115357                     }
115358                     if (host.fileExists(npmPath)) {
115359                         return "\"" + npmPath + "\"";
115360                     }
115361                 }
115362                 return "npm";
115363             }
115364             function loadTypesRegistryFile(typesRegistryFilePath, host, log) {
115365                 if (!host.fileExists(typesRegistryFilePath)) {
115366                     if (log.isEnabled()) {
115367                         log.writeLine("Types registry file '" + typesRegistryFilePath + "' does not exist");
115368                     }
115369                     return new ts.Map();
115370                 }
115371                 try {
115372                     var content = JSON.parse(host.readFile(typesRegistryFilePath));
115373                     return new ts.Map(ts.getEntries(content.entries));
115374                 }
115375                 catch (e) {
115376                     if (log.isEnabled()) {
115377                         log.writeLine("Error when loading types registry file '" + typesRegistryFilePath + "': " + e.message + ", " + e.stack);
115378                     }
115379                     return new ts.Map();
115380                 }
115381             }
115382             var typesRegistryPackageName = "types-registry";
115383             function getTypesRegistryFileLocation(globalTypingsCacheLocation) {
115384                 return ts.combinePaths(ts.normalizeSlashes(globalTypingsCacheLocation), "node_modules/" + typesRegistryPackageName + "/index.json");
115385             }
115386             var NodeTypingsInstaller = (function (_super) {
115387                 __extends(NodeTypingsInstaller, _super);
115388                 function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, throttleLimit, log) {
115389                     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;
115390                     _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation, _this.installTypingHost);
115391                     if (ts.stringContains(_this.npmPath, " ") && _this.npmPath[0] !== "\"") {
115392                         _this.npmPath = "\"" + _this.npmPath + "\"";
115393                     }
115394                     if (_this.log.isEnabled()) {
115395                         _this.log.writeLine("Process id: " + process.pid);
115396                         _this.log.writeLine("NPM location: " + _this.npmPath + " (explicit '" + server.Arguments.NpmLocation + "' " + (npmLocation === undefined ? "not " : "") + " provided)");
115397                         _this.log.writeLine("validateDefaultNpmLocation: " + validateDefaultNpmLocation);
115398                     }
115399                     (_this.nodeExecSync = require("child_process").execSync);
115400                     _this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
115401                     try {
115402                         if (_this.log.isEnabled()) {
115403                             _this.log.writeLine("Updating " + typesRegistryPackageName + " npm package...");
115404                         }
115405                         _this.execSyncAndLog(_this.npmPath + " install --ignore-scripts " + typesRegistryPackageName + "@" + _this.latestDistTag, { cwd: globalTypingsCacheLocation });
115406                         if (_this.log.isEnabled()) {
115407                             _this.log.writeLine("Updated " + typesRegistryPackageName + " npm package");
115408                         }
115409                     }
115410                     catch (e) {
115411                         if (_this.log.isEnabled()) {
115412                             _this.log.writeLine("Error updating " + typesRegistryPackageName + " package: " + e.message);
115413                         }
115414                         _this.delayedInitializationError = {
115415                             kind: "event::initializationFailed",
115416                             message: e.message,
115417                             stack: e.stack,
115418                         };
115419                     }
115420                     _this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), _this.installTypingHost, _this.log);
115421                     return _this;
115422                 }
115423                 NodeTypingsInstaller.prototype.listen = function () {
115424                     var _this = this;
115425                     process.on("message", function (req) {
115426                         if (_this.delayedInitializationError) {
115427                             _this.sendResponse(_this.delayedInitializationError);
115428                             _this.delayedInitializationError = undefined;
115429                         }
115430                         switch (req.kind) {
115431                             case "discover":
115432                                 _this.install(req);
115433                                 break;
115434                             case "closeProject":
115435                                 _this.closeProject(req);
115436                                 break;
115437                             case "typesRegistry": {
115438                                 var typesRegistry_1 = {};
115439                                 _this.typesRegistry.forEach(function (value, key) {
115440                                     typesRegistry_1[key] = value;
115441                                 });
115442                                 var response = { kind: server.EventTypesRegistry, typesRegistry: typesRegistry_1 };
115443                                 _this.sendResponse(response);
115444                                 break;
115445                             }
115446                             case "installPackage": {
115447                                 var fileName = req.fileName, packageName_1 = req.packageName, projectName_1 = req.projectName, projectRootPath = req.projectRootPath;
115448                                 var cwd = getDirectoryOfPackageJson(fileName, _this.installTypingHost) || projectRootPath;
115449                                 if (cwd) {
115450                                     _this.installWorker(-1, [packageName_1], cwd, function (success) {
115451                                         var message = success ? "Package " + packageName_1 + " installed." : "There was an error installing " + packageName_1 + ".";
115452                                         var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: success, message: message };
115453                                         _this.sendResponse(response);
115454                                     });
115455                                 }
115456                                 else {
115457                                     var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: false, message: "Could not determine a project root path." };
115458                                     _this.sendResponse(response);
115459                                 }
115460                                 break;
115461                             }
115462                             default:
115463                                 ts.Debug.assertNever(req);
115464                         }
115465                     });
115466                 };
115467                 NodeTypingsInstaller.prototype.sendResponse = function (response) {
115468                     if (this.log.isEnabled()) {
115469                         this.log.writeLine("Sending response:\n    " + JSON.stringify(response));
115470                     }
115471                     process.send(response);
115472                     if (this.log.isEnabled()) {
115473                         this.log.writeLine("Response has been sent.");
115474                     }
115475                 };
115476                 NodeTypingsInstaller.prototype.installWorker = function (requestId, packageNames, cwd, onRequestCompleted) {
115477                     var _this = this;
115478                     if (this.log.isEnabled()) {
115479                         this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(packageNames) + "'.");
115480                     }
115481                     var start = Date.now();
115482                     var hasError = typingsInstaller.installNpmPackages(this.npmPath, ts.version, packageNames, function (command) { return _this.execSyncAndLog(command, { cwd: cwd }); });
115483                     if (this.log.isEnabled()) {
115484                         this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms");
115485                     }
115486                     onRequestCompleted(!hasError);
115487                 };
115488                 NodeTypingsInstaller.prototype.execSyncAndLog = function (command, options) {
115489                     if (this.log.isEnabled()) {
115490                         this.log.writeLine("Exec: " + command);
115491                     }
115492                     try {
115493                         var stdout = this.nodeExecSync(command, __assign(__assign({}, options), { encoding: "utf-8" }));
115494                         if (this.log.isEnabled()) {
115495                             this.log.writeLine("    Succeeded. stdout:" + indent(ts.sys.newLine, stdout));
115496                         }
115497                         return false;
115498                     }
115499                     catch (error) {
115500                         var stdout = error.stdout, stderr = error.stderr;
115501                         this.log.writeLine("    Failed. stdout:" + indent(ts.sys.newLine, stdout) + ts.sys.newLine + "    stderr:" + indent(ts.sys.newLine, stderr));
115502                         return true;
115503                     }
115504                 };
115505                 return NodeTypingsInstaller;
115506             }(typingsInstaller.TypingsInstaller));
115507             typingsInstaller.NodeTypingsInstaller = NodeTypingsInstaller;
115508             function getDirectoryOfPackageJson(fileName, host) {
115509                 return ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (directory) {
115510                     if (host.fileExists(ts.combinePaths(directory, "package.json"))) {
115511                         return directory;
115512                     }
115513                 });
115514             }
115515             var logFilePath = server.findArgument(server.Arguments.LogFile);
115516             var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation);
115517             var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation);
115518             var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation);
115519             var npmLocation = server.findArgument(server.Arguments.NpmLocation);
115520             var validateDefaultNpmLocation = server.hasArgument(server.Arguments.ValidateDefaultNpmLocation);
115521             var log = new FileLog(logFilePath);
115522             if (log.isEnabled()) {
115523                 process.on("uncaughtException", function (e) {
115524                     log.writeLine("Unhandled exception: " + e + " at " + e.stack);
115525                 });
115526             }
115527             process.on("disconnect", function () {
115528                 if (log.isEnabled()) {
115529                     log.writeLine("Parent process has exited, shutting down...");
115530                 }
115531                 process.exit(0);
115532             });
115533             var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, 5, log);
115534             installer.listen();
115535             function indent(newline, str) {
115536                 return str && str.length
115537                     ? newline + "    " + str.replace(/\r?\n/, newline + "    ")
115538                     : "";
115539             }
115540         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
115541     })(server = ts.server || (ts.server = {}));
115542 })(ts || (ts = {}));
115543 //# sourceMappingURL=typingsInstaller.js.map